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_openai_model_client.py 64 kB

feat: Add thought process handling in tool calls and expose ThoughtEvent through stream in AgentChat (#5500) Resolves #5192 Test ```python import asyncio import os from random import randint from typing import List from autogen_core.tools import BaseTool, FunctionTool from autogen_ext.models.openai import OpenAIChatCompletionClient from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.ui import Console async def get_current_time(city: str) -> str: return f"The current time in {city} is {randint(0, 23)}:{randint(0, 59)}." tools: List[BaseTool] = [ FunctionTool( get_current_time, name="get_current_time", description="Get current time for a city.", ), ] model_client = OpenAIChatCompletionClient( model="anthropic/claude-3.5-haiku-20241022", base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], model_info={ "family": "claude-3.5-haiku", "function_calling": True, "vision": False, "json_output": False, } ) agent = AssistantAgent( name="Agent", model_client=model_client, tools=tools, system_message= "You are an assistant with some tools that can be used to answer some questions", ) async def main() -> None: await Console(agent.run_stream(task="What is current time of Paris and Toronto?")) asyncio.run(main()) ``` ``` ---------- user ---------- What is current time of Paris and Toronto? ---------- Agent ---------- I'll help you find the current time for Paris and Toronto by using the get_current_time function for each city. ---------- Agent ---------- [FunctionCall(id='toolu_01NwP3fNAwcYKn1x656Dq9xW', arguments='{"city": "Paris"}', name='get_current_time'), FunctionCall(id='toolu_018d4cWSy3TxXhjgmLYFrfRt', arguments='{"city": "Toronto"}', name='get_current_time')] ---------- Agent ---------- [FunctionExecutionResult(content='The current time in Paris is 1:10.', call_id='toolu_01NwP3fNAwcYKn1x656Dq9xW', is_error=False), FunctionExecutionResult(content='The current time in Toronto is 7:28.', call_id='toolu_018d4cWSy3TxXhjgmLYFrfRt', is_error=False)] ---------- Agent ---------- The current time in Paris is 1:10. The current time in Toronto is 7:28. ``` --------- Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
1 year ago
fix: Update SKChatCompletionAdapter message conversion (#5749) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> The PR introduces two changes. The first change is adding a name attribute to `FunctionExecutionResult`. The motivation is that semantic kernel requires it for their function result interface and it seemed like a easy modification as `FunctionExecutionResult` is always created in the context of a `FunctionCall` which will contain the name. I'm unsure if there was a motivation to keep it out but this change makes it easier to trace which tool the result refers to and also increases api compatibility with SK. The second change is an update to how messages are mapped from autogen to semantic kernel, which includes an update/fix in the processing of function results. ## Related issue number <!-- For example: "Closes #1234" --> Related to #5675 but wont fix the underlying issue of anthropic requiring tools during AssistantAgent reflection. ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed. --------- Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
1 year ago
feat: Add thought process handling in tool calls and expose ThoughtEvent through stream in AgentChat (#5500) Resolves #5192 Test ```python import asyncio import os from random import randint from typing import List from autogen_core.tools import BaseTool, FunctionTool from autogen_ext.models.openai import OpenAIChatCompletionClient from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.ui import Console async def get_current_time(city: str) -> str: return f"The current time in {city} is {randint(0, 23)}:{randint(0, 59)}." tools: List[BaseTool] = [ FunctionTool( get_current_time, name="get_current_time", description="Get current time for a city.", ), ] model_client = OpenAIChatCompletionClient( model="anthropic/claude-3.5-haiku-20241022", base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], model_info={ "family": "claude-3.5-haiku", "function_calling": True, "vision": False, "json_output": False, } ) agent = AssistantAgent( name="Agent", model_client=model_client, tools=tools, system_message= "You are an assistant with some tools that can be used to answer some questions", ) async def main() -> None: await Console(agent.run_stream(task="What is current time of Paris and Toronto?")) asyncio.run(main()) ``` ``` ---------- user ---------- What is current time of Paris and Toronto? ---------- Agent ---------- I'll help you find the current time for Paris and Toronto by using the get_current_time function for each city. ---------- Agent ---------- [FunctionCall(id='toolu_01NwP3fNAwcYKn1x656Dq9xW', arguments='{"city": "Paris"}', name='get_current_time'), FunctionCall(id='toolu_018d4cWSy3TxXhjgmLYFrfRt', arguments='{"city": "Toronto"}', name='get_current_time')] ---------- Agent ---------- [FunctionExecutionResult(content='The current time in Paris is 1:10.', call_id='toolu_01NwP3fNAwcYKn1x656Dq9xW', is_error=False), FunctionExecutionResult(content='The current time in Toronto is 7:28.', call_id='toolu_018d4cWSy3TxXhjgmLYFrfRt', is_error=False)] ---------- Agent ---------- The current time in Paris is 1:10. The current time in Toronto is 7:28. ``` --------- Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
1 year ago
feat: Add thought process handling in tool calls and expose ThoughtEvent through stream in AgentChat (#5500) Resolves #5192 Test ```python import asyncio import os from random import randint from typing import List from autogen_core.tools import BaseTool, FunctionTool from autogen_ext.models.openai import OpenAIChatCompletionClient from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.ui import Console async def get_current_time(city: str) -> str: return f"The current time in {city} is {randint(0, 23)}:{randint(0, 59)}." tools: List[BaseTool] = [ FunctionTool( get_current_time, name="get_current_time", description="Get current time for a city.", ), ] model_client = OpenAIChatCompletionClient( model="anthropic/claude-3.5-haiku-20241022", base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], model_info={ "family": "claude-3.5-haiku", "function_calling": True, "vision": False, "json_output": False, } ) agent = AssistantAgent( name="Agent", model_client=model_client, tools=tools, system_message= "You are an assistant with some tools that can be used to answer some questions", ) async def main() -> None: await Console(agent.run_stream(task="What is current time of Paris and Toronto?")) asyncio.run(main()) ``` ``` ---------- user ---------- What is current time of Paris and Toronto? ---------- Agent ---------- I'll help you find the current time for Paris and Toronto by using the get_current_time function for each city. ---------- Agent ---------- [FunctionCall(id='toolu_01NwP3fNAwcYKn1x656Dq9xW', arguments='{"city": "Paris"}', name='get_current_time'), FunctionCall(id='toolu_018d4cWSy3TxXhjgmLYFrfRt', arguments='{"city": "Toronto"}', name='get_current_time')] ---------- Agent ---------- [FunctionExecutionResult(content='The current time in Paris is 1:10.', call_id='toolu_01NwP3fNAwcYKn1x656Dq9xW', is_error=False), FunctionExecutionResult(content='The current time in Toronto is 7:28.', call_id='toolu_018d4cWSy3TxXhjgmLYFrfRt', is_error=False)] ---------- Agent ---------- The current time in Paris is 1:10. The current time in Toronto is 7:28. ``` --------- Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
1 year ago
feat: Add thought process handling in tool calls and expose ThoughtEvent through stream in AgentChat (#5500) Resolves #5192 Test ```python import asyncio import os from random import randint from typing import List from autogen_core.tools import BaseTool, FunctionTool from autogen_ext.models.openai import OpenAIChatCompletionClient from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.ui import Console async def get_current_time(city: str) -> str: return f"The current time in {city} is {randint(0, 23)}:{randint(0, 59)}." tools: List[BaseTool] = [ FunctionTool( get_current_time, name="get_current_time", description="Get current time for a city.", ), ] model_client = OpenAIChatCompletionClient( model="anthropic/claude-3.5-haiku-20241022", base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], model_info={ "family": "claude-3.5-haiku", "function_calling": True, "vision": False, "json_output": False, } ) agent = AssistantAgent( name="Agent", model_client=model_client, tools=tools, system_message= "You are an assistant with some tools that can be used to answer some questions", ) async def main() -> None: await Console(agent.run_stream(task="What is current time of Paris and Toronto?")) asyncio.run(main()) ``` ``` ---------- user ---------- What is current time of Paris and Toronto? ---------- Agent ---------- I'll help you find the current time for Paris and Toronto by using the get_current_time function for each city. ---------- Agent ---------- [FunctionCall(id='toolu_01NwP3fNAwcYKn1x656Dq9xW', arguments='{"city": "Paris"}', name='get_current_time'), FunctionCall(id='toolu_018d4cWSy3TxXhjgmLYFrfRt', arguments='{"city": "Toronto"}', name='get_current_time')] ---------- Agent ---------- [FunctionExecutionResult(content='The current time in Paris is 1:10.', call_id='toolu_01NwP3fNAwcYKn1x656Dq9xW', is_error=False), FunctionExecutionResult(content='The current time in Toronto is 7:28.', call_id='toolu_018d4cWSy3TxXhjgmLYFrfRt', is_error=False)] ---------- Agent ---------- The current time in Paris is 1:10. The current time in Toronto is 7:28. ``` --------- Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
1 year ago
fix: Update SKChatCompletionAdapter message conversion (#5749) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> The PR introduces two changes. The first change is adding a name attribute to `FunctionExecutionResult`. The motivation is that semantic kernel requires it for their function result interface and it seemed like a easy modification as `FunctionExecutionResult` is always created in the context of a `FunctionCall` which will contain the name. I'm unsure if there was a motivation to keep it out but this change makes it easier to trace which tool the result refers to and also increases api compatibility with SK. The second change is an update to how messages are mapped from autogen to semantic kernel, which includes an update/fix in the processing of function results. ## Related issue number <!-- For example: "Closes #1234" --> Related to #5675 but wont fix the underlying issue of anthropic requiring tools during AssistantAgent reflection. ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed. --------- Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
1 year ago
fix: Update SKChatCompletionAdapter message conversion (#5749) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> The PR introduces two changes. The first change is adding a name attribute to `FunctionExecutionResult`. The motivation is that semantic kernel requires it for their function result interface and it seemed like a easy modification as `FunctionExecutionResult` is always created in the context of a `FunctionCall` which will contain the name. I'm unsure if there was a motivation to keep it out but this change makes it easier to trace which tool the result refers to and also increases api compatibility with SK. The second change is an update to how messages are mapped from autogen to semantic kernel, which includes an update/fix in the processing of function results. ## Related issue number <!-- For example: "Closes #1234" --> Related to #5675 but wont fix the underlying issue of anthropic requiring tools during AssistantAgent reflection. ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed. --------- Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
1 year ago
fix: Update SKChatCompletionAdapter message conversion (#5749) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> The PR introduces two changes. The first change is adding a name attribute to `FunctionExecutionResult`. The motivation is that semantic kernel requires it for their function result interface and it seemed like a easy modification as `FunctionExecutionResult` is always created in the context of a `FunctionCall` which will contain the name. I'm unsure if there was a motivation to keep it out but this change makes it easier to trace which tool the result refers to and also increases api compatibility with SK. The second change is an update to how messages are mapped from autogen to semantic kernel, which includes an update/fix in the processing of function results. ## Related issue number <!-- For example: "Closes #1234" --> Related to #5675 but wont fix the underlying issue of anthropic requiring tools during AssistantAgent reflection. ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed. --------- Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
1 year ago
fix: Update SKChatCompletionAdapter message conversion (#5749) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> The PR introduces two changes. The first change is adding a name attribute to `FunctionExecutionResult`. The motivation is that semantic kernel requires it for their function result interface and it seemed like a easy modification as `FunctionExecutionResult` is always created in the context of a `FunctionCall` which will contain the name. I'm unsure if there was a motivation to keep it out but this change makes it easier to trace which tool the result refers to and also increases api compatibility with SK. The second change is an update to how messages are mapped from autogen to semantic kernel, which includes an update/fix in the processing of function results. ## Related issue number <!-- For example: "Closes #1234" --> Related to #5675 but wont fix the underlying issue of anthropic requiring tools during AssistantAgent reflection. ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed. --------- Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. from typing import Annotated, Any, AsyncGenerator, Dict, List, Literal, Tuple, TypeVar
  6. from unittest.mock import MagicMock
  7. import httpx
  8. import pytest
  9. from autogen_core import CancellationToken, FunctionCall, Image
  10. from autogen_core.models import (
  11. AssistantMessage,
  12. CreateResult,
  13. FunctionExecutionResult,
  14. FunctionExecutionResultMessage,
  15. LLMMessage,
  16. ModelInfo,
  17. RequestUsage,
  18. SystemMessage,
  19. UserMessage,
  20. )
  21. from autogen_core.models._model_client import ModelFamily
  22. from autogen_core.tools import BaseTool, FunctionTool
  23. from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, OpenAIChatCompletionClient
  24. from autogen_ext.models.openai._model_info import resolve_model
  25. from autogen_ext.models.openai._openai_client import calculate_vision_tokens, convert_tools, to_oai_type
  26. from openai.resources.beta.chat.completions import ( # type: ignore
  27. AsyncChatCompletionStreamManager as BetaAsyncChatCompletionStreamManager, # type: ignore
  28. )
  29. # type: ignore
  30. from openai.resources.beta.chat.completions import (
  31. AsyncCompletions as BetaAsyncCompletions,
  32. )
  33. from openai.resources.chat.completions import AsyncCompletions
  34. from openai.types.chat.chat_completion import ChatCompletion, Choice
  35. from openai.types.chat.chat_completion_chunk import (
  36. ChatCompletionChunk,
  37. ChoiceDelta,
  38. ChoiceDeltaToolCall,
  39. ChoiceDeltaToolCallFunction,
  40. )
  41. from openai.types.chat.chat_completion_chunk import (
  42. Choice as ChunkChoice,
  43. )
  44. from openai.types.chat.chat_completion_message import ChatCompletionMessage
  45. from openai.types.chat.chat_completion_message_tool_call import (
  46. ChatCompletionMessageToolCall,
  47. Function,
  48. )
  49. from openai.types.chat.parsed_chat_completion import ParsedChatCompletion, ParsedChatCompletionMessage, ParsedChoice
  50. from openai.types.chat.parsed_function_tool_call import ParsedFunction, ParsedFunctionToolCall
  51. from openai.types.completion_usage import CompletionUsage
  52. from pydantic import BaseModel, Field
  53. ResponseFormatT = TypeVar("ResponseFormatT", bound=BaseModel)
  54. def _pass_function(input: str) -> str:
  55. return "pass"
  56. async def _fail_function(input: str) -> str:
  57. return "fail"
  58. async def _echo_function(input: str) -> str:
  59. return input
  60. class MyResult(BaseModel):
  61. result: str = Field(description="The other description.")
  62. class MyArgs(BaseModel):
  63. query: str = Field(description="The description.")
  64. class MockChunkDefinition(BaseModel):
  65. # defining elements for diffentiating mocking chunks
  66. chunk_choice: ChunkChoice
  67. usage: CompletionUsage | None
  68. class MockChunkEvent(BaseModel):
  69. type: Literal["chunk"]
  70. chunk: ChatCompletionChunk
  71. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  72. model = resolve_model(kwargs.get("model", "gpt-4o"))
  73. mock_chunks_content = ["Hello", " Another Hello", " Yet Another Hello"]
  74. # The openai api implementations (OpenAI and Litellm) stream chunks of tokens
  75. # with content as string, and then at the end a token with stop set and finally if
  76. # usage requested with `"stream_options": {"include_usage": True}` a chunk with the usage data
  77. mock_chunks = [
  78. # generate the list of mock chunk content
  79. MockChunkDefinition(
  80. chunk_choice=ChunkChoice(
  81. finish_reason=None,
  82. index=0,
  83. delta=ChoiceDelta(
  84. content=mock_chunk_content,
  85. role="assistant",
  86. ),
  87. ),
  88. usage=None,
  89. )
  90. for mock_chunk_content in mock_chunks_content
  91. ] + [
  92. # generate the stop chunk
  93. MockChunkDefinition(
  94. chunk_choice=ChunkChoice(
  95. finish_reason="stop",
  96. index=0,
  97. delta=ChoiceDelta(
  98. content=None,
  99. role="assistant",
  100. ),
  101. ),
  102. usage=None,
  103. )
  104. ]
  105. # generate the usage chunk if configured
  106. if kwargs.get("stream_options", {}).get("include_usage") is True:
  107. mock_chunks = mock_chunks + [
  108. # ---- API differences
  109. # OPENAI API does NOT create a choice
  110. # LITELLM (proxy) DOES create a choice
  111. # Not simulating all the API options, just implementing the LITELLM variant
  112. MockChunkDefinition(
  113. chunk_choice=ChunkChoice(
  114. finish_reason=None,
  115. index=0,
  116. delta=ChoiceDelta(
  117. content=None,
  118. role="assistant",
  119. ),
  120. ),
  121. usage=CompletionUsage(prompt_tokens=3, completion_tokens=3, total_tokens=6),
  122. )
  123. ]
  124. elif kwargs.get("stream_options", {}).get("include_usage") is False:
  125. pass
  126. else:
  127. pass
  128. for mock_chunk in mock_chunks:
  129. await asyncio.sleep(0.1)
  130. yield ChatCompletionChunk(
  131. id="id",
  132. choices=[mock_chunk.chunk_choice],
  133. created=0,
  134. model=model,
  135. object="chat.completion.chunk",
  136. usage=mock_chunk.usage,
  137. )
  138. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  139. stream = kwargs.get("stream", False)
  140. model = resolve_model(kwargs.get("model", "gpt-4o"))
  141. if not stream:
  142. await asyncio.sleep(0.1)
  143. return ChatCompletion(
  144. id="id",
  145. choices=[
  146. Choice(finish_reason="stop", index=0, message=ChatCompletionMessage(content="Hello", role="assistant"))
  147. ],
  148. created=0,
  149. model=model,
  150. object="chat.completion",
  151. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  152. )
  153. else:
  154. return _mock_create_stream(*args, **kwargs)
  155. @pytest.mark.asyncio
  156. async def test_openai_chat_completion_client() -> None:
  157. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  158. assert client
  159. @pytest.mark.asyncio
  160. async def test_openai_chat_completion_client_with_gemini_model() -> None:
  161. client = OpenAIChatCompletionClient(model="gemini-1.5-flash", api_key="api_key")
  162. assert client
  163. @pytest.mark.asyncio
  164. async def test_openai_chat_completion_client_raise_on_unknown_model() -> None:
  165. with pytest.raises(ValueError, match="model_info is required"):
  166. _ = OpenAIChatCompletionClient(model="unknown", api_key="api_key")
  167. @pytest.mark.asyncio
  168. async def test_custom_model_with_capabilities() -> None:
  169. with pytest.raises(ValueError, match="model_info is required"):
  170. client = OpenAIChatCompletionClient(model="dummy_model", base_url="https://api.dummy.com/v0", api_key="api_key")
  171. client = OpenAIChatCompletionClient(
  172. model="dummy_model",
  173. base_url="https://api.dummy.com/v0",
  174. api_key="api_key",
  175. model_info={"vision": False, "function_calling": False, "json_output": False, "family": ModelFamily.UNKNOWN},
  176. )
  177. assert client
  178. @pytest.mark.asyncio
  179. async def test_azure_openai_chat_completion_client() -> None:
  180. client = AzureOpenAIChatCompletionClient(
  181. azure_deployment="gpt-4o-1",
  182. model="gpt-4o",
  183. api_key="api_key",
  184. api_version="2020-08-04",
  185. azure_endpoint="https://dummy.com",
  186. model_info={"vision": True, "function_calling": True, "json_output": True, "family": ModelFamily.GPT_4O},
  187. )
  188. assert client
  189. @pytest.mark.asyncio
  190. async def test_openai_chat_completion_client_create(
  191. monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
  192. ) -> None:
  193. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  194. with caplog.at_level(logging.INFO):
  195. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  196. result = await client.create(messages=[UserMessage(content="Hello", source="user")])
  197. assert result.content == "Hello"
  198. assert "LLMCall" in caplog.text and "Hello" in caplog.text
  199. @pytest.mark.asyncio
  200. async def test_openai_chat_completion_client_create_stream_with_usage(
  201. monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
  202. ) -> None:
  203. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  204. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  205. chunks: List[str | CreateResult] = []
  206. with caplog.at_level(logging.INFO):
  207. async for chunk in client.create_stream(
  208. messages=[UserMessage(content="Hello", source="user")],
  209. # include_usage not the default of the OPENAI API and must be explicitly set
  210. extra_create_args={"stream_options": {"include_usage": True}},
  211. ):
  212. chunks.append(chunk)
  213. assert "LLMStreamStart" in caplog.text
  214. assert "LLMStreamEnd" in caplog.text
  215. assert chunks[0] == "Hello"
  216. assert chunks[1] == " Another Hello"
  217. assert chunks[2] == " Yet Another Hello"
  218. assert isinstance(chunks[-1], CreateResult)
  219. assert isinstance(chunks[-1].content, str)
  220. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  221. assert chunks[-1].content in caplog.text
  222. assert chunks[-1].usage == RequestUsage(prompt_tokens=3, completion_tokens=3)
  223. @pytest.mark.asyncio
  224. async def test_openai_chat_completion_client_create_stream_no_usage_default(monkeypatch: pytest.MonkeyPatch) -> None:
  225. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  226. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  227. chunks: List[str | CreateResult] = []
  228. async for chunk in client.create_stream(
  229. messages=[UserMessage(content="Hello", source="user")],
  230. # include_usage not the default of the OPENAI APIis ,
  231. # it can be explicitly set
  232. # or just not declared which is the default
  233. # extra_create_args={"stream_options": {"include_usage": False}},
  234. ):
  235. chunks.append(chunk)
  236. assert chunks[0] == "Hello"
  237. assert chunks[1] == " Another Hello"
  238. assert chunks[2] == " Yet Another Hello"
  239. assert isinstance(chunks[-1], CreateResult)
  240. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  241. assert chunks[-1].usage == RequestUsage(prompt_tokens=0, completion_tokens=0)
  242. @pytest.mark.asyncio
  243. async def test_openai_chat_completion_client_create_stream_no_usage_explicit(monkeypatch: pytest.MonkeyPatch) -> None:
  244. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  245. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  246. chunks: List[str | CreateResult] = []
  247. async for chunk in client.create_stream(
  248. messages=[UserMessage(content="Hello", source="user")],
  249. # include_usage is not the default of the OPENAI API ,
  250. # it can be explicitly set
  251. # or just not declared which is the default
  252. extra_create_args={"stream_options": {"include_usage": False}},
  253. ):
  254. chunks.append(chunk)
  255. assert chunks[0] == "Hello"
  256. assert chunks[1] == " Another Hello"
  257. assert chunks[2] == " Yet Another Hello"
  258. assert isinstance(chunks[-1], CreateResult)
  259. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  260. assert chunks[-1].usage == RequestUsage(prompt_tokens=0, completion_tokens=0)
  261. @pytest.mark.asyncio
  262. async def test_openai_chat_completion_client_create_cancel(monkeypatch: pytest.MonkeyPatch) -> None:
  263. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  264. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  265. cancellation_token = CancellationToken()
  266. task = asyncio.create_task(
  267. client.create(messages=[UserMessage(content="Hello", source="user")], cancellation_token=cancellation_token)
  268. )
  269. cancellation_token.cancel()
  270. with pytest.raises(asyncio.CancelledError):
  271. await task
  272. @pytest.mark.asyncio
  273. async def test_openai_chat_completion_client_create_stream_cancel(monkeypatch: pytest.MonkeyPatch) -> None:
  274. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  275. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  276. cancellation_token = CancellationToken()
  277. stream = client.create_stream(
  278. messages=[UserMessage(content="Hello", source="user")], cancellation_token=cancellation_token
  279. )
  280. assert await anext(stream)
  281. cancellation_token.cancel()
  282. with pytest.raises(asyncio.CancelledError):
  283. async for _ in stream:
  284. pass
  285. @pytest.mark.asyncio
  286. async def test_openai_chat_completion_client_count_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
  287. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  288. messages: List[LLMMessage] = [
  289. SystemMessage(content="Hello"),
  290. UserMessage(content="Hello", source="user"),
  291. AssistantMessage(content="Hello", source="assistant"),
  292. UserMessage(
  293. content=[
  294. "str1",
  295. Image.from_base64(
  296. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
  297. ),
  298. ],
  299. source="user",
  300. ),
  301. FunctionExecutionResultMessage(
  302. content=[FunctionExecutionResult(content="Hello", call_id="1", is_error=False, name="tool1")]
  303. ),
  304. ]
  305. def tool1(test: str, test2: str) -> str:
  306. return test + test2
  307. def tool2(test1: int, test2: List[int]) -> str:
  308. return str(test1) + str(test2)
  309. tools = [FunctionTool(tool1, description="example tool 1"), FunctionTool(tool2, description="example tool 2")]
  310. mockcalculate_vision_tokens = MagicMock()
  311. monkeypatch.setattr("autogen_ext.models.openai._openai_client.calculate_vision_tokens", mockcalculate_vision_tokens)
  312. num_tokens = client.count_tokens(messages, tools=tools)
  313. assert num_tokens
  314. # Check that calculate_vision_tokens was called
  315. mockcalculate_vision_tokens.assert_called_once()
  316. remaining_tokens = client.remaining_tokens(messages, tools=tools)
  317. assert remaining_tokens
  318. @pytest.mark.parametrize(
  319. "mock_size, expected_num_tokens",
  320. [
  321. ((1, 1), 255),
  322. ((512, 512), 255),
  323. ((2048, 512), 765),
  324. ((2048, 2048), 765),
  325. ((512, 1024), 425),
  326. ],
  327. )
  328. def test_openai_count_image_tokens(mock_size: Tuple[int, int], expected_num_tokens: int) -> None:
  329. # Step 1: Mock the Image class with only the 'image' attribute
  330. mock_image_attr = MagicMock()
  331. mock_image_attr.size = mock_size
  332. mock_image = MagicMock()
  333. mock_image.image = mock_image_attr
  334. # Directly call calculate_vision_tokens and check the result
  335. calculated_tokens = calculate_vision_tokens(mock_image, detail="auto")
  336. assert calculated_tokens == expected_num_tokens
  337. def test_convert_tools_accepts_both_func_tool_and_schema() -> None:
  338. def my_function(arg: str, other: Annotated[int, "int arg"], nonrequired: int = 5) -> MyResult:
  339. return MyResult(result="test")
  340. tool = FunctionTool(my_function, description="Function tool.")
  341. schema = tool.schema
  342. converted_tool_schema = convert_tools([tool, schema])
  343. assert len(converted_tool_schema) == 2
  344. assert converted_tool_schema[0] == converted_tool_schema[1]
  345. def test_convert_tools_accepts_both_tool_and_schema() -> None:
  346. class MyTool(BaseTool[MyArgs, MyResult]):
  347. def __init__(self) -> None:
  348. super().__init__(
  349. args_type=MyArgs,
  350. return_type=MyResult,
  351. name="TestTool",
  352. description="Description of test tool.",
  353. )
  354. async def run(self, args: MyArgs, cancellation_token: CancellationToken) -> MyResult:
  355. return MyResult(result="value")
  356. tool = MyTool()
  357. schema = tool.schema
  358. converted_tool_schema = convert_tools([tool, schema])
  359. assert len(converted_tool_schema) == 2
  360. assert converted_tool_schema[0] == converted_tool_schema[1]
  361. @pytest.mark.asyncio
  362. async def test_structured_output(monkeypatch: pytest.MonkeyPatch) -> None:
  363. class AgentResponse(BaseModel):
  364. thoughts: str
  365. response: Literal["happy", "sad", "neutral"]
  366. model = "gpt-4o-2024-11-20"
  367. async def _mock_parse(*args: Any, **kwargs: Any) -> ParsedChatCompletion[AgentResponse]:
  368. return ParsedChatCompletion(
  369. id="id1",
  370. choices=[
  371. ParsedChoice(
  372. finish_reason="stop",
  373. index=0,
  374. message=ParsedChatCompletionMessage(
  375. content=json.dumps(
  376. {
  377. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  378. "response": "happy",
  379. }
  380. ),
  381. role="assistant",
  382. ),
  383. )
  384. ],
  385. created=0,
  386. model=model,
  387. object="chat.completion",
  388. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  389. )
  390. monkeypatch.setattr(BetaAsyncCompletions, "parse", _mock_parse)
  391. model_client = OpenAIChatCompletionClient(
  392. model=model,
  393. api_key="",
  394. response_format=AgentResponse, # type: ignore
  395. )
  396. # Test that the openai client was called with the correct response format.
  397. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  398. assert isinstance(create_result.content, str)
  399. response = AgentResponse.model_validate(json.loads(create_result.content))
  400. assert (
  401. response.thoughts
  402. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  403. )
  404. assert response.response == "happy"
  405. @pytest.mark.asyncio
  406. async def test_structured_output_with_tool_calls(monkeypatch: pytest.MonkeyPatch) -> None:
  407. class AgentResponse(BaseModel):
  408. thoughts: str
  409. response: Literal["happy", "sad", "neutral"]
  410. model = "gpt-4o-2024-11-20"
  411. async def _mock_parse(*args: Any, **kwargs: Any) -> ParsedChatCompletion[AgentResponse]:
  412. return ParsedChatCompletion(
  413. id="id1",
  414. choices=[
  415. ParsedChoice(
  416. finish_reason="tool_calls",
  417. index=0,
  418. message=ParsedChatCompletionMessage(
  419. content=json.dumps(
  420. {
  421. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  422. "response": "happy",
  423. }
  424. ),
  425. role="assistant",
  426. tool_calls=[
  427. ParsedFunctionToolCall(
  428. id="1",
  429. type="function",
  430. function=ParsedFunction(
  431. name="_pass_function",
  432. arguments=json.dumps({"input": "happy"}),
  433. ),
  434. )
  435. ],
  436. ),
  437. )
  438. ],
  439. created=0,
  440. model=model,
  441. object="chat.completion",
  442. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  443. )
  444. monkeypatch.setattr(BetaAsyncCompletions, "parse", _mock_parse)
  445. model_client = OpenAIChatCompletionClient(
  446. model=model,
  447. api_key="",
  448. response_format=AgentResponse, # type: ignore
  449. )
  450. # Test that the openai client was called with the correct response format.
  451. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  452. assert isinstance(create_result.content, list)
  453. assert len(create_result.content) == 1
  454. assert create_result.content[0] == FunctionCall(
  455. id="1", name="_pass_function", arguments=json.dumps({"input": "happy"})
  456. )
  457. assert isinstance(create_result.thought, str)
  458. response = AgentResponse.model_validate(json.loads(create_result.thought))
  459. assert (
  460. response.thoughts
  461. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  462. )
  463. assert response.response == "happy"
  464. @pytest.mark.asyncio
  465. async def test_structured_output_with_streaming(monkeypatch: pytest.MonkeyPatch) -> None:
  466. class AgentResponse(BaseModel):
  467. thoughts: str
  468. response: Literal["happy", "sad", "neutral"]
  469. raw_content = json.dumps(
  470. {
  471. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  472. "response": "happy",
  473. }
  474. )
  475. chunked_content = [raw_content[i : i + 5] for i in range(0, len(raw_content), 5)]
  476. assert "".join(chunked_content) == raw_content
  477. model = "gpt-4o-2024-11-20"
  478. mock_chunk_events = [
  479. MockChunkEvent(
  480. type="chunk",
  481. chunk=ChatCompletionChunk(
  482. id="id",
  483. choices=[
  484. ChunkChoice(
  485. finish_reason=None,
  486. index=0,
  487. delta=ChoiceDelta(
  488. content=mock_chunk_content,
  489. role="assistant",
  490. ),
  491. )
  492. ],
  493. created=0,
  494. model=model,
  495. object="chat.completion.chunk",
  496. usage=None,
  497. ),
  498. )
  499. for mock_chunk_content in chunked_content
  500. ]
  501. async def _mock_create_stream(*args: Any) -> AsyncGenerator[MockChunkEvent, None]:
  502. async def _stream() -> AsyncGenerator[MockChunkEvent, None]:
  503. for mock_chunk_event in mock_chunk_events:
  504. await asyncio.sleep(0.1)
  505. yield mock_chunk_event
  506. return _stream()
  507. # Mock the context manager __aenter__ method which returns the stream.
  508. monkeypatch.setattr(BetaAsyncChatCompletionStreamManager, "__aenter__", _mock_create_stream)
  509. model_client = OpenAIChatCompletionClient(
  510. model=model,
  511. api_key="",
  512. response_format=AgentResponse, # type: ignore
  513. )
  514. # Test that the openai client was called with the correct response format.
  515. chunks: List[str | CreateResult] = []
  516. async for chunk in model_client.create_stream(messages=[UserMessage(content="I am happy.", source="user")]):
  517. chunks.append(chunk)
  518. assert len(chunks) > 0
  519. assert isinstance(chunks[-1], CreateResult)
  520. assert isinstance(chunks[-1].content, str)
  521. response = AgentResponse.model_validate(json.loads(chunks[-1].content))
  522. assert (
  523. response.thoughts
  524. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  525. )
  526. assert response.response == "happy"
  527. @pytest.mark.asyncio
  528. async def test_structured_output_with_streaming_tool_calls(monkeypatch: pytest.MonkeyPatch) -> None:
  529. class AgentResponse(BaseModel):
  530. thoughts: str
  531. response: Literal["happy", "sad", "neutral"]
  532. raw_content = json.dumps(
  533. {
  534. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  535. "response": "happy",
  536. }
  537. )
  538. chunked_content = [raw_content[i : i + 5] for i in range(0, len(raw_content), 5)]
  539. assert "".join(chunked_content) == raw_content
  540. model = "gpt-4o-2024-11-20"
  541. # generate the list of mock chunk content
  542. mock_chunk_events = [
  543. MockChunkEvent(
  544. type="chunk",
  545. chunk=ChatCompletionChunk(
  546. id="id",
  547. choices=[
  548. ChunkChoice(
  549. finish_reason=None,
  550. index=0,
  551. delta=ChoiceDelta(
  552. content=mock_chunk_content,
  553. role="assistant",
  554. ),
  555. )
  556. ],
  557. created=0,
  558. model=model,
  559. object="chat.completion.chunk",
  560. usage=None,
  561. ),
  562. )
  563. for mock_chunk_content in chunked_content
  564. ]
  565. # add the tool call chunk.
  566. mock_chunk_events += [
  567. MockChunkEvent(
  568. type="chunk",
  569. chunk=ChatCompletionChunk(
  570. id="id",
  571. choices=[
  572. ChunkChoice(
  573. finish_reason="tool_calls",
  574. index=0,
  575. delta=ChoiceDelta(
  576. content=None,
  577. role="assistant",
  578. tool_calls=[
  579. ChoiceDeltaToolCall(
  580. id="1",
  581. index=0,
  582. type="function",
  583. function=ChoiceDeltaToolCallFunction(
  584. name="_pass_function",
  585. arguments=json.dumps({"input": "happy"}),
  586. ),
  587. )
  588. ],
  589. ),
  590. )
  591. ],
  592. created=0,
  593. model=model,
  594. object="chat.completion.chunk",
  595. usage=None,
  596. ),
  597. )
  598. ]
  599. async def _mock_create_stream(*args: Any) -> AsyncGenerator[MockChunkEvent, None]:
  600. async def _stream() -> AsyncGenerator[MockChunkEvent, None]:
  601. for mock_chunk_event in mock_chunk_events:
  602. await asyncio.sleep(0.1)
  603. yield mock_chunk_event
  604. return _stream()
  605. # Mock the context manager __aenter__ method which returns the stream.
  606. monkeypatch.setattr(BetaAsyncChatCompletionStreamManager, "__aenter__", _mock_create_stream)
  607. model_client = OpenAIChatCompletionClient(
  608. model=model,
  609. api_key="",
  610. response_format=AgentResponse, # type: ignore
  611. )
  612. # Test that the openai client was called with the correct response format.
  613. chunks: List[str | CreateResult] = []
  614. async for chunk in model_client.create_stream(messages=[UserMessage(content="I am happy.", source="user")]):
  615. chunks.append(chunk)
  616. assert len(chunks) > 0
  617. assert isinstance(chunks[-1], CreateResult)
  618. assert isinstance(chunks[-1].content, list)
  619. assert len(chunks[-1].content) == 1
  620. assert chunks[-1].content[0] == FunctionCall(
  621. id="1", name="_pass_function", arguments=json.dumps({"input": "happy"})
  622. )
  623. assert isinstance(chunks[-1].thought, str)
  624. response = AgentResponse.model_validate(json.loads(chunks[-1].thought))
  625. assert (
  626. response.thoughts
  627. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  628. )
  629. assert response.response == "happy"
  630. @pytest.mark.asyncio
  631. async def test_r1_think_field(monkeypatch: pytest.MonkeyPatch) -> None:
  632. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  633. chunks = ["<think> Hello</think>", " Another Hello", " Yet Another Hello"]
  634. for i, chunk in enumerate(chunks):
  635. await asyncio.sleep(0.1)
  636. yield ChatCompletionChunk(
  637. id="id",
  638. choices=[
  639. ChunkChoice(
  640. finish_reason="stop" if i == len(chunks) - 1 else None,
  641. index=0,
  642. delta=ChoiceDelta(
  643. content=chunk,
  644. role="assistant",
  645. ),
  646. ),
  647. ],
  648. created=0,
  649. model="r1",
  650. object="chat.completion.chunk",
  651. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  652. )
  653. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  654. stream = kwargs.get("stream", False)
  655. if not stream:
  656. await asyncio.sleep(0.1)
  657. return ChatCompletion(
  658. id="id",
  659. choices=[
  660. Choice(
  661. finish_reason="stop",
  662. index=0,
  663. message=ChatCompletionMessage(
  664. content="<think> Hello</think> Another Hello Yet Another Hello", role="assistant"
  665. ),
  666. )
  667. ],
  668. created=0,
  669. model="r1",
  670. object="chat.completion",
  671. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  672. )
  673. else:
  674. return _mock_create_stream(*args, **kwargs)
  675. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  676. model_client = OpenAIChatCompletionClient(
  677. model="r1",
  678. api_key="",
  679. model_info={"family": ModelFamily.R1, "vision": False, "function_calling": False, "json_output": False},
  680. )
  681. # Successful completion with think field.
  682. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  683. assert create_result.content == "Another Hello Yet Another Hello"
  684. assert create_result.finish_reason == "stop"
  685. assert not create_result.cached
  686. assert create_result.thought == "Hello"
  687. # Stream completion with think field.
  688. chunks: List[str | CreateResult] = []
  689. async for chunk in model_client.create_stream(messages=[UserMessage(content="Hello", source="user")]):
  690. chunks.append(chunk)
  691. assert len(chunks) > 0
  692. assert isinstance(chunks[-1], CreateResult)
  693. assert chunks[-1].content == "Another Hello Yet Another Hello"
  694. assert chunks[-1].thought == "Hello"
  695. assert not chunks[-1].cached
  696. @pytest.mark.asyncio
  697. async def test_r1_think_field_not_present(monkeypatch: pytest.MonkeyPatch) -> None:
  698. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  699. chunks = ["Hello", " Another Hello", " Yet Another Hello"]
  700. for i, chunk in enumerate(chunks):
  701. await asyncio.sleep(0.1)
  702. yield ChatCompletionChunk(
  703. id="id",
  704. choices=[
  705. ChunkChoice(
  706. finish_reason="stop" if i == len(chunks) - 1 else None,
  707. index=0,
  708. delta=ChoiceDelta(
  709. content=chunk,
  710. role="assistant",
  711. ),
  712. ),
  713. ],
  714. created=0,
  715. model="r1",
  716. object="chat.completion.chunk",
  717. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  718. )
  719. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  720. stream = kwargs.get("stream", False)
  721. if not stream:
  722. await asyncio.sleep(0.1)
  723. return ChatCompletion(
  724. id="id",
  725. choices=[
  726. Choice(
  727. finish_reason="stop",
  728. index=0,
  729. message=ChatCompletionMessage(
  730. content="Hello Another Hello Yet Another Hello", role="assistant"
  731. ),
  732. )
  733. ],
  734. created=0,
  735. model="r1",
  736. object="chat.completion",
  737. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  738. )
  739. else:
  740. return _mock_create_stream(*args, **kwargs)
  741. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  742. model_client = OpenAIChatCompletionClient(
  743. model="r1",
  744. api_key="",
  745. model_info={"family": ModelFamily.R1, "vision": False, "function_calling": False, "json_output": False},
  746. )
  747. # Warning completion when think field is not present.
  748. with pytest.warns(UserWarning, match="Could not find <think>..</think> field in model response content."):
  749. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  750. assert create_result.content == "Hello Another Hello Yet Another Hello"
  751. assert create_result.finish_reason == "stop"
  752. assert not create_result.cached
  753. assert create_result.thought is None
  754. # Stream completion with think field.
  755. with pytest.warns(UserWarning, match="Could not find <think>..</think> field in model response content."):
  756. chunks: List[str | CreateResult] = []
  757. async for chunk in model_client.create_stream(messages=[UserMessage(content="Hello", source="user")]):
  758. chunks.append(chunk)
  759. assert len(chunks) > 0
  760. assert isinstance(chunks[-1], CreateResult)
  761. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  762. assert chunks[-1].thought is None
  763. assert not chunks[-1].cached
  764. @pytest.mark.asyncio
  765. async def test_tool_calling(monkeypatch: pytest.MonkeyPatch) -> None:
  766. model = "gpt-4o-2024-05-13"
  767. chat_completions = [
  768. # Successful completion, single tool call
  769. ChatCompletion(
  770. id="id1",
  771. choices=[
  772. Choice(
  773. finish_reason="tool_calls",
  774. index=0,
  775. message=ChatCompletionMessage(
  776. content=None,
  777. tool_calls=[
  778. ChatCompletionMessageToolCall(
  779. id="1",
  780. type="function",
  781. function=Function(
  782. name="_pass_function",
  783. arguments=json.dumps({"input": "task"}),
  784. ),
  785. )
  786. ],
  787. role="assistant",
  788. ),
  789. )
  790. ],
  791. created=0,
  792. model=model,
  793. object="chat.completion",
  794. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  795. ),
  796. # Successful completion, parallel tool calls
  797. ChatCompletion(
  798. id="id2",
  799. choices=[
  800. Choice(
  801. finish_reason="tool_calls",
  802. index=0,
  803. message=ChatCompletionMessage(
  804. content=None,
  805. tool_calls=[
  806. ChatCompletionMessageToolCall(
  807. id="1",
  808. type="function",
  809. function=Function(
  810. name="_pass_function",
  811. arguments=json.dumps({"input": "task"}),
  812. ),
  813. ),
  814. ChatCompletionMessageToolCall(
  815. id="2",
  816. type="function",
  817. function=Function(
  818. name="_fail_function",
  819. arguments=json.dumps({"input": "task"}),
  820. ),
  821. ),
  822. ChatCompletionMessageToolCall(
  823. id="3",
  824. type="function",
  825. function=Function(
  826. name="_echo_function",
  827. arguments=json.dumps({"input": "task"}),
  828. ),
  829. ),
  830. ],
  831. role="assistant",
  832. ),
  833. )
  834. ],
  835. created=0,
  836. model=model,
  837. object="chat.completion",
  838. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  839. ),
  840. # Warning completion when finish reason is not tool_calls.
  841. ChatCompletion(
  842. id="id3",
  843. choices=[
  844. Choice(
  845. finish_reason="stop",
  846. index=0,
  847. message=ChatCompletionMessage(
  848. content=None,
  849. tool_calls=[
  850. ChatCompletionMessageToolCall(
  851. id="1",
  852. type="function",
  853. function=Function(
  854. name="_pass_function",
  855. arguments=json.dumps({"input": "task"}),
  856. ),
  857. )
  858. ],
  859. role="assistant",
  860. ),
  861. )
  862. ],
  863. created=0,
  864. model=model,
  865. object="chat.completion",
  866. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  867. ),
  868. # Thought field is populated when content is not None.
  869. ChatCompletion(
  870. id="id4",
  871. choices=[
  872. Choice(
  873. finish_reason="tool_calls",
  874. index=0,
  875. message=ChatCompletionMessage(
  876. content="I should make a tool call.",
  877. tool_calls=[
  878. ChatCompletionMessageToolCall(
  879. id="1",
  880. type="function",
  881. function=Function(
  882. name="_pass_function",
  883. arguments=json.dumps({"input": "task"}),
  884. ),
  885. )
  886. ],
  887. role="assistant",
  888. ),
  889. )
  890. ],
  891. created=0,
  892. model=model,
  893. object="chat.completion",
  894. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  895. ),
  896. # Should not be returning tool calls when the tool_calls are empty
  897. ChatCompletion(
  898. id="id5",
  899. choices=[
  900. Choice(
  901. finish_reason="stop",
  902. index=0,
  903. message=ChatCompletionMessage(
  904. content="I should make a tool call.",
  905. tool_calls=[],
  906. role="assistant",
  907. ),
  908. )
  909. ],
  910. created=0,
  911. model=model,
  912. object="chat.completion",
  913. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  914. ),
  915. # Should raise warning when function arguments is not a string.
  916. ChatCompletion(
  917. id="id6",
  918. choices=[
  919. Choice(
  920. finish_reason="tool_calls",
  921. index=0,
  922. message=ChatCompletionMessage(
  923. content=None,
  924. tool_calls=[
  925. ChatCompletionMessageToolCall(
  926. id="1",
  927. type="function",
  928. function=Function.construct(name="_pass_function", arguments={"input": "task"}), # type: ignore
  929. )
  930. ],
  931. role="assistant",
  932. ),
  933. )
  934. ],
  935. created=0,
  936. model=model,
  937. object="chat.completion",
  938. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  939. ),
  940. ]
  941. class _MockChatCompletion:
  942. def __init__(self, completions: List[ChatCompletion]):
  943. self.completions = list(completions)
  944. self.calls: List[Dict[str, Any]] = []
  945. async def mock_create(
  946. self, *args: Any, **kwargs: Any
  947. ) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  948. if kwargs.get("stream", False):
  949. raise NotImplementedError("Streaming not supported in this test.")
  950. self.calls.append(kwargs)
  951. return self.completions.pop(0)
  952. mock = _MockChatCompletion(chat_completions)
  953. monkeypatch.setattr(AsyncCompletions, "create", mock.mock_create)
  954. pass_tool = FunctionTool(_pass_function, description="pass tool.")
  955. fail_tool = FunctionTool(_fail_function, description="fail tool.")
  956. echo_tool = FunctionTool(_echo_function, description="echo tool.")
  957. model_client = OpenAIChatCompletionClient(model=model, api_key="")
  958. # Single tool call
  959. create_result = await model_client.create(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  960. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  961. # Verify that the tool schema was passed to the model client.
  962. kwargs = mock.calls[0]
  963. assert kwargs["tools"] == [{"function": pass_tool.schema, "type": "function"}]
  964. # Verify finish reason
  965. assert create_result.finish_reason == "function_calls"
  966. # Parallel tool calls
  967. create_result = await model_client.create(
  968. messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool, fail_tool, echo_tool]
  969. )
  970. assert create_result.content == [
  971. FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function"),
  972. FunctionCall(id="2", arguments=r'{"input": "task"}', name="_fail_function"),
  973. FunctionCall(id="3", arguments=r'{"input": "task"}', name="_echo_function"),
  974. ]
  975. # Verify that the tool schema was passed to the model client.
  976. kwargs = mock.calls[1]
  977. assert kwargs["tools"] == [
  978. {"function": pass_tool.schema, "type": "function"},
  979. {"function": fail_tool.schema, "type": "function"},
  980. {"function": echo_tool.schema, "type": "function"},
  981. ]
  982. # Verify finish reason
  983. assert create_result.finish_reason == "function_calls"
  984. # Warning completion when finish reason is not tool_calls.
  985. with pytest.warns(UserWarning, match="Finish reason mismatch"):
  986. create_result = await model_client.create(
  987. messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool]
  988. )
  989. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  990. assert create_result.finish_reason == "function_calls"
  991. # Thought field is populated when content is not None.
  992. create_result = await model_client.create(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  993. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  994. assert create_result.finish_reason == "function_calls"
  995. assert create_result.thought == "I should make a tool call."
  996. # Should not be returning tool calls when the tool_calls are empty
  997. create_result = await model_client.create(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  998. assert create_result.content == "I should make a tool call."
  999. assert create_result.finish_reason == "stop"
  1000. # Should raise warning when function arguments is not a string.
  1001. with pytest.warns(UserWarning, match="Tool call function arguments field is not a string"):
  1002. create_result = await model_client.create(
  1003. messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool]
  1004. )
  1005. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1006. assert create_result.finish_reason == "function_calls"
  1007. @pytest.mark.asyncio
  1008. async def test_tool_calling_with_stream(monkeypatch: pytest.MonkeyPatch) -> None:
  1009. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  1010. model = resolve_model(kwargs.get("model", "gpt-4o"))
  1011. mock_chunks_content = ["Hello", " Another Hello", " Yet Another Hello"]
  1012. mock_chunks = [
  1013. # generate the list of mock chunk content
  1014. MockChunkDefinition(
  1015. chunk_choice=ChunkChoice(
  1016. finish_reason=None,
  1017. index=0,
  1018. delta=ChoiceDelta(
  1019. content=mock_chunk_content,
  1020. role="assistant",
  1021. ),
  1022. ),
  1023. usage=None,
  1024. )
  1025. for mock_chunk_content in mock_chunks_content
  1026. ] + [
  1027. # generate the function call chunk
  1028. MockChunkDefinition(
  1029. chunk_choice=ChunkChoice(
  1030. finish_reason="tool_calls",
  1031. index=0,
  1032. delta=ChoiceDelta(
  1033. content=None,
  1034. role="assistant",
  1035. tool_calls=[
  1036. ChoiceDeltaToolCall(
  1037. index=0,
  1038. id="1",
  1039. type="function",
  1040. function=ChoiceDeltaToolCallFunction(
  1041. name="_pass_function",
  1042. arguments=json.dumps({"input": "task"}),
  1043. ),
  1044. )
  1045. ],
  1046. ),
  1047. ),
  1048. usage=None,
  1049. )
  1050. ]
  1051. for mock_chunk in mock_chunks:
  1052. await asyncio.sleep(0.1)
  1053. yield ChatCompletionChunk(
  1054. id="id",
  1055. choices=[mock_chunk.chunk_choice],
  1056. created=0,
  1057. model=model,
  1058. object="chat.completion.chunk",
  1059. usage=mock_chunk.usage,
  1060. )
  1061. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  1062. stream = kwargs.get("stream", False)
  1063. if not stream:
  1064. raise ValueError("Stream is not False")
  1065. else:
  1066. return _mock_create_stream(*args, **kwargs)
  1067. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  1068. model_client = OpenAIChatCompletionClient(model="gpt-4o", api_key="")
  1069. pass_tool = FunctionTool(_pass_function, description="pass tool.")
  1070. stream = model_client.create_stream(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  1071. chunks: List[str | CreateResult] = []
  1072. async for chunk in stream:
  1073. chunks.append(chunk)
  1074. assert chunks[0] == "Hello"
  1075. assert chunks[1] == " Another Hello"
  1076. assert chunks[2] == " Yet Another Hello"
  1077. assert isinstance(chunks[-1], CreateResult)
  1078. assert chunks[-1].content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1079. assert chunks[-1].finish_reason == "function_calls"
  1080. assert chunks[-1].thought == "Hello Another Hello Yet Another Hello"
  1081. async def _test_model_client_basic_completion(model_client: OpenAIChatCompletionClient) -> None:
  1082. # Test basic completion
  1083. create_result = await model_client.create(
  1084. messages=[
  1085. SystemMessage(content="You are a helpful assistant."),
  1086. UserMessage(content="Explain to me how AI works.", source="user"),
  1087. ]
  1088. )
  1089. assert isinstance(create_result.content, str)
  1090. assert len(create_result.content) > 0
  1091. async def _test_model_client_with_function_calling(model_client: OpenAIChatCompletionClient) -> None:
  1092. # Test tool calling
  1093. pass_tool = FunctionTool(_pass_function, name="pass_tool", description="pass session.")
  1094. fail_tool = FunctionTool(_fail_function, name="fail_tool", description="fail session.")
  1095. messages: List[LLMMessage] = [UserMessage(content="Call the pass tool with input 'task'", source="user")]
  1096. create_result = await model_client.create(messages=messages, tools=[pass_tool, fail_tool])
  1097. assert isinstance(create_result.content, list)
  1098. assert len(create_result.content) == 1
  1099. assert isinstance(create_result.content[0], FunctionCall)
  1100. assert create_result.content[0].name == "pass_tool"
  1101. assert json.loads(create_result.content[0].arguments) == {"input": "task"}
  1102. assert create_result.finish_reason == "function_calls"
  1103. assert create_result.usage is not None
  1104. # Test reflection on tool call response.
  1105. messages.append(AssistantMessage(content=create_result.content, source="assistant"))
  1106. messages.append(
  1107. FunctionExecutionResultMessage(
  1108. content=[
  1109. FunctionExecutionResult(
  1110. content="passed",
  1111. call_id=create_result.content[0].id,
  1112. is_error=False,
  1113. name=create_result.content[0].name,
  1114. )
  1115. ]
  1116. )
  1117. )
  1118. create_result = await model_client.create(messages=messages)
  1119. assert isinstance(create_result.content, str)
  1120. assert len(create_result.content) > 0
  1121. # Test parallel tool calling
  1122. messages = [
  1123. UserMessage(
  1124. content="Call both the pass tool with input 'task' and the fail tool also with input 'task'", source="user"
  1125. )
  1126. ]
  1127. create_result = await model_client.create(messages=messages, tools=[pass_tool, fail_tool])
  1128. assert isinstance(create_result.content, list)
  1129. assert len(create_result.content) == 2
  1130. assert isinstance(create_result.content[0], FunctionCall)
  1131. assert create_result.content[0].name == "pass_tool"
  1132. assert json.loads(create_result.content[0].arguments) == {"input": "task"}
  1133. assert isinstance(create_result.content[1], FunctionCall)
  1134. assert create_result.content[1].name == "fail_tool"
  1135. assert json.loads(create_result.content[1].arguments) == {"input": "task"}
  1136. assert create_result.finish_reason == "function_calls"
  1137. assert create_result.usage is not None
  1138. # Test reflection on parallel tool call response.
  1139. messages.append(AssistantMessage(content=create_result.content, source="assistant"))
  1140. messages.append(
  1141. FunctionExecutionResultMessage(
  1142. content=[
  1143. FunctionExecutionResult(
  1144. content="passed", call_id=create_result.content[0].id, is_error=False, name="pass_tool"
  1145. ),
  1146. FunctionExecutionResult(
  1147. content="failed", call_id=create_result.content[1].id, is_error=True, name="fail_tool"
  1148. ),
  1149. ]
  1150. )
  1151. )
  1152. create_result = await model_client.create(messages=messages)
  1153. assert isinstance(create_result.content, str)
  1154. assert len(create_result.content) > 0
  1155. @pytest.mark.asyncio
  1156. async def test_openai() -> None:
  1157. api_key = os.getenv("OPENAI_API_KEY")
  1158. if not api_key:
  1159. pytest.skip("OPENAI_API_KEY not found in environment variables")
  1160. model_client = OpenAIChatCompletionClient(
  1161. model="gpt-4o-mini",
  1162. api_key=api_key,
  1163. )
  1164. await _test_model_client_basic_completion(model_client)
  1165. await _test_model_client_with_function_calling(model_client)
  1166. @pytest.mark.asyncio
  1167. async def test_openai_structured_output() -> None:
  1168. api_key = os.getenv("OPENAI_API_KEY")
  1169. if not api_key:
  1170. pytest.skip("OPENAI_API_KEY not found in environment variables")
  1171. class AgentResponse(BaseModel):
  1172. thoughts: str
  1173. response: Literal["happy", "sad", "neutral"]
  1174. model_client = OpenAIChatCompletionClient(
  1175. model="gpt-4o-mini",
  1176. api_key=api_key,
  1177. response_format=AgentResponse, # type: ignore
  1178. )
  1179. # Test that the openai client was called with the correct response format.
  1180. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  1181. assert isinstance(create_result.content, str)
  1182. response = AgentResponse.model_validate(json.loads(create_result.content))
  1183. assert response.thoughts
  1184. assert response.response in ["happy", "sad", "neutral"]
  1185. @pytest.mark.asyncio
  1186. async def test_openai_structured_output_with_streaming() -> None:
  1187. api_key = os.getenv("OPENAI_API_KEY")
  1188. if not api_key:
  1189. pytest.skip("OPENAI_API_KEY not found in environment variables")
  1190. class AgentResponse(BaseModel):
  1191. thoughts: str
  1192. response: Literal["happy", "sad", "neutral"]
  1193. model_client = OpenAIChatCompletionClient(
  1194. model="gpt-4o-mini",
  1195. api_key=api_key,
  1196. response_format=AgentResponse, # type: ignore
  1197. )
  1198. # Test that the openai client was called with the correct response format.
  1199. stream = model_client.create_stream(messages=[UserMessage(content="I am happy.", source="user")])
  1200. chunks: List[str | CreateResult] = []
  1201. async for chunk in stream:
  1202. chunks.append(chunk)
  1203. assert len(chunks) > 0
  1204. assert isinstance(chunks[-1], CreateResult)
  1205. assert isinstance(chunks[-1].content, str)
  1206. response = AgentResponse.model_validate(json.loads(chunks[-1].content))
  1207. assert response.thoughts
  1208. assert response.response in ["happy", "sad", "neutral"]
  1209. @pytest.mark.asyncio
  1210. async def test_openai_structured_output_with_tool_calls() -> None:
  1211. api_key = os.getenv("OPENAI_API_KEY")
  1212. if not api_key:
  1213. pytest.skip("OPENAI_API_KEY not found in environment variables")
  1214. class AgentResponse(BaseModel):
  1215. thoughts: str
  1216. response: Literal["happy", "sad", "neutral"]
  1217. def sentiment_analysis(text: str) -> str:
  1218. """Given a text, return the sentiment."""
  1219. return "happy" if "happy" in text else "sad" if "sad" in text else "neutral"
  1220. tool = FunctionTool(sentiment_analysis, description="Sentiment Analysis", strict=True)
  1221. model_client = OpenAIChatCompletionClient(
  1222. model="gpt-4o-mini",
  1223. api_key=api_key,
  1224. response_format=AgentResponse, # type: ignore
  1225. )
  1226. response1 = await model_client.create(
  1227. messages=[
  1228. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1229. UserMessage(content="I am happy.", source="user"),
  1230. ],
  1231. tools=[tool],
  1232. extra_create_args={"tool_choice": "required"},
  1233. )
  1234. assert isinstance(response1.content, list)
  1235. assert len(response1.content) == 1
  1236. assert isinstance(response1.content[0], FunctionCall)
  1237. assert response1.content[0].name == "sentiment_analysis"
  1238. assert json.loads(response1.content[0].arguments) == {"text": "I am happy."}
  1239. assert response1.finish_reason == "function_calls"
  1240. response2 = await model_client.create(
  1241. messages=[
  1242. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1243. UserMessage(content="I am happy.", source="user"),
  1244. AssistantMessage(content=response1.content, source="assistant"),
  1245. FunctionExecutionResultMessage(
  1246. content=[
  1247. FunctionExecutionResult(
  1248. content="happy", call_id=response1.content[0].id, is_error=False, name=tool.name
  1249. )
  1250. ]
  1251. ),
  1252. ],
  1253. )
  1254. assert isinstance(response2.content, str)
  1255. parsed_response = AgentResponse.model_validate(json.loads(response2.content))
  1256. assert parsed_response.thoughts
  1257. assert parsed_response.response in ["happy", "sad", "neutral"]
  1258. @pytest.mark.asyncio
  1259. async def test_openai_structured_output_with_streaming_tool_calls() -> None:
  1260. api_key = os.getenv("OPENAI_API_KEY")
  1261. if not api_key:
  1262. pytest.skip("OPENAI_API_KEY not found in environment variables")
  1263. class AgentResponse(BaseModel):
  1264. thoughts: str
  1265. response: Literal["happy", "sad", "neutral"]
  1266. def sentiment_analysis(text: str) -> str:
  1267. """Given a text, return the sentiment."""
  1268. return "happy" if "happy" in text else "sad" if "sad" in text else "neutral"
  1269. tool = FunctionTool(sentiment_analysis, description="Sentiment Analysis", strict=True)
  1270. model_client = OpenAIChatCompletionClient(
  1271. model="gpt-4o-mini",
  1272. api_key=api_key,
  1273. response_format=AgentResponse, # type: ignore
  1274. )
  1275. chunks1: List[str | CreateResult] = []
  1276. stream1 = model_client.create_stream(
  1277. messages=[
  1278. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1279. UserMessage(content="I am happy.", source="user"),
  1280. ],
  1281. tools=[tool],
  1282. extra_create_args={"tool_choice": "required"},
  1283. )
  1284. async for chunk in stream1:
  1285. chunks1.append(chunk)
  1286. assert len(chunks1) > 0
  1287. create_result1 = chunks1[-1]
  1288. assert isinstance(create_result1, CreateResult)
  1289. assert isinstance(create_result1.content, list)
  1290. assert len(create_result1.content) == 1
  1291. assert isinstance(create_result1.content[0], FunctionCall)
  1292. assert create_result1.content[0].name == "sentiment_analysis"
  1293. assert json.loads(create_result1.content[0].arguments) == {"text": "I am happy."}
  1294. assert create_result1.finish_reason == "function_calls"
  1295. stream2 = model_client.create_stream(
  1296. messages=[
  1297. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1298. UserMessage(content="I am happy.", source="user"),
  1299. AssistantMessage(content=create_result1.content, source="assistant"),
  1300. FunctionExecutionResultMessage(
  1301. content=[
  1302. FunctionExecutionResult(
  1303. content="happy", call_id=create_result1.content[0].id, is_error=False, name=tool.name
  1304. )
  1305. ]
  1306. ),
  1307. ],
  1308. )
  1309. chunks2: List[str | CreateResult] = []
  1310. async for chunk in stream2:
  1311. chunks2.append(chunk)
  1312. assert len(chunks2) > 0
  1313. create_result2 = chunks2[-1]
  1314. assert isinstance(create_result2, CreateResult)
  1315. assert isinstance(create_result2.content, str)
  1316. parsed_response = AgentResponse.model_validate(json.loads(create_result2.content))
  1317. assert parsed_response.thoughts
  1318. assert parsed_response.response in ["happy", "sad", "neutral"]
  1319. @pytest.mark.asyncio
  1320. async def test_gemini() -> None:
  1321. api_key = os.getenv("GEMINI_API_KEY")
  1322. if not api_key:
  1323. pytest.skip("GEMINI_API_KEY not found in environment variables")
  1324. model_client = OpenAIChatCompletionClient(
  1325. model="gemini-1.5-flash",
  1326. )
  1327. await _test_model_client_basic_completion(model_client)
  1328. await _test_model_client_with_function_calling(model_client)
  1329. @pytest.mark.asyncio
  1330. async def test_hugging_face() -> None:
  1331. api_key = os.getenv("HF_TOKEN")
  1332. if not api_key:
  1333. pytest.skip("HF_TOKEN not found in environment variables")
  1334. model_client = OpenAIChatCompletionClient(
  1335. model="microsoft/Phi-3.5-mini-instruct",
  1336. api_key=api_key,
  1337. base_url="https://api-inference.huggingface.co/v1/",
  1338. model_info={
  1339. "function_calling": False,
  1340. "json_output": False,
  1341. "vision": False,
  1342. "family": ModelFamily.UNKNOWN,
  1343. },
  1344. )
  1345. await _test_model_client_basic_completion(model_client)
  1346. @pytest.mark.asyncio
  1347. async def test_ollama() -> None:
  1348. model = "deepseek-r1:1.5b"
  1349. model_info: ModelInfo = {
  1350. "function_calling": False,
  1351. "json_output": False,
  1352. "vision": False,
  1353. "family": ModelFamily.R1,
  1354. }
  1355. # Check if the model is running locally.
  1356. try:
  1357. async with httpx.AsyncClient() as client:
  1358. response = await client.get(f"http://localhost:11434/v1/models/{model}")
  1359. response.raise_for_status()
  1360. except httpx.HTTPStatusError as e:
  1361. pytest.skip(f"{model} model is not running locally: {e}")
  1362. except httpx.ConnectError as e:
  1363. pytest.skip(f"Ollama is not running locally: {e}")
  1364. model_client = OpenAIChatCompletionClient(
  1365. model=model,
  1366. api_key="placeholder",
  1367. base_url="http://localhost:11434/v1",
  1368. model_info=model_info,
  1369. )
  1370. # Test basic completion with the Ollama deepseek-r1:1.5b model.
  1371. create_result = await model_client.create(
  1372. messages=[
  1373. UserMessage(
  1374. content="Taking two balls from a bag of 10 green balls and 20 red balls, "
  1375. "what is the probability of getting a green and a red balls?",
  1376. source="user",
  1377. ),
  1378. ]
  1379. )
  1380. assert isinstance(create_result.content, str)
  1381. assert len(create_result.content) > 0
  1382. assert create_result.finish_reason == "stop"
  1383. assert create_result.usage is not None
  1384. if model_info["family"] == ModelFamily.R1:
  1385. assert create_result.thought is not None
  1386. # Test streaming completion with the Ollama deepseek-r1:1.5b model.
  1387. chunks: List[str | CreateResult] = []
  1388. async for chunk in model_client.create_stream(
  1389. messages=[
  1390. UserMessage(
  1391. content="Taking two balls from a bag of 10 green balls and 20 red balls, "
  1392. "what is the probability of getting a green and a red balls?",
  1393. source="user",
  1394. ),
  1395. ]
  1396. ):
  1397. chunks.append(chunk)
  1398. assert len(chunks) > 0
  1399. assert isinstance(chunks[-1], CreateResult)
  1400. assert chunks[-1].finish_reason == "stop"
  1401. assert len(chunks[-1].content) > 0
  1402. assert chunks[-1].usage is not None
  1403. if model_info["family"] == ModelFamily.R1:
  1404. assert chunks[-1].thought is not None
  1405. @pytest.mark.asyncio
  1406. async def test_add_name_prefixes(monkeypatch: pytest.MonkeyPatch) -> None:
  1407. sys_message = SystemMessage(content="You are a helpful AI agent, and you answer questions in a friendly way.")
  1408. assistant_message = AssistantMessage(content="Hello, how can I help you?", source="Assistant")
  1409. user_text_message = UserMessage(content="Hello, I am from Seattle.", source="Adam")
  1410. user_mm_message = UserMessage(
  1411. content=[
  1412. "Here is a postcard from Seattle:",
  1413. Image.from_base64(
  1414. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
  1415. ),
  1416. ],
  1417. source="Adam",
  1418. )
  1419. # Default conversion
  1420. oai_sys = to_oai_type(sys_message)[0]
  1421. oai_asst = to_oai_type(assistant_message)[0]
  1422. oai_text = to_oai_type(user_text_message)[0]
  1423. oai_mm = to_oai_type(user_mm_message)[0]
  1424. converted_sys = to_oai_type(sys_message, prepend_name=True)[0]
  1425. converted_asst = to_oai_type(assistant_message, prepend_name=True)[0]
  1426. converted_text = to_oai_type(user_text_message, prepend_name=True)[0]
  1427. converted_mm = to_oai_type(user_mm_message, prepend_name=True)[0]
  1428. # Invariants
  1429. assert "content" in oai_sys
  1430. assert "content" in oai_asst
  1431. assert "content" in oai_text
  1432. assert "content" in oai_mm
  1433. assert "content" in converted_sys
  1434. assert "content" in converted_asst
  1435. assert "content" in converted_text
  1436. assert "content" in converted_mm
  1437. assert oai_sys["role"] == converted_sys["role"]
  1438. assert oai_sys["content"] == converted_sys["content"]
  1439. assert oai_asst["role"] == converted_asst["role"]
  1440. assert oai_asst["content"] == converted_asst["content"]
  1441. assert oai_text["role"] == converted_text["role"]
  1442. assert oai_mm["role"] == converted_mm["role"]
  1443. assert isinstance(oai_mm["content"], list)
  1444. assert isinstance(converted_mm["content"], list)
  1445. assert len(oai_mm["content"]) == len(converted_mm["content"])
  1446. assert "text" in converted_mm["content"][0]
  1447. assert "text" in oai_mm["content"][0]
  1448. # Name prepended
  1449. assert str(converted_text["content"]) == "Adam said:\n" + str(oai_text["content"])
  1450. assert str(converted_mm["content"][0]["text"]) == "Adam said:\n" + str(oai_mm["content"][0]["text"])
  1451. # TODO: add integration tests for Azure OpenAI using AAD token.