You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_chat_completion_cache.py 5.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import copy
  2. from typing import List, Tuple, Union
  3. import pytest
  4. from autogen_core import InMemoryStore
  5. from autogen_core.models import (
  6. ChatCompletionClient,
  7. CreateResult,
  8. LLMMessage,
  9. SystemMessage,
  10. UserMessage,
  11. )
  12. from autogen_ext.models.cache import CHAT_CACHE_VALUE_TYPE, ChatCompletionCache
  13. from autogen_ext.models.replay import ReplayChatCompletionClient
  14. def get_test_data() -> Tuple[list[str], list[str], SystemMessage, ChatCompletionClient, ChatCompletionCache]:
  15. num_messages = 3
  16. responses = [f"This is dummy message number {i}" for i in range(num_messages)]
  17. prompts = [f"This is dummy prompt number {i}" for i in range(num_messages)]
  18. system_prompt = SystemMessage(content="This is a system prompt")
  19. replay_client = ReplayChatCompletionClient(responses)
  20. replay_client.set_cached_bool_value(False)
  21. store = InMemoryStore[CHAT_CACHE_VALUE_TYPE]()
  22. cached_client = ChatCompletionCache(replay_client, store)
  23. return responses, prompts, system_prompt, replay_client, cached_client
  24. @pytest.mark.asyncio
  25. async def test_cache_basic_with_args() -> None:
  26. responses, prompts, system_prompt, _, cached_client = get_test_data()
  27. response0 = await cached_client.create([system_prompt, UserMessage(content=prompts[0], source="user")])
  28. assert isinstance(response0, CreateResult)
  29. assert not response0.cached
  30. assert response0.content == responses[0]
  31. response1 = await cached_client.create([system_prompt, UserMessage(content=prompts[1], source="user")])
  32. assert not response1.cached
  33. assert response1.content == responses[1]
  34. # Cached output.
  35. response0_cached = await cached_client.create([system_prompt, UserMessage(content=prompts[0], source="user")])
  36. assert isinstance(response0, CreateResult)
  37. assert response0_cached.cached
  38. assert response0_cached.content == responses[0]
  39. # Cache miss if args change.
  40. response2 = await cached_client.create(
  41. [system_prompt, UserMessage(content=prompts[0], source="user")], json_output=True
  42. )
  43. assert isinstance(response2, CreateResult)
  44. assert not response2.cached
  45. assert response2.content == responses[2]
  46. @pytest.mark.asyncio
  47. async def test_cache_model_and_count_api() -> None:
  48. _, prompts, system_prompt, replay_client, cached_client = get_test_data()
  49. assert replay_client.model_info == cached_client.model_info
  50. assert replay_client.capabilities == cached_client.capabilities
  51. messages: List[LLMMessage] = [system_prompt, UserMessage(content=prompts[0], source="user")]
  52. assert replay_client.count_tokens(messages) == cached_client.count_tokens(messages)
  53. assert replay_client.remaining_tokens(messages) == cached_client.remaining_tokens(messages)
  54. @pytest.mark.asyncio
  55. async def test_cache_token_usage() -> None:
  56. responses, prompts, system_prompt, replay_client, cached_client = get_test_data()
  57. response0 = await cached_client.create([system_prompt, UserMessage(content=prompts[0], source="user")])
  58. assert isinstance(response0, CreateResult)
  59. assert not response0.cached
  60. assert response0.content == responses[0]
  61. actual_usage0 = copy.copy(cached_client.actual_usage())
  62. total_usage0 = copy.copy(cached_client.total_usage())
  63. response1 = await cached_client.create([system_prompt, UserMessage(content=prompts[1], source="user")])
  64. assert not response1.cached
  65. assert response1.content == responses[1]
  66. actual_usage1 = copy.copy(cached_client.actual_usage())
  67. total_usage1 = copy.copy(cached_client.total_usage())
  68. assert total_usage1.prompt_tokens > total_usage0.prompt_tokens
  69. assert total_usage1.completion_tokens > total_usage0.completion_tokens
  70. assert actual_usage1.prompt_tokens == actual_usage0.prompt_tokens
  71. assert actual_usage1.completion_tokens == actual_usage0.completion_tokens
  72. # Cached output.
  73. response0_cached = await cached_client.create([system_prompt, UserMessage(content=prompts[0], source="user")])
  74. assert isinstance(response0, CreateResult)
  75. assert response0_cached.cached
  76. assert response0_cached.content == responses[0]
  77. total_usage2 = copy.copy(cached_client.total_usage())
  78. assert total_usage2.prompt_tokens == total_usage1.prompt_tokens
  79. assert total_usage2.completion_tokens == total_usage1.completion_tokens
  80. assert cached_client.actual_usage() == replay_client.actual_usage()
  81. assert cached_client.total_usage() == replay_client.total_usage()
  82. @pytest.mark.asyncio
  83. async def test_cache_create_stream() -> None:
  84. _, prompts, system_prompt, _, cached_client = get_test_data()
  85. original_streamed_results: List[Union[str, CreateResult]] = []
  86. async for completion in cached_client.create_stream(
  87. [system_prompt, UserMessage(content=prompts[0], source="user")]
  88. ):
  89. original_streamed_results.append(completion)
  90. total_usage0 = copy.copy(cached_client.total_usage())
  91. cached_completion_results: List[Union[str, CreateResult]] = []
  92. async for completion in cached_client.create_stream(
  93. [system_prompt, UserMessage(content=prompts[0], source="user")]
  94. ):
  95. cached_completion_results.append(completion)
  96. total_usage1 = copy.copy(cached_client.total_usage())
  97. assert total_usage1.prompt_tokens == total_usage0.prompt_tokens
  98. assert total_usage1.completion_tokens == total_usage0.completion_tokens
  99. for original, cached in zip(original_streamed_results, cached_completion_results, strict=False):
  100. if isinstance(original, str):
  101. assert original == cached
  102. elif isinstance(original, CreateResult) and isinstance(cached, CreateResult):
  103. assert original.content == cached.content
  104. assert cached.cached
  105. assert not original.cached
  106. else:
  107. raise ValueError(f"Unexpected types : {type(original)} and {type(cached)}")