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 129 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
11 months 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
[BugFix][Refactor] Modular Transformer Pipeline and Fix Gemini/Anthropic Empty Content Handling (#6063) ## Why are these changes needed? This change addresses a compatibility issue when using Google Gemini models with AutoGen. Specifically, Gemini returns a 400 INVALID_ARGUMENT error when receiving a response with an empty "text" parameter. The root cause is that Gemini does not accept empty string values (e.g., "") as valid inputs in the history of the conversation. To fix this, if the content field is falsy (e.g., None, "", etc.), it is explicitly replaced with a single whitespace (" "), which prevents the Gemini model from rejecting the request. - **Gemini API compatibility:** Gemini models reject empty assistant messages (e.g., `""`), causing runtime errors. This PR ensures such messages are safely replaced with whitespace where appropriate. - **Avoiding regressions:** Applying the empty content workaround **only to Gemini**, and **only to valid message types**, avoids breaking OpenAI or other models. - **Reducing duplication:** Previously, message transformation logic was scattered and repeated across different message types and models. Modularizing this pipeline removes that redundancy. - **Improved maintainability:** With future model variants likely to introduce more constraints, this modular structure makes it easier to adapt transformations without writing ad-hoc code each time. - **Testing for correctness:** The new structure is verified with tests, ensuring the bug fix is effective and non-intrusive. ## Summary This PR introduces a **modular transformer pipeline** for message conversion and **fixes a Gemini-specific bug** related to empty assistant message content. ### Key Changes - **[Refactor]** Extracted message transformation logic into a unified pipeline to: - Reduce code duplication - Improve maintainability - Simplify debugging and extension for future model-specific logic - **[BugFix]** Gemini models do not accept empty assistant message content. - Introduced `_set_empty_to_whitespace` transformer to replace empty strings with `" "` only where needed - Applied it **only** to `"text"` and `"thought"` message types, not to `"tools"` to avoid serialization errors - **Improved structure for model-specific handling** - Transformer functions are now grouped and conditionally applied based on message type and model family - This design makes it easier to support future models or combinations (e.g., Gemini + R1) - **Test coverage added** - Added dedicated tests to verify that empty assistant content causes errors for Gemini - Ensured the fix resolves the issue without affecting OpenAI models --- ## Motivation Originally, Gemini-compatible endpoints would fail when receiving assistant messages with empty content (`""`). This issue required special handling without introducing brittle, ad-hoc patches. In addressing this, I also saw an opportunity to **modularize** the message transformation logic across models. This improves clarity, avoids duplication, and simplifies future adaptations (e.g., different constraints across model families). --- ## 📘 AutoGen Modular Message Transformer: Design & Usage Guide This document introduces the **new modular transformer system** used in AutoGen for converting `LLMMessage` instances to SDK-specific message formats (e.g., OpenAI-style `ChatCompletionMessageParam`). The design improves **reusability, extensibility**, and **maintainability** across different model families. --- ### 🚀 Overview Instead of scattering model-specific message conversion logic across the codebase, the new design introduces: - Modular transformer **functions** for each message type - Per-model **transformer maps** (e.g., for OpenAI-compatible models) - Optional **conditional transformers** for multimodal/text hybrid models - Clear separation between **message adaptation logic** and **SDK-specific builder** (e.g., `ChatCompletionUserMessageParam`) --- ### 🧱 1. Define Transform Functions Each transformer function takes: - `LLMMessage`: a structured AutoGen message - `context: dict`: metadata passed through the builder pipeline And returns: - A dictionary of keyword arguments for the target message constructor (e.g., `{"content": ..., "name": ..., "role": ...}`) ```python def _set_thought_as_content_gemini(message: LLMMessage, context: Dict[str, Any]) -> Dict[str, str | None]: assert isinstance(message, AssistantMessage) return {"content": message.thought or " "} ``` --- ### 🪢 2. Compose Transformer Pipelines Multiple transformer functions are composed into a pipeline using `build_transformer_func()`: ```python base_user_transformer_funcs: List[Callable[[LLMMessage, Dict[str, Any]], Dict[str, Any]]] = [ _assert_valid_name, _set_name, _set_role("user"), ] user_transformer = build_transformer_func( funcs=base_user_transformer_funcs, message_param_func=ChatCompletionUserMessageParam ) ``` - The `message_param_func` is the actual constructor for the target message class (usually from the SDK). - The pipeline is **ordered** — each function adds or overrides keys in the builder kwargs. --- ### 🗂️ 3. Register Transformer Map Each model family maintains a `TransformerMap`, which maps `LLMMessage` types to transformers: ```python __BASE_TRANSFORMER_MAP: TransformerMap = { SystemMessage: system_transformer, UserMessage: user_transformer, AssistantMessage: assistant_transformer, } register_transformer("openai", model_name_or_family, __BASE_TRANSFORMER_MAP) ``` - `"openai"` is currently required (as only OpenAI-compatible format is supported now). - Registration ensures AutoGen knows how to transform each message type for that model. --- ### 🔁 4. Conditional Transformers (Optional) When message construction depends on runtime conditions (e.g., `"text"` vs. `"multimodal"`), use: ```python conditional_transformer = build_conditional_transformer_func( funcs_map=user_transformer_funcs_claude, message_param_func_map=user_transformer_constructors, condition_func=user_condition, ) ``` Where: - `funcs_map`: maps condition label → list of transformer functions ```python user_transformer_funcs_claude = { "text": text_transformers + [_set_empty_to_whitespace], "multimodal": multimodal_transformers + [_set_empty_to_whitespace], } ``` - `message_param_func_map`: maps condition label → message builder ```python user_transformer_constructors = { "text": ChatCompletionUserMessageParam, "multimodal": ChatCompletionUserMessageParam, } ``` - `condition_func`: determines which transformer to apply at runtime ```python def user_condition(message: LLMMessage, context: Dict[str, Any]) -> str: if isinstance(message.content, str): return "text" return "multimodal" ``` --- ### 🧪 Example Flow ```python llm_message = AssistantMessage(name="a", thought="let’s go") model_family = "openai" model_name = "claude-3-opus" transformer = get_transformer(model_family, model_name, type(llm_message)) sdk_message = transformer(llm_message, context={}) ``` --- ### 🎯 Design Benefits | Feature | Benefit | |--------|---------| | 🧱 Function-based modular design | Easy to compose and test | | 🧩 Per-model registry | Clean separation across model families | | ⚖️ Conditional support | Allows multimodal / dynamic adaptation | | 🔄 Reuse-friendly | Shared logic (e.g., `_set_name`) is DRY | | 📦 SDK-specific | Keeps message adaptation aligned to builder interface | --- ### 🔮 Future Direction - Support more SDKs and formats by introducing new message_param_func - Global registry integration (currently `"openai"`-scoped) - Class-based transformer variant if complexity grows --- ## Related issue number Closes #5762 ## 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. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ v ] I've made sure all auto checks have passed. --------- Co-authored-by: Eric Zhu <ekzhu@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
[BugFix][Refactor] Modular Transformer Pipeline and Fix Gemini/Anthropic Empty Content Handling (#6063) ## Why are these changes needed? This change addresses a compatibility issue when using Google Gemini models with AutoGen. Specifically, Gemini returns a 400 INVALID_ARGUMENT error when receiving a response with an empty "text" parameter. The root cause is that Gemini does not accept empty string values (e.g., "") as valid inputs in the history of the conversation. To fix this, if the content field is falsy (e.g., None, "", etc.), it is explicitly replaced with a single whitespace (" "), which prevents the Gemini model from rejecting the request. - **Gemini API compatibility:** Gemini models reject empty assistant messages (e.g., `""`), causing runtime errors. This PR ensures such messages are safely replaced with whitespace where appropriate. - **Avoiding regressions:** Applying the empty content workaround **only to Gemini**, and **only to valid message types**, avoids breaking OpenAI or other models. - **Reducing duplication:** Previously, message transformation logic was scattered and repeated across different message types and models. Modularizing this pipeline removes that redundancy. - **Improved maintainability:** With future model variants likely to introduce more constraints, this modular structure makes it easier to adapt transformations without writing ad-hoc code each time. - **Testing for correctness:** The new structure is verified with tests, ensuring the bug fix is effective and non-intrusive. ## Summary This PR introduces a **modular transformer pipeline** for message conversion and **fixes a Gemini-specific bug** related to empty assistant message content. ### Key Changes - **[Refactor]** Extracted message transformation logic into a unified pipeline to: - Reduce code duplication - Improve maintainability - Simplify debugging and extension for future model-specific logic - **[BugFix]** Gemini models do not accept empty assistant message content. - Introduced `_set_empty_to_whitespace` transformer to replace empty strings with `" "` only where needed - Applied it **only** to `"text"` and `"thought"` message types, not to `"tools"` to avoid serialization errors - **Improved structure for model-specific handling** - Transformer functions are now grouped and conditionally applied based on message type and model family - This design makes it easier to support future models or combinations (e.g., Gemini + R1) - **Test coverage added** - Added dedicated tests to verify that empty assistant content causes errors for Gemini - Ensured the fix resolves the issue without affecting OpenAI models --- ## Motivation Originally, Gemini-compatible endpoints would fail when receiving assistant messages with empty content (`""`). This issue required special handling without introducing brittle, ad-hoc patches. In addressing this, I also saw an opportunity to **modularize** the message transformation logic across models. This improves clarity, avoids duplication, and simplifies future adaptations (e.g., different constraints across model families). --- ## 📘 AutoGen Modular Message Transformer: Design & Usage Guide This document introduces the **new modular transformer system** used in AutoGen for converting `LLMMessage` instances to SDK-specific message formats (e.g., OpenAI-style `ChatCompletionMessageParam`). The design improves **reusability, extensibility**, and **maintainability** across different model families. --- ### 🚀 Overview Instead of scattering model-specific message conversion logic across the codebase, the new design introduces: - Modular transformer **functions** for each message type - Per-model **transformer maps** (e.g., for OpenAI-compatible models) - Optional **conditional transformers** for multimodal/text hybrid models - Clear separation between **message adaptation logic** and **SDK-specific builder** (e.g., `ChatCompletionUserMessageParam`) --- ### 🧱 1. Define Transform Functions Each transformer function takes: - `LLMMessage`: a structured AutoGen message - `context: dict`: metadata passed through the builder pipeline And returns: - A dictionary of keyword arguments for the target message constructor (e.g., `{"content": ..., "name": ..., "role": ...}`) ```python def _set_thought_as_content_gemini(message: LLMMessage, context: Dict[str, Any]) -> Dict[str, str | None]: assert isinstance(message, AssistantMessage) return {"content": message.thought or " "} ``` --- ### 🪢 2. Compose Transformer Pipelines Multiple transformer functions are composed into a pipeline using `build_transformer_func()`: ```python base_user_transformer_funcs: List[Callable[[LLMMessage, Dict[str, Any]], Dict[str, Any]]] = [ _assert_valid_name, _set_name, _set_role("user"), ] user_transformer = build_transformer_func( funcs=base_user_transformer_funcs, message_param_func=ChatCompletionUserMessageParam ) ``` - The `message_param_func` is the actual constructor for the target message class (usually from the SDK). - The pipeline is **ordered** — each function adds or overrides keys in the builder kwargs. --- ### 🗂️ 3. Register Transformer Map Each model family maintains a `TransformerMap`, which maps `LLMMessage` types to transformers: ```python __BASE_TRANSFORMER_MAP: TransformerMap = { SystemMessage: system_transformer, UserMessage: user_transformer, AssistantMessage: assistant_transformer, } register_transformer("openai", model_name_or_family, __BASE_TRANSFORMER_MAP) ``` - `"openai"` is currently required (as only OpenAI-compatible format is supported now). - Registration ensures AutoGen knows how to transform each message type for that model. --- ### 🔁 4. Conditional Transformers (Optional) When message construction depends on runtime conditions (e.g., `"text"` vs. `"multimodal"`), use: ```python conditional_transformer = build_conditional_transformer_func( funcs_map=user_transformer_funcs_claude, message_param_func_map=user_transformer_constructors, condition_func=user_condition, ) ``` Where: - `funcs_map`: maps condition label → list of transformer functions ```python user_transformer_funcs_claude = { "text": text_transformers + [_set_empty_to_whitespace], "multimodal": multimodal_transformers + [_set_empty_to_whitespace], } ``` - `message_param_func_map`: maps condition label → message builder ```python user_transformer_constructors = { "text": ChatCompletionUserMessageParam, "multimodal": ChatCompletionUserMessageParam, } ``` - `condition_func`: determines which transformer to apply at runtime ```python def user_condition(message: LLMMessage, context: Dict[str, Any]) -> str: if isinstance(message.content, str): return "text" return "multimodal" ``` --- ### 🧪 Example Flow ```python llm_message = AssistantMessage(name="a", thought="let’s go") model_family = "openai" model_name = "claude-3-opus" transformer = get_transformer(model_family, model_name, type(llm_message)) sdk_message = transformer(llm_message, context={}) ``` --- ### 🎯 Design Benefits | Feature | Benefit | |--------|---------| | 🧱 Function-based modular design | Easy to compose and test | | 🧩 Per-model registry | Clean separation across model families | | ⚖️ Conditional support | Allows multimodal / dynamic adaptation | | 🔄 Reuse-friendly | Shared logic (e.g., `_set_name`) is DRY | | 📦 SDK-specific | Keeps message adaptation aligned to builder interface | --- ### 🔮 Future Direction - Support more SDKs and formats by introducing new message_param_func - Global registry integration (currently `"openai"`-scoped) - Class-based transformer variant if complexity grows --- ## Related issue number Closes #5762 ## 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. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ v ] I've made sure all auto checks have passed. --------- Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
1 year ago
[BugFix][Refactor] Modular Transformer Pipeline and Fix Gemini/Anthropic Empty Content Handling (#6063) ## Why are these changes needed? This change addresses a compatibility issue when using Google Gemini models with AutoGen. Specifically, Gemini returns a 400 INVALID_ARGUMENT error when receiving a response with an empty "text" parameter. The root cause is that Gemini does not accept empty string values (e.g., "") as valid inputs in the history of the conversation. To fix this, if the content field is falsy (e.g., None, "", etc.), it is explicitly replaced with a single whitespace (" "), which prevents the Gemini model from rejecting the request. - **Gemini API compatibility:** Gemini models reject empty assistant messages (e.g., `""`), causing runtime errors. This PR ensures such messages are safely replaced with whitespace where appropriate. - **Avoiding regressions:** Applying the empty content workaround **only to Gemini**, and **only to valid message types**, avoids breaking OpenAI or other models. - **Reducing duplication:** Previously, message transformation logic was scattered and repeated across different message types and models. Modularizing this pipeline removes that redundancy. - **Improved maintainability:** With future model variants likely to introduce more constraints, this modular structure makes it easier to adapt transformations without writing ad-hoc code each time. - **Testing for correctness:** The new structure is verified with tests, ensuring the bug fix is effective and non-intrusive. ## Summary This PR introduces a **modular transformer pipeline** for message conversion and **fixes a Gemini-specific bug** related to empty assistant message content. ### Key Changes - **[Refactor]** Extracted message transformation logic into a unified pipeline to: - Reduce code duplication - Improve maintainability - Simplify debugging and extension for future model-specific logic - **[BugFix]** Gemini models do not accept empty assistant message content. - Introduced `_set_empty_to_whitespace` transformer to replace empty strings with `" "` only where needed - Applied it **only** to `"text"` and `"thought"` message types, not to `"tools"` to avoid serialization errors - **Improved structure for model-specific handling** - Transformer functions are now grouped and conditionally applied based on message type and model family - This design makes it easier to support future models or combinations (e.g., Gemini + R1) - **Test coverage added** - Added dedicated tests to verify that empty assistant content causes errors for Gemini - Ensured the fix resolves the issue without affecting OpenAI models --- ## Motivation Originally, Gemini-compatible endpoints would fail when receiving assistant messages with empty content (`""`). This issue required special handling without introducing brittle, ad-hoc patches. In addressing this, I also saw an opportunity to **modularize** the message transformation logic across models. This improves clarity, avoids duplication, and simplifies future adaptations (e.g., different constraints across model families). --- ## 📘 AutoGen Modular Message Transformer: Design & Usage Guide This document introduces the **new modular transformer system** used in AutoGen for converting `LLMMessage` instances to SDK-specific message formats (e.g., OpenAI-style `ChatCompletionMessageParam`). The design improves **reusability, extensibility**, and **maintainability** across different model families. --- ### 🚀 Overview Instead of scattering model-specific message conversion logic across the codebase, the new design introduces: - Modular transformer **functions** for each message type - Per-model **transformer maps** (e.g., for OpenAI-compatible models) - Optional **conditional transformers** for multimodal/text hybrid models - Clear separation between **message adaptation logic** and **SDK-specific builder** (e.g., `ChatCompletionUserMessageParam`) --- ### 🧱 1. Define Transform Functions Each transformer function takes: - `LLMMessage`: a structured AutoGen message - `context: dict`: metadata passed through the builder pipeline And returns: - A dictionary of keyword arguments for the target message constructor (e.g., `{"content": ..., "name": ..., "role": ...}`) ```python def _set_thought_as_content_gemini(message: LLMMessage, context: Dict[str, Any]) -> Dict[str, str | None]: assert isinstance(message, AssistantMessage) return {"content": message.thought or " "} ``` --- ### 🪢 2. Compose Transformer Pipelines Multiple transformer functions are composed into a pipeline using `build_transformer_func()`: ```python base_user_transformer_funcs: List[Callable[[LLMMessage, Dict[str, Any]], Dict[str, Any]]] = [ _assert_valid_name, _set_name, _set_role("user"), ] user_transformer = build_transformer_func( funcs=base_user_transformer_funcs, message_param_func=ChatCompletionUserMessageParam ) ``` - The `message_param_func` is the actual constructor for the target message class (usually from the SDK). - The pipeline is **ordered** — each function adds or overrides keys in the builder kwargs. --- ### 🗂️ 3. Register Transformer Map Each model family maintains a `TransformerMap`, which maps `LLMMessage` types to transformers: ```python __BASE_TRANSFORMER_MAP: TransformerMap = { SystemMessage: system_transformer, UserMessage: user_transformer, AssistantMessage: assistant_transformer, } register_transformer("openai", model_name_or_family, __BASE_TRANSFORMER_MAP) ``` - `"openai"` is currently required (as only OpenAI-compatible format is supported now). - Registration ensures AutoGen knows how to transform each message type for that model. --- ### 🔁 4. Conditional Transformers (Optional) When message construction depends on runtime conditions (e.g., `"text"` vs. `"multimodal"`), use: ```python conditional_transformer = build_conditional_transformer_func( funcs_map=user_transformer_funcs_claude, message_param_func_map=user_transformer_constructors, condition_func=user_condition, ) ``` Where: - `funcs_map`: maps condition label → list of transformer functions ```python user_transformer_funcs_claude = { "text": text_transformers + [_set_empty_to_whitespace], "multimodal": multimodal_transformers + [_set_empty_to_whitespace], } ``` - `message_param_func_map`: maps condition label → message builder ```python user_transformer_constructors = { "text": ChatCompletionUserMessageParam, "multimodal": ChatCompletionUserMessageParam, } ``` - `condition_func`: determines which transformer to apply at runtime ```python def user_condition(message: LLMMessage, context: Dict[str, Any]) -> str: if isinstance(message.content, str): return "text" return "multimodal" ``` --- ### 🧪 Example Flow ```python llm_message = AssistantMessage(name="a", thought="let’s go") model_family = "openai" model_name = "claude-3-opus" transformer = get_transformer(model_family, model_name, type(llm_message)) sdk_message = transformer(llm_message, context={}) ``` --- ### 🎯 Design Benefits | Feature | Benefit | |--------|---------| | 🧱 Function-based modular design | Easy to compose and test | | 🧩 Per-model registry | Clean separation across model families | | ⚖️ Conditional support | Allows multimodal / dynamic adaptation | | 🔄 Reuse-friendly | Shared logic (e.g., `_set_name`) is DRY | | 📦 SDK-specific | Keeps message adaptation aligned to builder interface | --- ### 🔮 Future Direction - Support more SDKs and formats by introducing new message_param_func - Global registry integration (currently `"openai"`-scoped) - Class-based transformer variant if complexity grows --- ## Related issue number Closes #5762 ## 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. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ v ] I've made sure all auto checks have passed. --------- Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
1 year ago
[BugFix][Refactor] Modular Transformer Pipeline and Fix Gemini/Anthropic Empty Content Handling (#6063) ## Why are these changes needed? This change addresses a compatibility issue when using Google Gemini models with AutoGen. Specifically, Gemini returns a 400 INVALID_ARGUMENT error when receiving a response with an empty "text" parameter. The root cause is that Gemini does not accept empty string values (e.g., "") as valid inputs in the history of the conversation. To fix this, if the content field is falsy (e.g., None, "", etc.), it is explicitly replaced with a single whitespace (" "), which prevents the Gemini model from rejecting the request. - **Gemini API compatibility:** Gemini models reject empty assistant messages (e.g., `""`), causing runtime errors. This PR ensures such messages are safely replaced with whitespace where appropriate. - **Avoiding regressions:** Applying the empty content workaround **only to Gemini**, and **only to valid message types**, avoids breaking OpenAI or other models. - **Reducing duplication:** Previously, message transformation logic was scattered and repeated across different message types and models. Modularizing this pipeline removes that redundancy. - **Improved maintainability:** With future model variants likely to introduce more constraints, this modular structure makes it easier to adapt transformations without writing ad-hoc code each time. - **Testing for correctness:** The new structure is verified with tests, ensuring the bug fix is effective and non-intrusive. ## Summary This PR introduces a **modular transformer pipeline** for message conversion and **fixes a Gemini-specific bug** related to empty assistant message content. ### Key Changes - **[Refactor]** Extracted message transformation logic into a unified pipeline to: - Reduce code duplication - Improve maintainability - Simplify debugging and extension for future model-specific logic - **[BugFix]** Gemini models do not accept empty assistant message content. - Introduced `_set_empty_to_whitespace` transformer to replace empty strings with `" "` only where needed - Applied it **only** to `"text"` and `"thought"` message types, not to `"tools"` to avoid serialization errors - **Improved structure for model-specific handling** - Transformer functions are now grouped and conditionally applied based on message type and model family - This design makes it easier to support future models or combinations (e.g., Gemini + R1) - **Test coverage added** - Added dedicated tests to verify that empty assistant content causes errors for Gemini - Ensured the fix resolves the issue without affecting OpenAI models --- ## Motivation Originally, Gemini-compatible endpoints would fail when receiving assistant messages with empty content (`""`). This issue required special handling without introducing brittle, ad-hoc patches. In addressing this, I also saw an opportunity to **modularize** the message transformation logic across models. This improves clarity, avoids duplication, and simplifies future adaptations (e.g., different constraints across model families). --- ## 📘 AutoGen Modular Message Transformer: Design & Usage Guide This document introduces the **new modular transformer system** used in AutoGen for converting `LLMMessage` instances to SDK-specific message formats (e.g., OpenAI-style `ChatCompletionMessageParam`). The design improves **reusability, extensibility**, and **maintainability** across different model families. --- ### 🚀 Overview Instead of scattering model-specific message conversion logic across the codebase, the new design introduces: - Modular transformer **functions** for each message type - Per-model **transformer maps** (e.g., for OpenAI-compatible models) - Optional **conditional transformers** for multimodal/text hybrid models - Clear separation between **message adaptation logic** and **SDK-specific builder** (e.g., `ChatCompletionUserMessageParam`) --- ### 🧱 1. Define Transform Functions Each transformer function takes: - `LLMMessage`: a structured AutoGen message - `context: dict`: metadata passed through the builder pipeline And returns: - A dictionary of keyword arguments for the target message constructor (e.g., `{"content": ..., "name": ..., "role": ...}`) ```python def _set_thought_as_content_gemini(message: LLMMessage, context: Dict[str, Any]) -> Dict[str, str | None]: assert isinstance(message, AssistantMessage) return {"content": message.thought or " "} ``` --- ### 🪢 2. Compose Transformer Pipelines Multiple transformer functions are composed into a pipeline using `build_transformer_func()`: ```python base_user_transformer_funcs: List[Callable[[LLMMessage, Dict[str, Any]], Dict[str, Any]]] = [ _assert_valid_name, _set_name, _set_role("user"), ] user_transformer = build_transformer_func( funcs=base_user_transformer_funcs, message_param_func=ChatCompletionUserMessageParam ) ``` - The `message_param_func` is the actual constructor for the target message class (usually from the SDK). - The pipeline is **ordered** — each function adds or overrides keys in the builder kwargs. --- ### 🗂️ 3. Register Transformer Map Each model family maintains a `TransformerMap`, which maps `LLMMessage` types to transformers: ```python __BASE_TRANSFORMER_MAP: TransformerMap = { SystemMessage: system_transformer, UserMessage: user_transformer, AssistantMessage: assistant_transformer, } register_transformer("openai", model_name_or_family, __BASE_TRANSFORMER_MAP) ``` - `"openai"` is currently required (as only OpenAI-compatible format is supported now). - Registration ensures AutoGen knows how to transform each message type for that model. --- ### 🔁 4. Conditional Transformers (Optional) When message construction depends on runtime conditions (e.g., `"text"` vs. `"multimodal"`), use: ```python conditional_transformer = build_conditional_transformer_func( funcs_map=user_transformer_funcs_claude, message_param_func_map=user_transformer_constructors, condition_func=user_condition, ) ``` Where: - `funcs_map`: maps condition label → list of transformer functions ```python user_transformer_funcs_claude = { "text": text_transformers + [_set_empty_to_whitespace], "multimodal": multimodal_transformers + [_set_empty_to_whitespace], } ``` - `message_param_func_map`: maps condition label → message builder ```python user_transformer_constructors = { "text": ChatCompletionUserMessageParam, "multimodal": ChatCompletionUserMessageParam, } ``` - `condition_func`: determines which transformer to apply at runtime ```python def user_condition(message: LLMMessage, context: Dict[str, Any]) -> str: if isinstance(message.content, str): return "text" return "multimodal" ``` --- ### 🧪 Example Flow ```python llm_message = AssistantMessage(name="a", thought="let’s go") model_family = "openai" model_name = "claude-3-opus" transformer = get_transformer(model_family, model_name, type(llm_message)) sdk_message = transformer(llm_message, context={}) ``` --- ### 🎯 Design Benefits | Feature | Benefit | |--------|---------| | 🧱 Function-based modular design | Easy to compose and test | | 🧩 Per-model registry | Clean separation across model families | | ⚖️ Conditional support | Allows multimodal / dynamic adaptation | | 🔄 Reuse-friendly | Shared logic (e.g., `_set_name`) is DRY | | 📦 SDK-specific | Keeps message adaptation aligned to builder interface | --- ### 🔮 Future Direction - Support more SDKs and formats by introducing new message_param_func - Global registry integration (currently `"openai"`-scoped) - Class-based transformer variant if complexity grows --- ## Related issue number Closes #5762 ## 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. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ v ] I've made sure all auto checks have passed. --------- Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. from typing import Annotated, Any, AsyncGenerator, Dict, List, Literal, Tuple, TypeVar, get_args
  6. from unittest.mock import AsyncMock, MagicMock
  7. import httpx
  8. import pytest
  9. from autogen_agentchat.agents import AssistantAgent
  10. from autogen_agentchat.messages import MultiModalMessage
  11. from autogen_core import CancellationToken, FunctionCall, Image
  12. from autogen_core.models import (
  13. AssistantMessage,
  14. CreateResult,
  15. FunctionExecutionResult,
  16. FunctionExecutionResultMessage,
  17. LLMMessage,
  18. ModelInfo,
  19. RequestUsage,
  20. SystemMessage,
  21. UserMessage,
  22. )
  23. from autogen_core.models._model_client import ModelFamily
  24. from autogen_core.tools import BaseTool, FunctionTool
  25. from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, OpenAIChatCompletionClient
  26. from autogen_ext.models.openai._model_info import resolve_model
  27. from autogen_ext.models.openai._openai_client import (
  28. BaseOpenAIChatCompletionClient,
  29. calculate_vision_tokens,
  30. convert_tools,
  31. to_oai_type,
  32. )
  33. from autogen_ext.models.openai._transformation import TransformerMap, get_transformer
  34. from autogen_ext.models.openai._transformation.registry import _find_model_family # pyright: ignore[reportPrivateUsage]
  35. from openai.lib.streaming.chat import AsyncChatCompletionStreamManager
  36. from openai.resources.chat.completions import AsyncCompletions
  37. from openai.types.chat.chat_completion import ChatCompletion, Choice
  38. from openai.types.chat.chat_completion_chunk import (
  39. ChatCompletionChunk,
  40. ChoiceDelta,
  41. ChoiceDeltaToolCall,
  42. ChoiceDeltaToolCallFunction,
  43. )
  44. from openai.types.chat.chat_completion_chunk import (
  45. Choice as ChunkChoice,
  46. )
  47. from openai.types.chat.chat_completion_message import ChatCompletionMessage
  48. from openai.types.chat.chat_completion_message_function_tool_call import (
  49. ChatCompletionMessageFunctionToolCall as _FuncToolCall,
  50. )
  51. from openai.types.chat.chat_completion_message_function_tool_call import Function as _TypedFunction # type: ignore
  52. from openai.types.chat.parsed_chat_completion import (
  53. ParsedChatCompletion,
  54. ParsedChatCompletionMessage,
  55. ParsedChoice,
  56. )
  57. from openai.types.chat.parsed_function_tool_call import ParsedFunction, ParsedFunctionToolCall
  58. from openai.types.completion_usage import CompletionUsage
  59. from pydantic import BaseModel, Field
  60. # Provide a constructible alias for tests compatible with OpenAI 1.99 types
  61. ChatCompletionMessageToolCall = _FuncToolCall # type: ignore[assignment]
  62. # Use the typed Pydantic model directly so .construct and call both work
  63. Function = _TypedFunction # type: ignore[assignment]
  64. ResponseFormatT = TypeVar("ResponseFormatT", bound=BaseModel)
  65. def _pass_function(input: str) -> str:
  66. return "pass"
  67. async def _fail_function(input: str) -> str:
  68. return "fail"
  69. async def _echo_function(input: str) -> str:
  70. return input
  71. class MyResult(BaseModel):
  72. result: str = Field(description="The other description.")
  73. class MyArgs(BaseModel):
  74. query: str = Field(description="The description.")
  75. class MockChunkDefinition(BaseModel):
  76. # defining elements for diffentiating mocking chunks
  77. chunk_choice: ChunkChoice
  78. usage: CompletionUsage | None
  79. class MockChunkEvent(BaseModel):
  80. type: Literal["chunk"]
  81. chunk: ChatCompletionChunk
  82. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  83. model = resolve_model(kwargs.get("model", "gpt-4.1-nano"))
  84. mock_chunks_content = ["Hello", " Another Hello", " Yet Another Hello"]
  85. # The openai api implementations (OpenAI and Litellm) stream chunks of tokens
  86. # with content as string, and then at the end a token with stop set and finally if
  87. # usage requested with `"stream_options": {"include_usage": True}` a chunk with the usage data
  88. mock_chunks = [
  89. # generate the list of mock chunk content
  90. MockChunkDefinition(
  91. chunk_choice=ChunkChoice(
  92. finish_reason=None,
  93. index=0,
  94. delta=ChoiceDelta(
  95. content=mock_chunk_content,
  96. role="assistant",
  97. ),
  98. ),
  99. usage=None,
  100. )
  101. for mock_chunk_content in mock_chunks_content
  102. ] + [
  103. # generate the stop chunk
  104. MockChunkDefinition(
  105. chunk_choice=ChunkChoice(
  106. finish_reason="stop",
  107. index=0,
  108. delta=ChoiceDelta(
  109. content=None,
  110. role="assistant",
  111. ),
  112. ),
  113. usage=None,
  114. )
  115. ]
  116. # generate the usage chunk if configured
  117. if kwargs.get("stream_options", {}).get("include_usage") is True:
  118. mock_chunks = mock_chunks + [
  119. # ---- API differences
  120. # OPENAI API does NOT create a choice
  121. # LITELLM (proxy) DOES create a choice
  122. # Not simulating all the API options, just implementing the LITELLM variant
  123. MockChunkDefinition(
  124. chunk_choice=ChunkChoice(
  125. finish_reason=None,
  126. index=0,
  127. delta=ChoiceDelta(
  128. content=None,
  129. role="assistant",
  130. ),
  131. ),
  132. usage=CompletionUsage(prompt_tokens=3, completion_tokens=3, total_tokens=6),
  133. )
  134. ]
  135. elif kwargs.get("stream_options", {}).get("include_usage") is False:
  136. pass
  137. else:
  138. pass
  139. for mock_chunk in mock_chunks:
  140. await asyncio.sleep(0.1)
  141. yield ChatCompletionChunk(
  142. id="id",
  143. choices=[mock_chunk.chunk_choice],
  144. created=0,
  145. model=model,
  146. object="chat.completion.chunk",
  147. usage=mock_chunk.usage,
  148. )
  149. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  150. stream = kwargs.get("stream", False)
  151. model = resolve_model(kwargs.get("model", "gpt-4.1-nano"))
  152. if not stream:
  153. await asyncio.sleep(0.1)
  154. return ChatCompletion(
  155. id="id",
  156. choices=[
  157. Choice(finish_reason="stop", index=0, message=ChatCompletionMessage(content="Hello", role="assistant"))
  158. ],
  159. created=0,
  160. model=model,
  161. object="chat.completion",
  162. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  163. )
  164. else:
  165. return _mock_create_stream(*args, **kwargs)
  166. @pytest.mark.asyncio
  167. async def test_openai_chat_completion_client() -> None:
  168. client = OpenAIChatCompletionClient(model="gpt-4.1-nano", api_key="api_key")
  169. assert client
  170. @pytest.mark.asyncio
  171. async def test_openai_chat_completion_client_with_gemini_model() -> None:
  172. client = OpenAIChatCompletionClient(model="gemini-1.5-flash", api_key="api_key")
  173. assert client
  174. @pytest.mark.asyncio
  175. async def test_openai_chat_completion_client_serialization() -> None:
  176. client = OpenAIChatCompletionClient(model="gpt-4.1-nano", api_key="sk-password")
  177. assert client
  178. config = client.dump_component()
  179. assert config
  180. assert "sk-password" not in str(config)
  181. serialized_config = config.model_dump_json()
  182. assert serialized_config
  183. assert "sk-password" not in serialized_config
  184. client2 = OpenAIChatCompletionClient.load_component(config)
  185. assert client2
  186. @pytest.mark.asyncio
  187. async def test_openai_chat_completion_client_raise_on_unknown_model() -> None:
  188. with pytest.raises(ValueError, match="model_info is required"):
  189. _ = OpenAIChatCompletionClient(model="unknown", api_key="api_key")
  190. @pytest.mark.asyncio
  191. async def test_custom_model_with_capabilities() -> None:
  192. with pytest.raises(ValueError, match="model_info is required"):
  193. client = OpenAIChatCompletionClient(model="dummy_model", base_url="https://api.dummy.com/v0", api_key="api_key")
  194. client = OpenAIChatCompletionClient(
  195. model="dummy_model",
  196. base_url="https://api.dummy.com/v0",
  197. api_key="api_key",
  198. model_info={
  199. "vision": False,
  200. "function_calling": False,
  201. "json_output": False,
  202. "family": ModelFamily.UNKNOWN,
  203. "structured_output": False,
  204. },
  205. )
  206. assert client
  207. @pytest.mark.asyncio
  208. async def test_azure_openai_chat_completion_client() -> None:
  209. client = AzureOpenAIChatCompletionClient(
  210. azure_deployment="gpt-4o-1",
  211. model="gpt-4o",
  212. api_key="api_key",
  213. api_version="2020-08-04",
  214. azure_endpoint="https://dummy.com",
  215. model_info={
  216. "vision": True,
  217. "function_calling": True,
  218. "json_output": True,
  219. "family": ModelFamily.GPT_4O,
  220. "structured_output": True,
  221. },
  222. )
  223. assert client
  224. @pytest.mark.asyncio
  225. async def test_openai_chat_completion_client_create(
  226. monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
  227. ) -> None:
  228. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  229. with caplog.at_level(logging.INFO):
  230. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  231. result = await client.create(messages=[UserMessage(content="Hello", source="user")])
  232. assert result.content == "Hello"
  233. assert "LLMCall" in caplog.text and "Hello" in caplog.text
  234. @pytest.mark.asyncio
  235. async def test_openai_chat_completion_client_create_stream_with_usage(
  236. monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
  237. ) -> None:
  238. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  239. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  240. chunks: List[str | CreateResult] = []
  241. # Check that include_usage works when set via create_args
  242. with caplog.at_level(logging.INFO):
  243. async for chunk in client.create_stream(
  244. messages=[UserMessage(content="Hello", source="user")],
  245. # include_usage not the default of the OPENAI API and must be explicitly set
  246. extra_create_args={"stream_options": {"include_usage": True}},
  247. ):
  248. chunks.append(chunk)
  249. assert "LLMStreamStart" in caplog.text
  250. assert "LLMStreamEnd" in caplog.text
  251. assert chunks[0] == "Hello"
  252. assert chunks[1] == " Another Hello"
  253. assert chunks[2] == " Yet Another Hello"
  254. assert isinstance(chunks[-1], CreateResult)
  255. assert isinstance(chunks[-1].content, str)
  256. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  257. assert chunks[-1].content in caplog.text
  258. assert chunks[-1].usage == RequestUsage(prompt_tokens=3, completion_tokens=3)
  259. chunks = []
  260. # Check that include_usage works when set via include_usage flag
  261. with caplog.at_level(logging.INFO):
  262. async for chunk in client.create_stream(
  263. messages=[UserMessage(content="Hello", source="user")],
  264. include_usage=True,
  265. ):
  266. chunks.append(chunk)
  267. assert "LLMStreamStart" in caplog.text
  268. assert "LLMStreamEnd" in caplog.text
  269. assert chunks[0] == "Hello"
  270. assert chunks[1] == " Another Hello"
  271. assert chunks[2] == " Yet Another Hello"
  272. assert isinstance(chunks[-1], CreateResult)
  273. assert isinstance(chunks[-1].content, str)
  274. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  275. assert chunks[-1].content in caplog.text
  276. assert chunks[-1].usage == RequestUsage(prompt_tokens=3, completion_tokens=3)
  277. chunks = []
  278. # Check that setting both flags to different values raises an exception
  279. with pytest.raises(ValueError):
  280. async for chunk in client.create_stream(
  281. messages=[UserMessage(content="Hello", source="user")],
  282. extra_create_args={"stream_options": {"include_usage": False}},
  283. include_usage=True,
  284. ):
  285. chunks.append(chunk)
  286. @pytest.mark.asyncio
  287. async def test_openai_chat_completion_client_create_stream_no_usage_default(monkeypatch: pytest.MonkeyPatch) -> None:
  288. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  289. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  290. chunks: List[str | CreateResult] = []
  291. async for chunk in client.create_stream(
  292. messages=[UserMessage(content="Hello", source="user")],
  293. # include_usage not the default of the OPENAI APIis ,
  294. # it can be explicitly set
  295. # or just not declared which is the default
  296. # extra_create_args={"stream_options": {"include_usage": False}},
  297. ):
  298. chunks.append(chunk)
  299. assert chunks[0] == "Hello"
  300. assert chunks[1] == " Another Hello"
  301. assert chunks[2] == " Yet Another Hello"
  302. assert isinstance(chunks[-1], CreateResult)
  303. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  304. assert chunks[-1].usage == RequestUsage(prompt_tokens=0, completion_tokens=0)
  305. @pytest.mark.asyncio
  306. async def test_openai_chat_completion_client_create_stream_no_usage_explicit(monkeypatch: pytest.MonkeyPatch) -> None:
  307. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  308. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  309. chunks: List[str | CreateResult] = []
  310. async for chunk in client.create_stream(
  311. messages=[UserMessage(content="Hello", source="user")],
  312. # include_usage is not the default of the OPENAI API ,
  313. # it can be explicitly set
  314. # or just not declared which is the default
  315. extra_create_args={"stream_options": {"include_usage": False}},
  316. ):
  317. chunks.append(chunk)
  318. assert chunks[0] == "Hello"
  319. assert chunks[1] == " Another Hello"
  320. assert chunks[2] == " Yet Another Hello"
  321. @pytest.mark.asyncio
  322. async def test_openai_chat_completion_client_none_usage(monkeypatch: pytest.MonkeyPatch) -> None:
  323. """Test that completion_tokens and prompt_tokens handle None usage correctly.
  324. This test addresses issue #6352 where result.usage could be None,
  325. causing TypeError in logging when trying to access completion_tokens.
  326. """
  327. async def _mock_create_with_none_usage(*args: Any, **kwargs: Any) -> ChatCompletion:
  328. await asyncio.sleep(0.1)
  329. # Create a ChatCompletion with None usage (which can happen in some API scenarios)
  330. return ChatCompletion(
  331. id="id",
  332. choices=[
  333. Choice(finish_reason="stop", index=0, message=ChatCompletionMessage(content="Hello", role="assistant"))
  334. ],
  335. created=0,
  336. model="gpt-4o",
  337. object="chat.completion",
  338. usage=None, # This is the scenario from the issue
  339. )
  340. monkeypatch.setattr(AsyncCompletions, "create", _mock_create_with_none_usage)
  341. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  342. # This should not raise a TypeError
  343. result = await client.create(messages=[UserMessage(content="Hello", source="user")])
  344. # Verify that the usage is correctly set to 0 when usage is None
  345. assert result.usage.prompt_tokens == 0
  346. assert result.usage.completion_tokens == 0
  347. @pytest.mark.asyncio
  348. async def test_openai_chat_completion_client_create_cancel(monkeypatch: pytest.MonkeyPatch) -> None:
  349. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  350. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  351. cancellation_token = CancellationToken()
  352. task = asyncio.create_task(
  353. client.create(messages=[UserMessage(content="Hello", source="user")], cancellation_token=cancellation_token)
  354. )
  355. cancellation_token.cancel()
  356. with pytest.raises(asyncio.CancelledError):
  357. await task
  358. @pytest.mark.asyncio
  359. async def test_openai_chat_completion_client_create_stream_cancel(monkeypatch: pytest.MonkeyPatch) -> None:
  360. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  361. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  362. cancellation_token = CancellationToken()
  363. stream = client.create_stream(
  364. messages=[UserMessage(content="Hello", source="user")], cancellation_token=cancellation_token
  365. )
  366. assert await anext(stream)
  367. cancellation_token.cancel()
  368. with pytest.raises(asyncio.CancelledError):
  369. async for _ in stream:
  370. pass
  371. @pytest.mark.asyncio
  372. async def test_openai_chat_completion_client_count_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
  373. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
  374. messages: List[LLMMessage] = [
  375. SystemMessage(content="Hello"),
  376. UserMessage(content="Hello", source="user"),
  377. AssistantMessage(content="Hello", source="assistant"),
  378. UserMessage(
  379. content=[
  380. "str1",
  381. Image.from_base64(
  382. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
  383. ),
  384. ],
  385. source="user",
  386. ),
  387. FunctionExecutionResultMessage(
  388. content=[FunctionExecutionResult(content="Hello", call_id="1", is_error=False, name="tool1")]
  389. ),
  390. ]
  391. def tool1(test: str, test2: str) -> str:
  392. return test + test2
  393. def tool2(test1: int, test2: List[int]) -> str:
  394. return str(test1) + str(test2)
  395. tools = [FunctionTool(tool1, description="example tool 1"), FunctionTool(tool2, description="example tool 2")]
  396. mockcalculate_vision_tokens = MagicMock()
  397. monkeypatch.setattr("autogen_ext.models.openai._openai_client.calculate_vision_tokens", mockcalculate_vision_tokens)
  398. num_tokens = client.count_tokens(messages, tools=tools)
  399. assert num_tokens
  400. # Check that calculate_vision_tokens was called
  401. mockcalculate_vision_tokens.assert_called_once()
  402. remaining_tokens = client.remaining_tokens(messages, tools=tools)
  403. assert remaining_tokens
  404. @pytest.mark.parametrize(
  405. "mock_size, expected_num_tokens",
  406. [
  407. ((1, 1), 255),
  408. ((512, 512), 255),
  409. ((2048, 512), 765),
  410. ((2048, 2048), 765),
  411. ((512, 1024), 425),
  412. ],
  413. )
  414. def test_openai_count_image_tokens(mock_size: Tuple[int, int], expected_num_tokens: int) -> None:
  415. # Step 1: Mock the Image class with only the 'image' attribute
  416. mock_image_attr = MagicMock()
  417. mock_image_attr.size = mock_size
  418. mock_image = MagicMock()
  419. mock_image.image = mock_image_attr
  420. # Directly call calculate_vision_tokens and check the result
  421. calculated_tokens = calculate_vision_tokens(mock_image, detail="auto")
  422. assert calculated_tokens == expected_num_tokens
  423. def test_convert_tools_accepts_both_func_tool_and_schema() -> None:
  424. def my_function(arg: str, other: Annotated[int, "int arg"], nonrequired: int = 5) -> MyResult:
  425. return MyResult(result="test")
  426. tool = FunctionTool(my_function, description="Function tool.")
  427. schema = tool.schema
  428. converted_tool_schema = convert_tools([tool, schema])
  429. assert len(converted_tool_schema) == 2
  430. assert converted_tool_schema[0] == converted_tool_schema[1]
  431. def test_convert_tools_accepts_both_tool_and_schema() -> None:
  432. class MyTool(BaseTool[MyArgs, MyResult]):
  433. def __init__(self) -> None:
  434. super().__init__(
  435. args_type=MyArgs,
  436. return_type=MyResult,
  437. name="TestTool",
  438. description="Description of test tool.",
  439. )
  440. async def run(self, args: MyArgs, cancellation_token: CancellationToken) -> MyResult:
  441. return MyResult(result="value")
  442. tool = MyTool()
  443. schema = tool.schema
  444. converted_tool_schema = convert_tools([tool, schema])
  445. assert len(converted_tool_schema) == 2
  446. assert converted_tool_schema[0] == converted_tool_schema[1]
  447. @pytest.mark.asyncio
  448. async def test_json_mode(monkeypatch: pytest.MonkeyPatch) -> None:
  449. model = "gpt-4.1-nano-2025-04-14"
  450. called_args = {}
  451. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion:
  452. # Capture the arguments passed to the function
  453. called_args["kwargs"] = kwargs
  454. return ChatCompletion(
  455. id="id1",
  456. choices=[
  457. Choice(
  458. finish_reason="stop",
  459. index=0,
  460. message=ChatCompletionMessage(
  461. content=json.dumps({"thoughts": "happy", "response": "happy"}),
  462. role="assistant",
  463. ),
  464. )
  465. ],
  466. created=0,
  467. model=model,
  468. object="chat.completion",
  469. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  470. )
  471. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  472. model_client = OpenAIChatCompletionClient(model=model, api_key="")
  473. # Test that the openai client was called with the correct response format.
  474. create_result = await model_client.create(
  475. messages=[UserMessage(content="I am happy.", source="user")], json_output=True
  476. )
  477. assert isinstance(create_result.content, str)
  478. response = json.loads(create_result.content)
  479. assert response["thoughts"] == "happy"
  480. assert response["response"] == "happy"
  481. assert called_args["kwargs"]["response_format"] == {"type": "json_object"}
  482. # Make sure that the response format is set to json_object when json_output is True, regardless of the extra_create_args.
  483. create_result = await model_client.create(
  484. messages=[UserMessage(content="I am happy.", source="user")],
  485. json_output=True,
  486. extra_create_args={"response_format": "json_object"},
  487. )
  488. assert isinstance(create_result.content, str)
  489. response = json.loads(create_result.content)
  490. assert response["thoughts"] == "happy"
  491. assert response["response"] == "happy"
  492. assert called_args["kwargs"]["response_format"] == {"type": "json_object"}
  493. create_result = await model_client.create(
  494. messages=[UserMessage(content="I am happy.", source="user")],
  495. json_output=True,
  496. extra_create_args={"response_format": "text"},
  497. )
  498. assert isinstance(create_result.content, str)
  499. response = json.loads(create_result.content)
  500. assert response["thoughts"] == "happy"
  501. assert response["response"] == "happy"
  502. # Check that the openai client was called with the correct response format.
  503. assert called_args["kwargs"]["response_format"] == {"type": "json_object"}
  504. # Make sure when json_output is set to False, the response format is always set to text.
  505. create_result = await model_client.create(
  506. messages=[UserMessage(content="I am happy.", source="user")],
  507. json_output=False,
  508. extra_create_args={"response_format": "text"},
  509. )
  510. assert called_args["kwargs"]["response_format"] == {"type": "text"}
  511. create_result = await model_client.create(
  512. messages=[UserMessage(content="I am happy.", source="user")],
  513. json_output=False,
  514. extra_create_args={"response_format": "json_object"},
  515. )
  516. assert called_args["kwargs"]["response_format"] == {"type": "text"}
  517. # Make sure when response_format is set it is used when json_output is not set.
  518. create_result = await model_client.create(
  519. messages=[UserMessage(content="I am happy.", source="user")],
  520. extra_create_args={"response_format": {"type": "json_object"}},
  521. )
  522. assert isinstance(create_result.content, str)
  523. response = json.loads(create_result.content)
  524. assert response["thoughts"] == "happy"
  525. assert response["response"] == "happy"
  526. assert called_args["kwargs"]["response_format"] == {"type": "json_object"}
  527. @pytest.mark.asyncio
  528. async def test_structured_output_using_response_format(monkeypatch: pytest.MonkeyPatch) -> None:
  529. class AgentResponse(BaseModel):
  530. thoughts: str
  531. response: Literal["happy", "sad", "neutral"]
  532. model = "gpt-4.1-nano-2025-04-14"
  533. called_args = {}
  534. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion:
  535. # Capture the arguments passed to the function
  536. called_args["kwargs"] = kwargs
  537. return ChatCompletion(
  538. id="id1",
  539. choices=[
  540. Choice(
  541. finish_reason="stop",
  542. index=0,
  543. message=ChatCompletionMessage(
  544. content=json.dumps({"thoughts": "happy", "response": "happy"}),
  545. role="assistant",
  546. ),
  547. )
  548. ],
  549. created=0,
  550. model=model,
  551. object="chat.completion",
  552. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  553. )
  554. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  555. # Scenario 1: response_format is set to constructor.
  556. model_client = OpenAIChatCompletionClient(
  557. model=model,
  558. api_key="",
  559. response_format={
  560. "type": "json_schema",
  561. "json_schema": {
  562. "name": "test",
  563. "description": "test",
  564. "schema": AgentResponse.model_json_schema(),
  565. },
  566. },
  567. )
  568. create_result = await model_client.create(
  569. messages=[UserMessage(content="I am happy.", source="user")],
  570. )
  571. assert isinstance(create_result.content, str)
  572. response = json.loads(create_result.content)
  573. assert response["thoughts"] == "happy"
  574. assert response["response"] == "happy"
  575. assert called_args["kwargs"]["response_format"]["type"] == "json_schema"
  576. # Test the response format can be serailized and deserialized.
  577. config = model_client.dump_component()
  578. assert config
  579. loaded_client = OpenAIChatCompletionClient.load_component(config)
  580. create_result = await loaded_client.create(
  581. messages=[UserMessage(content="I am happy.", source="user")],
  582. )
  583. assert isinstance(create_result.content, str)
  584. response = json.loads(create_result.content)
  585. assert response["thoughts"] == "happy"
  586. assert response["response"] == "happy"
  587. assert called_args["kwargs"]["response_format"]["type"] == "json_schema"
  588. # Scenario 2: response_format is set to a extra_create_args.
  589. model_client = OpenAIChatCompletionClient(model=model, api_key="")
  590. create_result = await model_client.create(
  591. messages=[UserMessage(content="I am happy.", source="user")],
  592. extra_create_args={
  593. "response_format": {
  594. "type": "json_schema",
  595. "json_schema": {
  596. "name": "test",
  597. "description": "test",
  598. "schema": AgentResponse.model_json_schema(),
  599. },
  600. }
  601. },
  602. )
  603. assert isinstance(create_result.content, str)
  604. response = json.loads(create_result.content)
  605. assert response["thoughts"] == "happy"
  606. assert response["response"] == "happy"
  607. assert called_args["kwargs"]["response_format"]["type"] == "json_schema"
  608. @pytest.mark.asyncio
  609. async def test_structured_output(monkeypatch: pytest.MonkeyPatch) -> None:
  610. class AgentResponse(BaseModel):
  611. thoughts: str
  612. response: Literal["happy", "sad", "neutral"]
  613. model = "gpt-4.1-nano-2025-04-14"
  614. async def _mock_parse(*args: Any, **kwargs: Any) -> ParsedChatCompletion[AgentResponse]:
  615. return ParsedChatCompletion(
  616. id="id1",
  617. choices=[
  618. ParsedChoice(
  619. finish_reason="stop",
  620. index=0,
  621. message=ParsedChatCompletionMessage(
  622. content=json.dumps(
  623. {
  624. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  625. "response": "happy",
  626. }
  627. ),
  628. role="assistant",
  629. ),
  630. )
  631. ],
  632. created=0,
  633. model=model,
  634. object="chat.completion",
  635. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  636. )
  637. monkeypatch.setattr(AsyncCompletions, "parse", _mock_parse)
  638. model_client = OpenAIChatCompletionClient(
  639. model=model,
  640. api_key="",
  641. )
  642. # Test that the openai client was called with the correct response format.
  643. create_result = await model_client.create(
  644. messages=[UserMessage(content="I am happy.", source="user")], json_output=AgentResponse
  645. )
  646. assert isinstance(create_result.content, str)
  647. response = AgentResponse.model_validate(json.loads(create_result.content))
  648. assert (
  649. response.thoughts
  650. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  651. )
  652. assert response.response == "happy"
  653. # Test that a warning will be raise if response_format is set to a dict.
  654. with pytest.warns(
  655. UserWarning,
  656. match="response_format is found in extra_create_args while json_output is set to a Pydantic model class.",
  657. ):
  658. create_result = await model_client.create(
  659. messages=[UserMessage(content="I am happy.", source="user")],
  660. json_output=AgentResponse,
  661. extra_create_args={"response_format": {"type": "json_object"}},
  662. )
  663. # Test that a warning will be raised if response_format is set to a pydantic model.
  664. with pytest.warns(
  665. DeprecationWarning,
  666. match="Using response_format to specify the BaseModel for structured output type will be deprecated.",
  667. ):
  668. create_result = await model_client.create(
  669. messages=[UserMessage(content="I am happy.", source="user")],
  670. extra_create_args={"response_format": AgentResponse},
  671. )
  672. # Test that a ValueError will be raised if response_format and json_output are set to a pydantic model.
  673. with pytest.raises(
  674. ValueError, match="response_format and json_output cannot be set to a Pydantic model class at the same time."
  675. ):
  676. create_result = await model_client.create(
  677. messages=[UserMessage(content="I am happy.", source="user")],
  678. json_output=AgentResponse,
  679. extra_create_args={"response_format": AgentResponse},
  680. )
  681. @pytest.mark.asyncio
  682. async def test_structured_output_with_tool_calls(monkeypatch: pytest.MonkeyPatch) -> None:
  683. class AgentResponse(BaseModel):
  684. thoughts: str
  685. response: Literal["happy", "sad", "neutral"]
  686. model = "gpt-4.1-nano-2025-04-14"
  687. async def _mock_parse(*args: Any, **kwargs: Any) -> ParsedChatCompletion[AgentResponse]:
  688. return ParsedChatCompletion(
  689. id="id1",
  690. choices=[
  691. ParsedChoice(
  692. finish_reason="tool_calls",
  693. index=0,
  694. message=ParsedChatCompletionMessage(
  695. content=json.dumps(
  696. {
  697. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  698. "response": "happy",
  699. }
  700. ),
  701. role="assistant",
  702. tool_calls=[
  703. ParsedFunctionToolCall(
  704. id="1",
  705. type="function",
  706. function=ParsedFunction(
  707. name="_pass_function",
  708. arguments=json.dumps({"input": "happy"}),
  709. ),
  710. )
  711. ],
  712. ),
  713. )
  714. ],
  715. created=0,
  716. model=model,
  717. object="chat.completion",
  718. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  719. )
  720. monkeypatch.setattr(AsyncCompletions, "parse", _mock_parse)
  721. model_client = OpenAIChatCompletionClient(
  722. model=model,
  723. api_key="",
  724. )
  725. # Test that the openai client was called with the correct response format.
  726. create_result = await model_client.create(
  727. messages=[UserMessage(content="I am happy.", source="user")], json_output=AgentResponse
  728. )
  729. assert isinstance(create_result.content, list)
  730. assert len(create_result.content) == 1
  731. assert create_result.content[0] == FunctionCall(
  732. id="1", name="_pass_function", arguments=json.dumps({"input": "happy"})
  733. )
  734. assert isinstance(create_result.thought, str)
  735. response = AgentResponse.model_validate(json.loads(create_result.thought))
  736. assert (
  737. response.thoughts
  738. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  739. )
  740. assert response.response == "happy"
  741. @pytest.mark.asyncio
  742. async def test_structured_output_with_streaming(monkeypatch: pytest.MonkeyPatch) -> None:
  743. class AgentResponse(BaseModel):
  744. thoughts: str
  745. response: Literal["happy", "sad", "neutral"]
  746. raw_content = json.dumps(
  747. {
  748. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  749. "response": "happy",
  750. }
  751. )
  752. chunked_content = [raw_content[i : i + 5] for i in range(0, len(raw_content), 5)]
  753. assert "".join(chunked_content) == raw_content
  754. model = "gpt-4.1-nano-2025-04-14"
  755. mock_chunk_events = [
  756. MockChunkEvent(
  757. type="chunk",
  758. chunk=ChatCompletionChunk(
  759. id="id",
  760. choices=[
  761. ChunkChoice(
  762. finish_reason=None,
  763. index=0,
  764. delta=ChoiceDelta(
  765. content=mock_chunk_content,
  766. role="assistant",
  767. ),
  768. )
  769. ],
  770. created=0,
  771. model=model,
  772. object="chat.completion.chunk",
  773. usage=None,
  774. ),
  775. )
  776. for mock_chunk_content in chunked_content
  777. ]
  778. async def _mock_create_stream(*args: Any) -> AsyncGenerator[MockChunkEvent, None]:
  779. async def _stream() -> AsyncGenerator[MockChunkEvent, None]:
  780. for mock_chunk_event in mock_chunk_events:
  781. await asyncio.sleep(0.1)
  782. yield mock_chunk_event
  783. return _stream()
  784. # Mock the context manager __aenter__ method which returns the stream.
  785. monkeypatch.setattr(AsyncChatCompletionStreamManager, "__aenter__", _mock_create_stream)
  786. model_client = OpenAIChatCompletionClient(
  787. model=model,
  788. api_key="",
  789. )
  790. # Test that the openai client was called with the correct response format.
  791. chunks: List[str | CreateResult] = []
  792. async for chunk in model_client.create_stream(
  793. messages=[UserMessage(content="I am happy.", source="user")], json_output=AgentResponse
  794. ):
  795. chunks.append(chunk)
  796. assert len(chunks) > 0
  797. assert isinstance(chunks[-1], CreateResult)
  798. assert isinstance(chunks[-1].content, str)
  799. response = AgentResponse.model_validate(json.loads(chunks[-1].content))
  800. assert (
  801. response.thoughts
  802. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  803. )
  804. assert response.response == "happy"
  805. @pytest.mark.asyncio
  806. async def test_structured_output_with_streaming_tool_calls(monkeypatch: pytest.MonkeyPatch) -> None:
  807. class AgentResponse(BaseModel):
  808. thoughts: str
  809. response: Literal["happy", "sad", "neutral"]
  810. raw_content = json.dumps(
  811. {
  812. "thoughts": "The user explicitly states that they are happy without any indication of sadness or neutrality.",
  813. "response": "happy",
  814. }
  815. )
  816. chunked_content = [raw_content[i : i + 5] for i in range(0, len(raw_content), 5)]
  817. assert "".join(chunked_content) == raw_content
  818. model = "gpt-4.1-nano-2025-04-14"
  819. # generate the list of mock chunk content
  820. mock_chunk_events = [
  821. MockChunkEvent(
  822. type="chunk",
  823. chunk=ChatCompletionChunk(
  824. id="id",
  825. choices=[
  826. ChunkChoice(
  827. finish_reason=None,
  828. index=0,
  829. delta=ChoiceDelta(
  830. content=mock_chunk_content,
  831. role="assistant",
  832. ),
  833. )
  834. ],
  835. created=0,
  836. model=model,
  837. object="chat.completion.chunk",
  838. usage=None,
  839. ),
  840. )
  841. for mock_chunk_content in chunked_content
  842. ]
  843. # add the tool call chunk.
  844. mock_chunk_events += [
  845. MockChunkEvent(
  846. type="chunk",
  847. chunk=ChatCompletionChunk(
  848. id="id",
  849. choices=[
  850. ChunkChoice(
  851. finish_reason="tool_calls",
  852. index=0,
  853. delta=ChoiceDelta(
  854. content=None,
  855. role="assistant",
  856. tool_calls=[
  857. ChoiceDeltaToolCall(
  858. id="1",
  859. index=0,
  860. type="function",
  861. function=ChoiceDeltaToolCallFunction(
  862. name="_pass_function",
  863. arguments=json.dumps({"input": "happy"}),
  864. ),
  865. )
  866. ],
  867. ),
  868. )
  869. ],
  870. created=0,
  871. model=model,
  872. object="chat.completion.chunk",
  873. usage=None,
  874. ),
  875. )
  876. ]
  877. async def _mock_create_stream(*args: Any) -> AsyncGenerator[MockChunkEvent, None]:
  878. async def _stream() -> AsyncGenerator[MockChunkEvent, None]:
  879. for mock_chunk_event in mock_chunk_events:
  880. await asyncio.sleep(0.1)
  881. yield mock_chunk_event
  882. return _stream()
  883. # Mock the context manager __aenter__ method which returns the stream.
  884. monkeypatch.setattr(AsyncChatCompletionStreamManager, "__aenter__", _mock_create_stream)
  885. model_client = OpenAIChatCompletionClient(
  886. model=model,
  887. api_key="",
  888. )
  889. # Test that the openai client was called with the correct response format.
  890. chunks: List[str | CreateResult] = []
  891. async for chunk in model_client.create_stream(
  892. messages=[UserMessage(content="I am happy.", source="user")], json_output=AgentResponse
  893. ):
  894. chunks.append(chunk)
  895. assert len(chunks) > 0
  896. assert isinstance(chunks[-1], CreateResult)
  897. assert isinstance(chunks[-1].content, list)
  898. assert len(chunks[-1].content) == 1
  899. assert chunks[-1].content[0] == FunctionCall(
  900. id="1", name="_pass_function", arguments=json.dumps({"input": "happy"})
  901. )
  902. assert isinstance(chunks[-1].thought, str)
  903. response = AgentResponse.model_validate(json.loads(chunks[-1].thought))
  904. assert (
  905. response.thoughts
  906. == "The user explicitly states that they are happy without any indication of sadness or neutrality."
  907. )
  908. assert response.response == "happy"
  909. @pytest.mark.asyncio
  910. async def test_r1_reasoning_content(monkeypatch: pytest.MonkeyPatch) -> None:
  911. """Test handling of reasoning_content in R1 model. Testing create without streaming."""
  912. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion:
  913. return ChatCompletion(
  914. id="test_id",
  915. model="r1",
  916. object="chat.completion",
  917. created=1234567890,
  918. choices=[
  919. Choice(
  920. index=0,
  921. message=ChatCompletionMessage(
  922. role="assistant",
  923. content="This is the main content",
  924. # The reasoning content is included in model_extra for hosted R1 models.
  925. reasoning_content="This is the reasoning content", # type: ignore
  926. ),
  927. finish_reason="stop",
  928. )
  929. ],
  930. usage=CompletionUsage(
  931. prompt_tokens=10,
  932. completion_tokens=10,
  933. total_tokens=20,
  934. ),
  935. )
  936. # Patch the client creation
  937. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  938. # Create the client
  939. model_client = OpenAIChatCompletionClient(
  940. model="r1",
  941. api_key="",
  942. model_info={
  943. "family": ModelFamily.R1,
  944. "vision": False,
  945. "function_calling": False,
  946. "json_output": False,
  947. "structured_output": False,
  948. },
  949. )
  950. # Test the create method
  951. result = await model_client.create([UserMessage(content="Test message", source="user")])
  952. # Verify that the content and thought are as expected
  953. assert result.content == "This is the main content"
  954. assert result.thought == "This is the reasoning content"
  955. @pytest.mark.asyncio
  956. async def test_r1_reasoning_content_streaming(monkeypatch: pytest.MonkeyPatch) -> None:
  957. """Test that reasoning_content in model_extra is correctly extracted and streamed."""
  958. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  959. contentChunks = [None, None, "This is the main content"]
  960. reasoningChunks = ["This is the reasoning content 1", "This is the reasoning content 2", None]
  961. for i in range(len(contentChunks)):
  962. await asyncio.sleep(0.1)
  963. yield ChatCompletionChunk(
  964. id="id",
  965. choices=[
  966. ChunkChoice(
  967. finish_reason="stop" if i == len(contentChunks) - 1 else None,
  968. index=0,
  969. delta=ChoiceDelta(
  970. content=contentChunks[i],
  971. # The reasoning content is included in model_extra for hosted R1 models.
  972. reasoning_content=reasoningChunks[i], # type: ignore
  973. role="assistant",
  974. ),
  975. ),
  976. ],
  977. created=0,
  978. model="r1",
  979. object="chat.completion.chunk",
  980. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  981. )
  982. async def _mock_create(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  983. return _mock_create_stream(*args, **kwargs)
  984. # Patch the client creation
  985. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  986. # Create the client
  987. model_client = OpenAIChatCompletionClient(
  988. model="r1",
  989. api_key="",
  990. model_info={
  991. "family": ModelFamily.R1,
  992. "vision": False,
  993. "function_calling": False,
  994. "json_output": False,
  995. "structured_output": False,
  996. },
  997. )
  998. # Test the create_stream method
  999. chunks: List[str | CreateResult] = []
  1000. async for chunk in model_client.create_stream(messages=[UserMessage(content="Hello", source="user")]):
  1001. chunks.append(chunk)
  1002. # Verify that the chunks first stream the reasoning content and then the main content
  1003. # Then verify that the final result has the correct content and thought
  1004. assert len(chunks) == 5
  1005. assert chunks[0] == "<think>This is the reasoning content 1"
  1006. assert chunks[1] == "This is the reasoning content 2"
  1007. assert chunks[2] == "</think>"
  1008. assert chunks[3] == "This is the main content"
  1009. assert isinstance(chunks[4], CreateResult)
  1010. assert chunks[4].content == "This is the main content"
  1011. assert chunks[4].thought == "This is the reasoning content 1This is the reasoning content 2"
  1012. @pytest.mark.asyncio
  1013. async def test_r1_think_field(monkeypatch: pytest.MonkeyPatch) -> None:
  1014. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  1015. chunks = ["<think> Hello</think>", " Another Hello", " Yet Another Hello"]
  1016. for i, chunk in enumerate(chunks):
  1017. await asyncio.sleep(0.1)
  1018. yield ChatCompletionChunk(
  1019. id="id",
  1020. choices=[
  1021. ChunkChoice(
  1022. finish_reason="stop" if i == len(chunks) - 1 else None,
  1023. index=0,
  1024. delta=ChoiceDelta(
  1025. content=chunk,
  1026. role="assistant",
  1027. ),
  1028. ),
  1029. ],
  1030. created=0,
  1031. model="r1",
  1032. object="chat.completion.chunk",
  1033. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  1034. )
  1035. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  1036. stream = kwargs.get("stream", False)
  1037. if not stream:
  1038. await asyncio.sleep(0.1)
  1039. return ChatCompletion(
  1040. id="id",
  1041. choices=[
  1042. Choice(
  1043. finish_reason="stop",
  1044. index=0,
  1045. message=ChatCompletionMessage(
  1046. content="<think> Hello</think> Another Hello Yet Another Hello", role="assistant"
  1047. ),
  1048. )
  1049. ],
  1050. created=0,
  1051. model="r1",
  1052. object="chat.completion",
  1053. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  1054. )
  1055. else:
  1056. return _mock_create_stream(*args, **kwargs)
  1057. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  1058. model_client = OpenAIChatCompletionClient(
  1059. model="r1",
  1060. api_key="",
  1061. model_info={
  1062. "family": ModelFamily.R1,
  1063. "vision": False,
  1064. "function_calling": False,
  1065. "json_output": False,
  1066. "structured_output": False,
  1067. },
  1068. )
  1069. # Successful completion with think field.
  1070. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  1071. assert create_result.content == "Another Hello Yet Another Hello"
  1072. assert create_result.finish_reason == "stop"
  1073. assert not create_result.cached
  1074. assert create_result.thought == "Hello"
  1075. # Stream completion with think field.
  1076. chunks: List[str | CreateResult] = []
  1077. async for chunk in model_client.create_stream(messages=[UserMessage(content="Hello", source="user")]):
  1078. chunks.append(chunk)
  1079. assert len(chunks) > 0
  1080. assert isinstance(chunks[-1], CreateResult)
  1081. assert chunks[-1].content == "Another Hello Yet Another Hello"
  1082. assert chunks[-1].thought == "Hello"
  1083. assert not chunks[-1].cached
  1084. @pytest.mark.asyncio
  1085. async def test_r1_think_field_not_present(monkeypatch: pytest.MonkeyPatch) -> None:
  1086. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  1087. chunks = ["Hello", " Another Hello", " Yet Another Hello"]
  1088. for i, chunk in enumerate(chunks):
  1089. await asyncio.sleep(0.1)
  1090. yield ChatCompletionChunk(
  1091. id="id",
  1092. choices=[
  1093. ChunkChoice(
  1094. finish_reason="stop" if i == len(chunks) - 1 else None,
  1095. index=0,
  1096. delta=ChoiceDelta(
  1097. content=chunk,
  1098. role="assistant",
  1099. ),
  1100. ),
  1101. ],
  1102. created=0,
  1103. model="r1",
  1104. object="chat.completion.chunk",
  1105. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  1106. )
  1107. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  1108. stream = kwargs.get("stream", False)
  1109. if not stream:
  1110. await asyncio.sleep(0.1)
  1111. return ChatCompletion(
  1112. id="id",
  1113. choices=[
  1114. Choice(
  1115. finish_reason="stop",
  1116. index=0,
  1117. message=ChatCompletionMessage(
  1118. content="Hello Another Hello Yet Another Hello", role="assistant"
  1119. ),
  1120. )
  1121. ],
  1122. created=0,
  1123. model="r1",
  1124. object="chat.completion",
  1125. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  1126. )
  1127. else:
  1128. return _mock_create_stream(*args, **kwargs)
  1129. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  1130. model_client = OpenAIChatCompletionClient(
  1131. model="r1",
  1132. api_key="",
  1133. model_info={
  1134. "family": ModelFamily.R1,
  1135. "vision": False,
  1136. "function_calling": False,
  1137. "json_output": False,
  1138. "structured_output": False,
  1139. },
  1140. )
  1141. # Warning completion when think field is not present.
  1142. with pytest.warns(UserWarning, match="Could not find <think>..</think> field in model response content."):
  1143. create_result = await model_client.create(messages=[UserMessage(content="I am happy.", source="user")])
  1144. assert create_result.content == "Hello Another Hello Yet Another Hello"
  1145. assert create_result.finish_reason == "stop"
  1146. assert not create_result.cached
  1147. assert create_result.thought is None
  1148. # Stream completion with think field.
  1149. with pytest.warns(UserWarning, match="Could not find <think>..</think> field in model response content."):
  1150. chunks: List[str | CreateResult] = []
  1151. async for chunk in model_client.create_stream(messages=[UserMessage(content="Hello", source="user")]):
  1152. chunks.append(chunk)
  1153. assert len(chunks) > 0
  1154. assert isinstance(chunks[-1], CreateResult)
  1155. assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
  1156. assert chunks[-1].thought is None
  1157. assert not chunks[-1].cached
  1158. @pytest.mark.asyncio
  1159. async def test_tool_calling(monkeypatch: pytest.MonkeyPatch) -> None:
  1160. model = "gpt-4.1-nano-2025-04-14"
  1161. chat_completions = [
  1162. # Successful completion, single tool call
  1163. ChatCompletion(
  1164. id="id1",
  1165. choices=[
  1166. Choice(
  1167. finish_reason="tool_calls",
  1168. index=0,
  1169. message=ChatCompletionMessage(
  1170. content=None,
  1171. tool_calls=[
  1172. ChatCompletionMessageToolCall(
  1173. id="1",
  1174. type="function",
  1175. function=Function(
  1176. name="_pass_function",
  1177. arguments=json.dumps({"input": "task"}),
  1178. ),
  1179. )
  1180. ],
  1181. role="assistant",
  1182. ),
  1183. )
  1184. ],
  1185. created=0,
  1186. model=model,
  1187. object="chat.completion",
  1188. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  1189. ),
  1190. # Successful completion, parallel tool calls
  1191. ChatCompletion(
  1192. id="id2",
  1193. choices=[
  1194. Choice(
  1195. finish_reason="tool_calls",
  1196. index=0,
  1197. message=ChatCompletionMessage(
  1198. content=None,
  1199. tool_calls=[
  1200. ChatCompletionMessageToolCall(
  1201. id="1",
  1202. type="function",
  1203. function=Function(
  1204. name="_pass_function",
  1205. arguments=json.dumps({"input": "task"}),
  1206. ),
  1207. ),
  1208. ChatCompletionMessageToolCall(
  1209. id="2",
  1210. type="function",
  1211. function=Function(
  1212. name="_fail_function",
  1213. arguments=json.dumps({"input": "task"}),
  1214. ),
  1215. ),
  1216. ChatCompletionMessageToolCall(
  1217. id="3",
  1218. type="function",
  1219. function=Function(
  1220. name="_echo_function",
  1221. arguments=json.dumps({"input": "task"}),
  1222. ),
  1223. ),
  1224. ],
  1225. role="assistant",
  1226. ),
  1227. )
  1228. ],
  1229. created=0,
  1230. model=model,
  1231. object="chat.completion",
  1232. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  1233. ),
  1234. # Warning completion when finish reason is not tool_calls.
  1235. ChatCompletion(
  1236. id="id3",
  1237. choices=[
  1238. Choice(
  1239. finish_reason="stop",
  1240. index=0,
  1241. message=ChatCompletionMessage(
  1242. content=None,
  1243. tool_calls=[
  1244. ChatCompletionMessageToolCall(
  1245. id="1",
  1246. type="function",
  1247. function=Function(
  1248. name="_pass_function",
  1249. arguments=json.dumps({"input": "task"}),
  1250. ),
  1251. )
  1252. ],
  1253. role="assistant",
  1254. ),
  1255. )
  1256. ],
  1257. created=0,
  1258. model=model,
  1259. object="chat.completion",
  1260. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  1261. ),
  1262. # Thought field is populated when content is not None.
  1263. ChatCompletion(
  1264. id="id4",
  1265. choices=[
  1266. Choice(
  1267. finish_reason="tool_calls",
  1268. index=0,
  1269. message=ChatCompletionMessage(
  1270. content="I should make a tool call.",
  1271. tool_calls=[
  1272. ChatCompletionMessageToolCall(
  1273. id="1",
  1274. type="function",
  1275. function=Function(
  1276. name="_pass_function",
  1277. arguments=json.dumps({"input": "task"}),
  1278. ),
  1279. )
  1280. ],
  1281. role="assistant",
  1282. ),
  1283. )
  1284. ],
  1285. created=0,
  1286. model=model,
  1287. object="chat.completion",
  1288. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  1289. ),
  1290. # Should not be returning tool calls when the tool_calls are empty
  1291. ChatCompletion(
  1292. id="id5",
  1293. choices=[
  1294. Choice(
  1295. finish_reason="stop",
  1296. index=0,
  1297. message=ChatCompletionMessage(
  1298. content="I should make a tool call.",
  1299. tool_calls=[],
  1300. role="assistant",
  1301. ),
  1302. )
  1303. ],
  1304. created=0,
  1305. model=model,
  1306. object="chat.completion",
  1307. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  1308. ),
  1309. # Should raise warning when function arguments is not a string.
  1310. ChatCompletion(
  1311. id="id6",
  1312. choices=[
  1313. Choice(
  1314. finish_reason="tool_calls",
  1315. index=0,
  1316. message=ChatCompletionMessage(
  1317. content=None,
  1318. tool_calls=[
  1319. ChatCompletionMessageToolCall(
  1320. id="1",
  1321. type="function",
  1322. function=Function.construct(name="_pass_function", arguments={"input": "task"}), # type: ignore
  1323. )
  1324. ],
  1325. role="assistant",
  1326. ),
  1327. )
  1328. ],
  1329. created=0,
  1330. model=model,
  1331. object="chat.completion",
  1332. usage=CompletionUsage(prompt_tokens=10, completion_tokens=5, total_tokens=0),
  1333. ),
  1334. ]
  1335. class _MockChatCompletion:
  1336. def __init__(self, completions: List[ChatCompletion]):
  1337. self.completions = list(completions)
  1338. self.calls: List[Dict[str, Any]] = []
  1339. async def mock_create(
  1340. self, *args: Any, **kwargs: Any
  1341. ) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  1342. if kwargs.get("stream", False):
  1343. raise NotImplementedError("Streaming not supported in this test.")
  1344. self.calls.append(kwargs)
  1345. return self.completions.pop(0)
  1346. mock = _MockChatCompletion(chat_completions)
  1347. monkeypatch.setattr(AsyncCompletions, "create", mock.mock_create)
  1348. pass_tool = FunctionTool(_pass_function, description="pass tool.")
  1349. fail_tool = FunctionTool(_fail_function, description="fail tool.")
  1350. echo_tool = FunctionTool(_echo_function, description="echo tool.")
  1351. model_client = OpenAIChatCompletionClient(model=model, api_key="")
  1352. # Single tool call
  1353. create_result = await model_client.create(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  1354. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1355. # Verify that the tool schema was passed to the model client.
  1356. kwargs = mock.calls[0]
  1357. assert kwargs["tools"] == [{"function": pass_tool.schema, "type": "function"}]
  1358. # Verify finish reason
  1359. assert create_result.finish_reason == "function_calls"
  1360. # Parallel tool calls
  1361. create_result = await model_client.create(
  1362. messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool, fail_tool, echo_tool]
  1363. )
  1364. assert create_result.content == [
  1365. FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function"),
  1366. FunctionCall(id="2", arguments=r'{"input": "task"}', name="_fail_function"),
  1367. FunctionCall(id="3", arguments=r'{"input": "task"}', name="_echo_function"),
  1368. ]
  1369. # Verify that the tool schema was passed to the model client.
  1370. kwargs = mock.calls[1]
  1371. assert kwargs["tools"] == [
  1372. {"function": pass_tool.schema, "type": "function"},
  1373. {"function": fail_tool.schema, "type": "function"},
  1374. {"function": echo_tool.schema, "type": "function"},
  1375. ]
  1376. # Verify finish reason
  1377. assert create_result.finish_reason == "function_calls"
  1378. # Warning completion when finish reason is not tool_calls.
  1379. with pytest.warns(UserWarning, match="Finish reason mismatch"):
  1380. create_result = await model_client.create(
  1381. messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool]
  1382. )
  1383. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1384. assert create_result.finish_reason == "function_calls"
  1385. # Thought field is populated when content is not None.
  1386. create_result = await model_client.create(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  1387. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1388. assert create_result.finish_reason == "function_calls"
  1389. assert create_result.thought == "I should make a tool call."
  1390. # Should not be returning tool calls when the tool_calls are empty
  1391. create_result = await model_client.create(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  1392. assert create_result.content == "I should make a tool call."
  1393. assert create_result.finish_reason == "stop"
  1394. # Should raise warning when function arguments is not a string.
  1395. with pytest.warns(UserWarning, match="Tool call function arguments field is not a string"):
  1396. create_result = await model_client.create(
  1397. messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool]
  1398. )
  1399. assert create_result.content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1400. assert create_result.finish_reason == "function_calls"
  1401. @pytest.mark.asyncio
  1402. async def test_tool_calling_with_stream(monkeypatch: pytest.MonkeyPatch) -> None:
  1403. async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
  1404. model = resolve_model(kwargs.get("model", "gpt-4o"))
  1405. mock_chunks_content = ["Hello", " Another Hello", " Yet Another Hello"]
  1406. mock_chunks = [
  1407. # generate the list of mock chunk content
  1408. MockChunkDefinition(
  1409. chunk_choice=ChunkChoice(
  1410. finish_reason=None,
  1411. index=0,
  1412. delta=ChoiceDelta(
  1413. content=mock_chunk_content,
  1414. role="assistant",
  1415. ),
  1416. ),
  1417. usage=None,
  1418. )
  1419. for mock_chunk_content in mock_chunks_content
  1420. ] + [
  1421. # generate the function call chunk
  1422. MockChunkDefinition(
  1423. chunk_choice=ChunkChoice(
  1424. finish_reason="tool_calls",
  1425. index=0,
  1426. delta=ChoiceDelta(
  1427. content=None,
  1428. role="assistant",
  1429. tool_calls=[
  1430. ChoiceDeltaToolCall(
  1431. index=0,
  1432. id="1",
  1433. type="function",
  1434. function=ChoiceDeltaToolCallFunction(
  1435. name="_pass_function",
  1436. arguments=json.dumps({"input": "task"}),
  1437. ),
  1438. )
  1439. ],
  1440. ),
  1441. ),
  1442. usage=None,
  1443. )
  1444. ]
  1445. for mock_chunk in mock_chunks:
  1446. await asyncio.sleep(0.1)
  1447. yield ChatCompletionChunk(
  1448. id="id",
  1449. choices=[mock_chunk.chunk_choice],
  1450. created=0,
  1451. model=model,
  1452. object="chat.completion.chunk",
  1453. usage=mock_chunk.usage,
  1454. )
  1455. async def _mock_create(*args: Any, **kwargs: Any) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  1456. stream = kwargs.get("stream", False)
  1457. if not stream:
  1458. raise ValueError("Stream is not False")
  1459. else:
  1460. return _mock_create_stream(*args, **kwargs)
  1461. monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
  1462. model_client = OpenAIChatCompletionClient(model="gpt-4o", api_key="")
  1463. pass_tool = FunctionTool(_pass_function, description="pass tool.")
  1464. stream = model_client.create_stream(messages=[UserMessage(content="Hello", source="user")], tools=[pass_tool])
  1465. chunks: List[str | CreateResult] = []
  1466. async for chunk in stream:
  1467. chunks.append(chunk)
  1468. assert chunks[0] == "Hello"
  1469. assert chunks[1] == " Another Hello"
  1470. assert chunks[2] == " Yet Another Hello"
  1471. assert isinstance(chunks[-1], CreateResult)
  1472. assert chunks[-1].content == [FunctionCall(id="1", arguments=r'{"input": "task"}', name="_pass_function")]
  1473. assert chunks[-1].finish_reason == "function_calls"
  1474. assert chunks[-1].thought == "Hello Another Hello Yet Another Hello"
  1475. @pytest.mark.asyncio
  1476. async def test_tool_calls_assistant_message_content_field(monkeypatch: pytest.MonkeyPatch) -> None:
  1477. """Test that AssistantMessage with tool calls includes required content field.
  1478. This test addresses the issue where AssistantMessage with tool calls but no thought
  1479. was missing the required 'content' field, causing OpenAI API UnprocessableEntityError(422).
  1480. """
  1481. # Create a tool call for testing
  1482. tool_calls = [
  1483. FunctionCall(id="call_1", name="increment_number", arguments='{"number": 5}'),
  1484. FunctionCall(id="call_2", name="increment_number", arguments='{"number": 6}'),
  1485. ]
  1486. # Mock response for tool calls
  1487. chat_completion = ChatCompletion(
  1488. id="id1",
  1489. choices=[
  1490. Choice(
  1491. finish_reason="stop",
  1492. index=0,
  1493. message=ChatCompletionMessage(
  1494. role="assistant",
  1495. content="Done",
  1496. ),
  1497. )
  1498. ],
  1499. created=1234567890,
  1500. model="gpt-4o",
  1501. object="chat.completion",
  1502. usage=CompletionUsage(completion_tokens=10, prompt_tokens=5, total_tokens=15),
  1503. )
  1504. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="test")
  1505. mock_create = AsyncMock(return_value=chat_completion)
  1506. # Test AssistantMessage with tool calls but no thought
  1507. assistant_message_no_thought = AssistantMessage(
  1508. content=tool_calls,
  1509. source="assistant",
  1510. thought=None, # No thought - this was causing the issue
  1511. )
  1512. with monkeypatch.context() as mp:
  1513. mp.setattr(client._client.chat.completions, "create", mock_create) # type: ignore[reportPrivateUsage]
  1514. await client.create(
  1515. messages=[
  1516. UserMessage(content="Please increment these numbers", source="user"),
  1517. assistant_message_no_thought,
  1518. ]
  1519. )
  1520. # Verify the API was called and check the messages sent
  1521. mock_create.assert_called_once()
  1522. call_args = mock_create.call_args
  1523. # Extract the messages from the API call
  1524. messages = call_args.kwargs["messages"]
  1525. # Find the assistant message in the API call
  1526. assistant_messages = [msg for msg in messages if msg["role"] == "assistant"]
  1527. assert len(assistant_messages) == 1
  1528. assistant_msg = assistant_messages[0]
  1529. # Verify all required fields are present
  1530. assert "role" in assistant_msg
  1531. assert "tool_calls" in assistant_msg
  1532. assert "content" in assistant_msg # This was missing before the fix
  1533. # Verify field values
  1534. assert assistant_msg["role"] == "assistant"
  1535. assert assistant_msg["content"] is None # Should be null for tools without thought
  1536. assert len(assistant_msg["tool_calls"]) == 2
  1537. # Test AssistantMessage with tool calls AND thought
  1538. assistant_message_with_thought = AssistantMessage(
  1539. content=tool_calls, source="assistant", thought="I need to increment these numbers."
  1540. )
  1541. mock_create.reset_mock() # Reset for second test
  1542. with monkeypatch.context() as mp:
  1543. mp.setattr(client._client.chat.completions, "create", mock_create) # type: ignore[reportPrivateUsage]
  1544. await client.create(
  1545. messages=[
  1546. UserMessage(content="Please increment these numbers", source="user"),
  1547. assistant_message_with_thought,
  1548. ]
  1549. )
  1550. # Verify the API was called for the second test
  1551. mock_create.assert_called_once()
  1552. call_args = mock_create.call_args
  1553. # Extract the messages from the API call
  1554. messages = call_args.kwargs["messages"]
  1555. # Find the assistant message in the API call
  1556. assistant_messages = [msg for msg in messages if msg["role"] == "assistant"]
  1557. assert len(assistant_messages) == 1
  1558. assistant_msg_with_thought = assistant_messages[0]
  1559. # Should have both tool_calls and content with thought text
  1560. assert "role" in assistant_msg_with_thought
  1561. assert "tool_calls" in assistant_msg_with_thought
  1562. assert "content" in assistant_msg_with_thought
  1563. assert assistant_msg_with_thought["role"] == "assistant"
  1564. assert assistant_msg_with_thought["content"] == "I need to increment these numbers."
  1565. assert len(assistant_msg_with_thought["tool_calls"]) == 2
  1566. @pytest.fixture()
  1567. def openai_client(request: pytest.FixtureRequest) -> OpenAIChatCompletionClient:
  1568. model = request.node.callspec.params["model"] # type: ignore
  1569. assert isinstance(model, str)
  1570. if model.startswith("gemini"):
  1571. api_key = os.getenv("GEMINI_API_KEY")
  1572. if not api_key:
  1573. pytest.skip("GEMINI_API_KEY not found in environment variables")
  1574. elif model.startswith("claude"):
  1575. api_key = os.getenv("ANTHROPIC_API_KEY")
  1576. if not api_key:
  1577. pytest.skip("ANTHROPIC_API_KEY not found in environment variables")
  1578. else:
  1579. api_key = os.getenv("OPENAI_API_KEY")
  1580. if not api_key:
  1581. pytest.skip("OPENAI_API_KEY not found in environment variables")
  1582. model_client = OpenAIChatCompletionClient(
  1583. model=model,
  1584. api_key=api_key,
  1585. )
  1586. return model_client
  1587. @pytest.mark.asyncio
  1588. @pytest.mark.parametrize(
  1589. "model",
  1590. ["gpt-4.1-nano", "gemini-1.5-flash", "claude-3-5-haiku-20241022"],
  1591. )
  1592. async def test_model_client_basic_completion(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  1593. # Test basic completion
  1594. create_result = await openai_client.create(
  1595. messages=[
  1596. SystemMessage(content="You are a helpful assistant."),
  1597. UserMessage(content="Explain to me how AI works.", source="user"),
  1598. ]
  1599. )
  1600. assert isinstance(create_result.content, str)
  1601. assert len(create_result.content) > 0
  1602. @pytest.mark.asyncio
  1603. @pytest.mark.parametrize(
  1604. "model",
  1605. ["gpt-4.1-nano", "gemini-1.5-flash", "claude-3-5-haiku-20241022"],
  1606. )
  1607. async def test_model_client_with_function_calling(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  1608. # Test tool calling
  1609. pass_tool = FunctionTool(_pass_function, name="pass_tool", description="pass session.")
  1610. fail_tool = FunctionTool(_fail_function, name="fail_tool", description="fail session.")
  1611. messages: List[LLMMessage] = [
  1612. UserMessage(content="Call the pass tool with input 'task' summarize the result.", source="user")
  1613. ]
  1614. create_result = await openai_client.create(messages=messages, tools=[pass_tool, fail_tool])
  1615. assert isinstance(create_result.content, list)
  1616. assert len(create_result.content) == 1
  1617. assert isinstance(create_result.content[0], FunctionCall)
  1618. assert create_result.content[0].name == "pass_tool"
  1619. assert json.loads(create_result.content[0].arguments) == {"input": "task"}
  1620. assert create_result.finish_reason == "function_calls"
  1621. assert create_result.usage is not None
  1622. # Test reflection on tool call response.
  1623. messages.append(AssistantMessage(content=create_result.content, source="assistant"))
  1624. messages.append(
  1625. FunctionExecutionResultMessage(
  1626. content=[
  1627. FunctionExecutionResult(
  1628. content="passed",
  1629. call_id=create_result.content[0].id,
  1630. is_error=False,
  1631. name=create_result.content[0].name,
  1632. )
  1633. ]
  1634. )
  1635. )
  1636. create_result = await openai_client.create(messages=messages)
  1637. assert isinstance(create_result.content, str)
  1638. assert len(create_result.content) > 0
  1639. # Test parallel tool calling
  1640. messages = [
  1641. UserMessage(
  1642. content="Call both the pass tool with input 'task' and the fail tool also with input 'task' and summarize the result",
  1643. source="user",
  1644. )
  1645. ]
  1646. create_result = await openai_client.create(messages=messages, tools=[pass_tool, fail_tool])
  1647. assert isinstance(create_result.content, list)
  1648. assert len(create_result.content) == 2
  1649. assert isinstance(create_result.content[0], FunctionCall)
  1650. assert create_result.content[0].name == "pass_tool"
  1651. assert json.loads(create_result.content[0].arguments) == {"input": "task"}
  1652. assert isinstance(create_result.content[1], FunctionCall)
  1653. assert create_result.content[1].name == "fail_tool"
  1654. assert json.loads(create_result.content[1].arguments) == {"input": "task"}
  1655. assert create_result.finish_reason == "function_calls"
  1656. assert create_result.usage is not None
  1657. # Test reflection on parallel tool call response.
  1658. messages.append(AssistantMessage(content=create_result.content, source="assistant"))
  1659. messages.append(
  1660. FunctionExecutionResultMessage(
  1661. content=[
  1662. FunctionExecutionResult(
  1663. content="passed", call_id=create_result.content[0].id, is_error=False, name="pass_tool"
  1664. ),
  1665. FunctionExecutionResult(
  1666. content="failed", call_id=create_result.content[1].id, is_error=True, name="fail_tool"
  1667. ),
  1668. ]
  1669. )
  1670. )
  1671. create_result = await openai_client.create(messages=messages)
  1672. assert isinstance(create_result.content, str)
  1673. assert len(create_result.content) > 0
  1674. @pytest.mark.asyncio
  1675. @pytest.mark.parametrize(
  1676. "model",
  1677. ["gpt-4.1-nano", "gemini-1.5-flash"],
  1678. )
  1679. async def test_openai_structured_output_using_response_format(
  1680. model: str, openai_client: OpenAIChatCompletionClient
  1681. ) -> None:
  1682. class AgentResponse(BaseModel):
  1683. thoughts: str
  1684. response: Literal["happy", "sad", "neutral"]
  1685. create_result = await openai_client.create(
  1686. messages=[UserMessage(content="I am happy.", source="user")],
  1687. extra_create_args={
  1688. "response_format": {
  1689. "type": "json_schema",
  1690. "json_schema": {
  1691. "name": "AgentResponse",
  1692. "description": "Agent response",
  1693. "schema": AgentResponse.model_json_schema(),
  1694. },
  1695. }
  1696. },
  1697. )
  1698. assert isinstance(create_result.content, str)
  1699. assert len(create_result.content) > 0
  1700. response = AgentResponse.model_validate(json.loads(create_result.content))
  1701. assert response.thoughts
  1702. assert response.response in ["happy", "sad", "neutral"]
  1703. @pytest.mark.asyncio
  1704. @pytest.mark.parametrize(
  1705. "model",
  1706. ["gpt-4.1-nano", "gemini-1.5-flash"],
  1707. )
  1708. async def test_openai_structured_output(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  1709. class AgentResponse(BaseModel):
  1710. thoughts: str
  1711. response: Literal["happy", "sad", "neutral"]
  1712. # Test that the openai client was called with the correct response format.
  1713. create_result = await openai_client.create(
  1714. messages=[UserMessage(content="I am happy.", source="user")], json_output=AgentResponse
  1715. )
  1716. assert isinstance(create_result.content, str)
  1717. response = AgentResponse.model_validate(json.loads(create_result.content))
  1718. assert response.thoughts
  1719. assert response.response in ["happy", "sad", "neutral"]
  1720. @pytest.mark.asyncio
  1721. @pytest.mark.parametrize(
  1722. "model",
  1723. ["gpt-4.1-nano", "gemini-1.5-flash"],
  1724. )
  1725. async def test_openai_structured_output_with_streaming(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  1726. class AgentResponse(BaseModel):
  1727. thoughts: str
  1728. response: Literal["happy", "sad", "neutral"]
  1729. # Test that the openai client was called with the correct response format.
  1730. stream = openai_client.create_stream(
  1731. messages=[UserMessage(content="I am happy.", source="user")], json_output=AgentResponse
  1732. )
  1733. chunks: List[str | CreateResult] = []
  1734. async for chunk in stream:
  1735. chunks.append(chunk)
  1736. assert len(chunks) > 0
  1737. assert isinstance(chunks[-1], CreateResult)
  1738. assert isinstance(chunks[-1].content, str)
  1739. response = AgentResponse.model_validate(json.loads(chunks[-1].content))
  1740. assert response.thoughts
  1741. assert response.response in ["happy", "sad", "neutral"]
  1742. @pytest.mark.asyncio
  1743. @pytest.mark.parametrize(
  1744. "model",
  1745. [
  1746. "gpt-4.1-nano",
  1747. # "gemini-1.5-flash", # Gemini models do not support structured output with tool calls from model client.
  1748. ],
  1749. )
  1750. async def test_openai_structured_output_with_tool_calls(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  1751. class AgentResponse(BaseModel):
  1752. thoughts: str
  1753. response: Literal["happy", "sad", "neutral"]
  1754. def sentiment_analysis(text: str) -> str:
  1755. """Given a text, return the sentiment."""
  1756. return "happy" if "happy" in text else "sad" if "sad" in text else "neutral"
  1757. tool = FunctionTool(sentiment_analysis, description="Sentiment Analysis", strict=True)
  1758. extra_create_args = {"tool_choice": "required"}
  1759. response1 = await openai_client.create(
  1760. messages=[
  1761. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1762. UserMessage(content="I am happy.", source="user"),
  1763. ],
  1764. tools=[tool],
  1765. extra_create_args=extra_create_args,
  1766. json_output=AgentResponse,
  1767. )
  1768. assert isinstance(response1.content, list)
  1769. assert len(response1.content) == 1
  1770. assert isinstance(response1.content[0], FunctionCall)
  1771. assert response1.content[0].name == "sentiment_analysis"
  1772. assert json.loads(response1.content[0].arguments) == {"text": "I am happy."}
  1773. assert response1.finish_reason == "function_calls"
  1774. response2 = await openai_client.create(
  1775. messages=[
  1776. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1777. UserMessage(content="I am happy.", source="user"),
  1778. AssistantMessage(content=response1.content, source="assistant"),
  1779. FunctionExecutionResultMessage(
  1780. content=[
  1781. FunctionExecutionResult(
  1782. content="happy", call_id=response1.content[0].id, is_error=False, name=tool.name
  1783. )
  1784. ]
  1785. ),
  1786. ],
  1787. json_output=AgentResponse,
  1788. )
  1789. assert isinstance(response2.content, str)
  1790. parsed_response = AgentResponse.model_validate(json.loads(response2.content))
  1791. assert parsed_response.thoughts
  1792. assert parsed_response.response in ["happy", "sad", "neutral"]
  1793. @pytest.mark.asyncio
  1794. @pytest.mark.parametrize(
  1795. "model",
  1796. [
  1797. "gpt-4.1-nano",
  1798. # "gemini-1.5-flash", # Gemini models do not support structured output with tool calls from model client.
  1799. ],
  1800. )
  1801. async def test_openai_structured_output_with_streaming_tool_calls(
  1802. model: str, openai_client: OpenAIChatCompletionClient
  1803. ) -> None:
  1804. class AgentResponse(BaseModel):
  1805. thoughts: str
  1806. response: Literal["happy", "sad", "neutral"]
  1807. def sentiment_analysis(text: str) -> str:
  1808. """Given a text, return the sentiment."""
  1809. return "happy" if "happy" in text else "sad" if "sad" in text else "neutral"
  1810. tool = FunctionTool(sentiment_analysis, description="Sentiment Analysis", strict=True)
  1811. extra_create_args = {"tool_choice": "required"}
  1812. chunks1: List[str | CreateResult] = []
  1813. stream1 = openai_client.create_stream(
  1814. messages=[
  1815. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1816. UserMessage(content="I am happy.", source="user"),
  1817. ],
  1818. tools=[tool],
  1819. extra_create_args=extra_create_args,
  1820. json_output=AgentResponse,
  1821. )
  1822. async for chunk in stream1:
  1823. chunks1.append(chunk)
  1824. assert len(chunks1) > 0
  1825. create_result1 = chunks1[-1]
  1826. assert isinstance(create_result1, CreateResult)
  1827. assert isinstance(create_result1.content, list)
  1828. assert len(create_result1.content) == 1
  1829. assert isinstance(create_result1.content[0], FunctionCall)
  1830. assert create_result1.content[0].name == "sentiment_analysis"
  1831. assert json.loads(create_result1.content[0].arguments) == {"text": "I am happy."}
  1832. assert create_result1.finish_reason == "function_calls"
  1833. stream2 = openai_client.create_stream(
  1834. messages=[
  1835. SystemMessage(content="Analyze input text sentiment using the tool provided."),
  1836. UserMessage(content="I am happy.", source="user"),
  1837. AssistantMessage(content=create_result1.content, source="assistant"),
  1838. FunctionExecutionResultMessage(
  1839. content=[
  1840. FunctionExecutionResult(
  1841. content="happy", call_id=create_result1.content[0].id, is_error=False, name=tool.name
  1842. )
  1843. ]
  1844. ),
  1845. ],
  1846. json_output=AgentResponse,
  1847. )
  1848. chunks2: List[str | CreateResult] = []
  1849. async for chunk in stream2:
  1850. chunks2.append(chunk)
  1851. assert len(chunks2) > 0
  1852. create_result2 = chunks2[-1]
  1853. assert isinstance(create_result2, CreateResult)
  1854. assert isinstance(create_result2.content, str)
  1855. parsed_response = AgentResponse.model_validate(json.loads(create_result2.content))
  1856. assert parsed_response.thoughts
  1857. assert parsed_response.response in ["happy", "sad", "neutral"]
  1858. @pytest.mark.asyncio
  1859. async def test_hugging_face() -> None:
  1860. api_key = os.getenv("HF_TOKEN")
  1861. if not api_key:
  1862. pytest.skip("HF_TOKEN not found in environment variables")
  1863. model_client = OpenAIChatCompletionClient(
  1864. model="microsoft/Phi-3.5-mini-instruct",
  1865. api_key=api_key,
  1866. base_url="https://api-inference.huggingface.co/v1/",
  1867. model_info={
  1868. "function_calling": False,
  1869. "json_output": False,
  1870. "vision": False,
  1871. "family": ModelFamily.UNKNOWN,
  1872. "structured_output": False,
  1873. },
  1874. )
  1875. # Test basic completion
  1876. create_result = await model_client.create(
  1877. messages=[
  1878. SystemMessage(content="You are a helpful assistant."),
  1879. UserMessage(content="Explain to me how AI works.", source="user"),
  1880. ]
  1881. )
  1882. assert isinstance(create_result.content, str)
  1883. assert len(create_result.content) > 0
  1884. @pytest.mark.asyncio
  1885. async def test_ollama() -> None:
  1886. model = "deepseek-r1:1.5b"
  1887. model_info: ModelInfo = {
  1888. "function_calling": False,
  1889. "json_output": False,
  1890. "vision": False,
  1891. "family": ModelFamily.R1,
  1892. "structured_output": False,
  1893. }
  1894. # Check if the model is running locally.
  1895. try:
  1896. async with httpx.AsyncClient() as client:
  1897. response = await client.get(f"http://localhost:11434/v1/models/{model}")
  1898. response.raise_for_status()
  1899. except httpx.HTTPStatusError as e:
  1900. pytest.skip(f"{model} model is not running locally: {e}")
  1901. except httpx.ConnectError as e:
  1902. pytest.skip(f"Ollama is not running locally: {e}")
  1903. model_client = OpenAIChatCompletionClient(
  1904. model=model,
  1905. api_key="placeholder",
  1906. base_url="http://localhost:11434/v1",
  1907. model_info=model_info,
  1908. )
  1909. # Test basic completion with the Ollama deepseek-r1:1.5b model.
  1910. create_result = await model_client.create(
  1911. messages=[
  1912. UserMessage(
  1913. content="Taking two balls from a bag of 10 green balls and 20 red balls, "
  1914. "what is the probability of getting a green and a red balls?",
  1915. source="user",
  1916. ),
  1917. ]
  1918. )
  1919. assert isinstance(create_result.content, str)
  1920. assert len(create_result.content) > 0
  1921. assert create_result.finish_reason == "stop"
  1922. assert create_result.usage is not None
  1923. if model_info["family"] == ModelFamily.R1:
  1924. assert create_result.thought is not None
  1925. # Test streaming completion with the Ollama deepseek-r1:1.5b model.
  1926. chunks: List[str | CreateResult] = []
  1927. async for chunk in model_client.create_stream(
  1928. messages=[
  1929. UserMessage(
  1930. content="Taking two balls from a bag of 10 green balls and 20 red balls, "
  1931. "what is the probability of getting a green and a red balls?",
  1932. source="user",
  1933. ),
  1934. ]
  1935. ):
  1936. chunks.append(chunk)
  1937. assert len(chunks) > 0
  1938. assert isinstance(chunks[-1], CreateResult)
  1939. assert chunks[-1].finish_reason == "stop"
  1940. assert len(chunks[-1].content) > 0
  1941. assert chunks[-1].usage is not None
  1942. if model_info["family"] == ModelFamily.R1:
  1943. assert chunks[-1].thought is not None
  1944. @pytest.mark.asyncio
  1945. async def test_add_name_prefixes(monkeypatch: pytest.MonkeyPatch) -> None:
  1946. sys_message = SystemMessage(content="You are a helpful AI agent, and you answer questions in a friendly way.")
  1947. assistant_message = AssistantMessage(content="Hello, how can I help you?", source="Assistant")
  1948. user_text_message = UserMessage(content="Hello, I am from Seattle.", source="Adam")
  1949. user_mm_message = UserMessage(
  1950. content=[
  1951. "Here is a postcard from Seattle:",
  1952. Image.from_base64(
  1953. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
  1954. ),
  1955. ],
  1956. source="Adam",
  1957. )
  1958. # Default conversion
  1959. oai_sys = to_oai_type(sys_message)[0]
  1960. oai_asst = to_oai_type(assistant_message)[0]
  1961. oai_text = to_oai_type(user_text_message)[0]
  1962. oai_mm = to_oai_type(user_mm_message)[0]
  1963. converted_sys = to_oai_type(sys_message, prepend_name=True)[0]
  1964. converted_asst = to_oai_type(assistant_message, prepend_name=True)[0]
  1965. converted_text = to_oai_type(user_text_message, prepend_name=True)[0]
  1966. converted_mm = to_oai_type(user_mm_message, prepend_name=True)[0]
  1967. # Invariants
  1968. assert "content" in oai_sys
  1969. assert "content" in oai_asst
  1970. assert "content" in oai_text
  1971. assert "content" in oai_mm
  1972. assert "content" in converted_sys
  1973. assert "content" in converted_asst
  1974. assert "content" in converted_text
  1975. assert "content" in converted_mm
  1976. assert oai_sys["role"] == converted_sys["role"]
  1977. assert oai_sys["content"] == converted_sys["content"]
  1978. assert oai_asst["role"] == converted_asst["role"]
  1979. assert oai_asst["content"] == converted_asst["content"]
  1980. assert oai_text["role"] == converted_text["role"]
  1981. assert oai_mm["role"] == converted_mm["role"]
  1982. assert isinstance(oai_mm["content"], list)
  1983. assert isinstance(converted_mm["content"], list)
  1984. assert len(oai_mm["content"]) == len(converted_mm["content"])
  1985. assert "text" in converted_mm["content"][0]
  1986. assert "text" in oai_mm["content"][0]
  1987. # Name prepended
  1988. assert str(converted_text["content"]) == "Adam said:\n" + str(oai_text["content"])
  1989. assert str(converted_mm["content"][0]["text"]) == "Adam said:\n" + str(oai_mm["content"][0]["text"])
  1990. @pytest.mark.asyncio
  1991. @pytest.mark.parametrize(
  1992. "model",
  1993. [
  1994. "gpt-4.1-nano",
  1995. "gemini-1.5-flash",
  1996. "claude-3-5-haiku-20241022",
  1997. ],
  1998. )
  1999. async def test_muliple_system_message(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  2000. """Test multiple system messages in a single request."""
  2001. # Test multiple system messages
  2002. messages: List[LLMMessage] = [
  2003. SystemMessage(content="When you say anything Start with 'FOO'"),
  2004. SystemMessage(content="When you say anything End with 'BAR'"),
  2005. UserMessage(content="Just say '.'", source="user"),
  2006. ]
  2007. result = await openai_client.create(messages=messages)
  2008. result_content = result.content
  2009. assert isinstance(result_content, str)
  2010. result_content = result_content.strip()
  2011. assert result_content[:3] == "FOO"
  2012. assert result_content[-3:] == "BAR"
  2013. @pytest.mark.asyncio
  2014. async def test_system_message_merge_with_continuous_system_messages_models() -> None:
  2015. """Tests that system messages are merged correctly for Gemini models."""
  2016. # Create a mock client
  2017. mock_client = MagicMock()
  2018. client = BaseOpenAIChatCompletionClient(
  2019. client=mock_client,
  2020. create_args={"model": "gemini-1.5-flash"},
  2021. model_info={
  2022. "vision": False,
  2023. "function_calling": False,
  2024. "json_output": False,
  2025. "family": "unknown",
  2026. "structured_output": False,
  2027. "multiple_system_messages": False,
  2028. },
  2029. )
  2030. # Create two system messages
  2031. messages: List[LLMMessage] = [
  2032. SystemMessage(content="I am system message 1"),
  2033. SystemMessage(content="I am system message 2"),
  2034. UserMessage(content="Hello", source="user"),
  2035. ]
  2036. # Process the messages
  2037. # pylint: disable=protected-access
  2038. # The method is protected, but we need to test it
  2039. create_params = client._process_create_args( # pyright: ignore[reportPrivateUsage]
  2040. messages=messages,
  2041. tools=[],
  2042. json_output=None,
  2043. extra_create_args={},
  2044. tool_choice="none",
  2045. )
  2046. # Extract the actual messages from the result
  2047. oai_messages = create_params.messages
  2048. # Check that there is only one system message and it contains the merged content
  2049. system_messages = [msg for msg in oai_messages if msg["role"] == "system"]
  2050. assert len(system_messages) == 1
  2051. assert system_messages[0]["content"] == "I am system message 1\nI am system message 2"
  2052. # Check that the user message is preserved
  2053. user_messages = [msg for msg in oai_messages if msg["role"] == "user"]
  2054. assert len(user_messages) == 1
  2055. assert user_messages[0]["content"] == "Hello"
  2056. @pytest.mark.asyncio
  2057. async def test_system_message_merge_with_non_continuous_messages() -> None:
  2058. """Tests that an error is raised when non-continuous system messages are provided."""
  2059. # Create a mock client
  2060. mock_client = MagicMock()
  2061. client = BaseOpenAIChatCompletionClient(
  2062. client=mock_client,
  2063. create_args={"model": "gemini-1.5-flash"},
  2064. model_info={
  2065. "vision": False,
  2066. "function_calling": False,
  2067. "json_output": False,
  2068. "family": "unknown",
  2069. "structured_output": False,
  2070. "multiple_system_messages": False,
  2071. },
  2072. )
  2073. # Create non-continuous system messages
  2074. messages: List[LLMMessage] = [
  2075. SystemMessage(content="I am system message 1"),
  2076. UserMessage(content="Hello", source="user"),
  2077. SystemMessage(content="I am system message 2"),
  2078. ]
  2079. # Process should raise ValueError
  2080. with pytest.raises(ValueError, match="Multiple and Not continuous system messages are not supported"):
  2081. # pylint: disable=protected-access
  2082. # The method is protected, but we need to test it
  2083. client._process_create_args( # pyright: ignore[reportPrivateUsage]
  2084. messages=messages,
  2085. tools=[],
  2086. json_output=None,
  2087. extra_create_args={},
  2088. tool_choice="none",
  2089. )
  2090. @pytest.mark.asyncio
  2091. async def test_system_message_not_merged_for_multiple_system_messages_true() -> None:
  2092. """Tests that system messages aren't modified for non-Gemini models."""
  2093. # Create a mock client
  2094. mock_client = MagicMock()
  2095. client = BaseOpenAIChatCompletionClient(
  2096. client=mock_client,
  2097. create_args={"model": "gpt-4.1-nano"},
  2098. model_info={
  2099. "vision": False,
  2100. "function_calling": False,
  2101. "json_output": False,
  2102. "family": "unknown",
  2103. "structured_output": False,
  2104. "multiple_system_messages": True,
  2105. },
  2106. )
  2107. # Create two system messages
  2108. messages: List[LLMMessage] = [
  2109. SystemMessage(content="I am system message 1"),
  2110. SystemMessage(content="I am system message 2"),
  2111. UserMessage(content="Hello", source="user"),
  2112. ]
  2113. # Process the messages
  2114. # pylint: disable=protected-access
  2115. # The method is protected, but we need to test it
  2116. create_params = client._process_create_args( # pyright: ignore[reportPrivateUsage]
  2117. messages=messages,
  2118. tools=[],
  2119. json_output=None,
  2120. extra_create_args={},
  2121. tool_choice="none",
  2122. )
  2123. # Extract the actual messages from the result
  2124. oai_messages = create_params.messages
  2125. # Check that there are two system messages preserved
  2126. system_messages = [msg for msg in oai_messages if msg["role"] == "system"]
  2127. assert len(system_messages) == 2
  2128. assert system_messages[0]["content"] == "I am system message 1"
  2129. assert system_messages[1]["content"] == "I am system message 2"
  2130. @pytest.mark.asyncio
  2131. async def test_no_system_messages_for_gemini_model() -> None:
  2132. """Tests behavior when no system messages are provided to a Gemini model."""
  2133. # Create a mock client
  2134. mock_client = MagicMock()
  2135. client = BaseOpenAIChatCompletionClient(
  2136. client=mock_client,
  2137. create_args={"model": "gemini-1.5-flash"},
  2138. model_info={
  2139. "vision": False,
  2140. "function_calling": False,
  2141. "json_output": False,
  2142. "family": "unknown",
  2143. "structured_output": False,
  2144. },
  2145. )
  2146. # Create messages with no system message
  2147. messages: List[LLMMessage] = [
  2148. UserMessage(content="Hello", source="user"),
  2149. AssistantMessage(content="Hi there", source="assistant"),
  2150. ]
  2151. # Process the messages
  2152. # pylint: disable=protected-access
  2153. # The method is protected, but we need to test it
  2154. create_params = client._process_create_args( # pyright: ignore[reportPrivateUsage]
  2155. messages=messages,
  2156. tools=[],
  2157. json_output=None,
  2158. extra_create_args={},
  2159. tool_choice="none",
  2160. )
  2161. # Extract the actual messages from the result
  2162. oai_messages = create_params.messages
  2163. # Check that there are no system messages
  2164. system_messages = [msg for msg in oai_messages if msg["role"] == "system"]
  2165. assert len(system_messages) == 0
  2166. # Check that other messages are preserved
  2167. user_messages = [msg for msg in oai_messages if msg["role"] == "user"]
  2168. assistant_messages = [msg for msg in oai_messages if msg["role"] == "assistant"]
  2169. assert len(user_messages) == 1
  2170. assert len(assistant_messages) == 1
  2171. @pytest.mark.asyncio
  2172. async def test_single_system_message_for_gemini_model() -> None:
  2173. """Tests that a single system message is preserved for Gemini models."""
  2174. # Create a mock client
  2175. mock_client = MagicMock()
  2176. client = BaseOpenAIChatCompletionClient(
  2177. client=mock_client,
  2178. create_args={"model": "gemini-1.5-flash"},
  2179. model_info={
  2180. "vision": False,
  2181. "function_calling": False,
  2182. "json_output": False,
  2183. "family": "unknown",
  2184. "structured_output": False,
  2185. },
  2186. )
  2187. # Create messages with a single system message
  2188. messages: List[LLMMessage] = [
  2189. SystemMessage(content="I am the only system message"),
  2190. UserMessage(content="Hello", source="user"),
  2191. ]
  2192. # Process the messages
  2193. # pylint: disable=protected-access
  2194. # The method is protected, but we need to test it
  2195. create_params = client._process_create_args( # pyright: ignore[reportPrivateUsage]
  2196. messages=messages,
  2197. tools=[],
  2198. json_output=None,
  2199. extra_create_args={},
  2200. tool_choice="auto",
  2201. )
  2202. # Extract the actual messages from the result
  2203. oai_messages = create_params.messages
  2204. # Check that there is exactly one system message with the correct content
  2205. system_messages = [msg for msg in oai_messages if msg["role"] == "system"]
  2206. assert len(system_messages) == 1
  2207. assert system_messages[0]["content"] == "I am the only system message"
  2208. def noop(input: str) -> str:
  2209. return "done"
  2210. @pytest.mark.asyncio
  2211. @pytest.mark.parametrize("model", ["gemini-1.5-flash"])
  2212. async def test_empty_assistant_content_with_gemini(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  2213. # Test tool calling
  2214. tool = FunctionTool(noop, name="noop", description="No-op tool")
  2215. messages: List[LLMMessage] = [UserMessage(content="Call noop", source="user")]
  2216. result = await openai_client.create(messages=messages, tools=[tool])
  2217. assert isinstance(result.content, list)
  2218. tool_call = result.content[0]
  2219. assert isinstance(tool_call, FunctionCall)
  2220. # reply with empty string as thought (== content)
  2221. messages.append(AssistantMessage(content=result.content, thought="", source="assistant"))
  2222. messages.append(
  2223. FunctionExecutionResultMessage(
  2224. content=[
  2225. FunctionExecutionResult(
  2226. content="done",
  2227. call_id=tool_call.id,
  2228. is_error=False,
  2229. name=tool_call.name,
  2230. )
  2231. ]
  2232. )
  2233. )
  2234. # This will crash if _set_empty_to_whitespace is not applied to "thought"
  2235. result = await openai_client.create(messages=messages)
  2236. assert isinstance(result.content, str)
  2237. assert result.content.strip() != "" or result.content == " "
  2238. @pytest.mark.asyncio
  2239. @pytest.mark.parametrize(
  2240. "model",
  2241. [
  2242. "gpt-4.1-nano",
  2243. "gemini-1.5-flash",
  2244. "claude-3-5-haiku-20241022",
  2245. ],
  2246. )
  2247. async def test_empty_assistant_content_string_with_some_model(
  2248. model: str, openai_client: OpenAIChatCompletionClient
  2249. ) -> None:
  2250. # message: assistant is response empty content
  2251. messages: list[LLMMessage] = [
  2252. UserMessage(content="Say something", source="user"),
  2253. AssistantMessage(content="test", source="assistant"),
  2254. UserMessage(content="", source="user"),
  2255. ]
  2256. # This will crash if _set_empty_to_whitespace is not applied to "content"
  2257. result = await openai_client.create(messages=messages)
  2258. assert isinstance(result.content, str)
  2259. def test_openai_model_registry_find_well() -> None:
  2260. model = "gpt-4o"
  2261. client1 = OpenAIChatCompletionClient(model=model, api_key="test")
  2262. client2 = OpenAIChatCompletionClient(
  2263. model=model,
  2264. model_info={
  2265. "vision": False,
  2266. "function_calling": False,
  2267. "json_output": False,
  2268. "structured_output": False,
  2269. "family": ModelFamily.UNKNOWN,
  2270. },
  2271. api_key="test",
  2272. )
  2273. def get_regitered_transformer(client: OpenAIChatCompletionClient) -> TransformerMap:
  2274. model_name = client._create_args["model"] # pyright: ignore[reportPrivateUsage]
  2275. model_family = client.model_info["family"]
  2276. return get_transformer("openai", model_name, model_family)
  2277. assert get_regitered_transformer(client1) == get_regitered_transformer(client2)
  2278. @pytest.mark.asyncio
  2279. @pytest.mark.parametrize(
  2280. "model",
  2281. [
  2282. "gpt-4.1-nano",
  2283. ],
  2284. )
  2285. async def test_openai_model_unknown_message_type(model: str, openai_client: OpenAIChatCompletionClient) -> None:
  2286. class WrongMessage:
  2287. content = "foo"
  2288. source = "bar"
  2289. messages: List[WrongMessage] = [WrongMessage()]
  2290. with pytest.raises(ValueError, match="Unknown message type"):
  2291. await openai_client.create(messages=messages) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
  2292. @pytest.mark.asyncio
  2293. @pytest.mark.parametrize(
  2294. "model",
  2295. [
  2296. "claude-3-5-haiku-20241022",
  2297. ],
  2298. )
  2299. async def test_claude_trailing_whitespace_at_last_assistant_content(
  2300. model: str, openai_client: OpenAIChatCompletionClient
  2301. ) -> None:
  2302. messages: list[LLMMessage] = [
  2303. UserMessage(content="foo", source="user"),
  2304. UserMessage(content="bar", source="user"),
  2305. AssistantMessage(content="foobar ", source="assistant"),
  2306. ]
  2307. result = await openai_client.create(messages=messages)
  2308. assert isinstance(result.content, str)
  2309. def test_rstrip_railing_whitespace_at_last_assistant_content() -> None:
  2310. messages: list[LLMMessage] = [
  2311. UserMessage(content="foo", source="user"),
  2312. UserMessage(content="bar", source="user"),
  2313. AssistantMessage(content="foobar ", source="assistant"),
  2314. ]
  2315. # This will crash if _rstrip_railing_whitespace_at_last_assistant_content is not applied to "content"
  2316. dummy_client = OpenAIChatCompletionClient(model="claude-3-5-haiku-20241022", api_key="dummy-key")
  2317. result = dummy_client._rstrip_last_assistant_message(messages) # pyright: ignore[reportPrivateUsage]
  2318. assert isinstance(result[-1].content, str)
  2319. assert result[-1].content == "foobar"
  2320. def test_find_model_family() -> None:
  2321. assert _find_model_family("openai", "gpt-4") == ModelFamily.GPT_4
  2322. assert _find_model_family("openai", "gpt-4-latest") == ModelFamily.GPT_4
  2323. assert _find_model_family("openai", "gpt-4o") == ModelFamily.GPT_4O
  2324. assert _find_model_family("openai", "gemini-2.0-flash") == ModelFamily.GEMINI_2_0_FLASH
  2325. assert _find_model_family("openai", "claude-3-5-haiku-20241022") == ModelFamily.CLAUDE_3_5_HAIKU
  2326. assert _find_model_family("openai", "error") == ModelFamily.UNKNOWN
  2327. @pytest.mark.asyncio
  2328. @pytest.mark.parametrize(
  2329. "model",
  2330. [
  2331. "gpt-4.1-nano",
  2332. "gemini-1.5-flash",
  2333. "claude-3-5-haiku-20241022",
  2334. ],
  2335. )
  2336. async def test_multimodal_message_test(
  2337. model: str, openai_client: OpenAIChatCompletionClient, monkeypatch: pytest.MonkeyPatch
  2338. ) -> None:
  2339. # Test that the multimodal message is converted to the correct format
  2340. img = Image.from_base64(
  2341. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
  2342. )
  2343. multi_modal_message = MultiModalMessage(content=["Can you describe the content of this image?", img], source="user")
  2344. ocr_agent = AssistantAgent(
  2345. name="ocr_agent", model_client=openai_client, system_message="""You are a helpful agent."""
  2346. )
  2347. _ = await ocr_agent.run(task=multi_modal_message)
  2348. @pytest.mark.asyncio
  2349. async def test_mistral_remove_name() -> None:
  2350. # Test that the name pramaeter is removed from the message
  2351. # when the model is Mistral
  2352. message = UserMessage(content="foo", source="user")
  2353. params = to_oai_type(message, prepend_name=False, model="mistral-7b", model_family=ModelFamily.MISTRAL)
  2354. assert ("name" in params[0]) is False
  2355. # when the model is gpt-4o, the name parameter is not removed
  2356. params = to_oai_type(message, prepend_name=False, model="gpt-4o", model_family=ModelFamily.GPT_4O)
  2357. assert ("name" in params[0]) is True
  2358. @pytest.mark.asyncio
  2359. async def test_include_name_in_message() -> None:
  2360. """Test that include_name_in_message parameter controls the name field."""
  2361. # Test with UserMessage
  2362. user_message = UserMessage(content="Hello, I am from Seattle.", source="Adam")
  2363. # Test with include_name_in_message=True (default)
  2364. result_with_name = to_oai_type(user_message, include_name_in_message=True)[0]
  2365. assert "name" in result_with_name
  2366. assert result_with_name["name"] == "Adam" # type: ignore[typeddict-item]
  2367. assert result_with_name["role"] == "user"
  2368. assert result_with_name["content"] == "Hello, I am from Seattle."
  2369. # Test with include_name_in_message=False
  2370. result_without_name = to_oai_type(user_message, include_name_in_message=False)[0]
  2371. assert "name" not in result_without_name
  2372. assert result_without_name["role"] == "user"
  2373. assert result_without_name["content"] == "Hello, I am from Seattle."
  2374. # Test with AssistantMessage (should not have name field regardless)
  2375. assistant_message = AssistantMessage(content="Hello, how can I help you?", source="Assistant")
  2376. # Test with include_name_in_message=True
  2377. result_assistant_with_name = to_oai_type(assistant_message, include_name_in_message=True)[0]
  2378. assert "name" not in result_assistant_with_name
  2379. assert result_assistant_with_name["role"] == "assistant"
  2380. # Test with include_name_in_message=False
  2381. result_assistant_without_name = to_oai_type(assistant_message, include_name_in_message=False)[0]
  2382. assert "name" not in result_assistant_without_name
  2383. assert result_assistant_without_name["role"] == "assistant"
  2384. # Test with SystemMessage (should not have name field regardless)
  2385. system_message = SystemMessage(content="You are a helpful assistant.")
  2386. result_system_with_name = to_oai_type(system_message, include_name_in_message=True)[0]
  2387. result_system_without_name = to_oai_type(system_message, include_name_in_message=False)[0]
  2388. assert "name" not in result_system_with_name
  2389. assert "name" not in result_system_without_name
  2390. assert result_system_with_name["role"] == "system"
  2391. assert result_system_without_name["role"] == "system"
  2392. # Test default behavior (should include name when parameter not specified)
  2393. result_default = to_oai_type(user_message)[0] # include_name_in_message defaults to True
  2394. assert "name" in result_default
  2395. assert result_default["name"] == "Adam" # type: ignore[typeddict-item]
  2396. @pytest.mark.asyncio
  2397. async def test_include_name_with_different_models() -> None:
  2398. """Test that include_name_in_message works with different model families."""
  2399. user_message = UserMessage(content="Hello", source="User")
  2400. # Test with GPT-4o model (normally includes name)
  2401. result_gpt4o_with_name = to_oai_type(
  2402. user_message, model="gpt-4o", model_family=ModelFamily.GPT_4O, include_name_in_message=True
  2403. )[0]
  2404. result_gpt4o_without_name = to_oai_type(
  2405. user_message, model="gpt-4o", model_family=ModelFamily.GPT_4O, include_name_in_message=False
  2406. )[0]
  2407. assert "name" in result_gpt4o_with_name
  2408. assert "name" not in result_gpt4o_without_name
  2409. # Test with Mistral model (normally excludes name, but should still respect the parameter)
  2410. result_mistral_with_name = to_oai_type(
  2411. user_message, model="mistral-7b", model_family=ModelFamily.MISTRAL, include_name_in_message=True
  2412. )[0]
  2413. result_mistral_without_name = to_oai_type(
  2414. user_message, model="mistral-7b", model_family=ModelFamily.MISTRAL, include_name_in_message=False
  2415. )[0]
  2416. # Note: Mistral transformers are specifically built without _set_name, so they won't have name regardless
  2417. # But our parameter still controls the behavior consistently
  2418. assert "name" not in result_mistral_with_name # Mistral design excludes names
  2419. assert "name" not in result_mistral_without_name
  2420. # Test with unknown model (uses default transformer)
  2421. result_unknown_with_name = to_oai_type(
  2422. user_message, model="some-custom-model", model_family=ModelFamily.UNKNOWN, include_name_in_message=True
  2423. )[0]
  2424. result_unknown_without_name = to_oai_type(
  2425. user_message, model="some-custom-model", model_family=ModelFamily.UNKNOWN, include_name_in_message=False
  2426. )[0]
  2427. assert "name" in result_unknown_with_name
  2428. assert "name" not in result_unknown_without_name
  2429. @pytest.mark.asyncio
  2430. async def test_mock_tool_choice_specific_tool(monkeypatch: pytest.MonkeyPatch) -> None:
  2431. """Test tool_choice parameter with a specific tool using mocks."""
  2432. def _pass_function(input: str) -> str:
  2433. """Simple passthrough function."""
  2434. return f"Processed: {input}"
  2435. def _add_numbers(a: int, b: int) -> int:
  2436. """Add two numbers together."""
  2437. return a + b
  2438. model = "gpt-4o"
  2439. # Mock successful completion with specific tool call
  2440. chat_completion = ChatCompletion(
  2441. id="id1",
  2442. choices=[
  2443. Choice(
  2444. finish_reason="tool_calls",
  2445. index=0,
  2446. message=ChatCompletionMessage(
  2447. role="assistant",
  2448. content=None,
  2449. tool_calls=[
  2450. ChatCompletionMessageToolCall(
  2451. id="1",
  2452. type="function",
  2453. function=Function(
  2454. name="_pass_function",
  2455. arguments=json.dumps({"input": "hello"}),
  2456. ),
  2457. )
  2458. ],
  2459. ),
  2460. )
  2461. ],
  2462. created=1234567890,
  2463. model=model,
  2464. object="chat.completion",
  2465. usage=CompletionUsage(completion_tokens=10, prompt_tokens=5, total_tokens=15),
  2466. )
  2467. client = OpenAIChatCompletionClient(model=model, api_key="test")
  2468. # Define tools
  2469. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2470. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2471. # Create mock for the chat completions create method
  2472. mock_create = AsyncMock(return_value=chat_completion)
  2473. with monkeypatch.context() as mp:
  2474. mp.setattr(client._client.chat.completions, "create", mock_create) # type: ignore[reportPrivateUsage]
  2475. _ = await client.create(
  2476. messages=[UserMessage(content="Process 'hello'", source="user")],
  2477. tools=[pass_tool, add_tool],
  2478. tool_choice=pass_tool, # Force use of specific tool
  2479. )
  2480. # Verify the correct API call was made
  2481. mock_create.assert_called_once()
  2482. call_args = mock_create.call_args
  2483. # Check that tool_choice was set correctly
  2484. assert "tool_choice" in call_args.kwargs
  2485. assert call_args.kwargs["tool_choice"] == {"type": "function", "function": {"name": "_pass_function"}}
  2486. @pytest.mark.asyncio
  2487. async def test_mock_tool_choice_auto(monkeypatch: pytest.MonkeyPatch) -> None:
  2488. """Test tool_choice parameter with 'auto' setting using mocks."""
  2489. def _pass_function(input: str) -> str:
  2490. """Simple passthrough function."""
  2491. return f"Processed: {input}"
  2492. def _add_numbers(a: int, b: int) -> int:
  2493. """Add two numbers together."""
  2494. return a + b
  2495. model = "gpt-4o"
  2496. # Mock successful completion
  2497. chat_completion = ChatCompletion(
  2498. id="id1",
  2499. choices=[
  2500. Choice(
  2501. finish_reason="tool_calls",
  2502. index=0,
  2503. message=ChatCompletionMessage(
  2504. role="assistant",
  2505. content=None,
  2506. tool_calls=[
  2507. ChatCompletionMessageToolCall(
  2508. id="1",
  2509. type="function",
  2510. function=Function(
  2511. name="_add_numbers",
  2512. arguments=json.dumps({"a": 1, "b": 2}),
  2513. ),
  2514. )
  2515. ],
  2516. ),
  2517. )
  2518. ],
  2519. created=1234567890,
  2520. model=model,
  2521. object="chat.completion",
  2522. usage=CompletionUsage(completion_tokens=10, prompt_tokens=5, total_tokens=15),
  2523. )
  2524. client = OpenAIChatCompletionClient(model=model, api_key="test")
  2525. # Define tools
  2526. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2527. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2528. # Create mock for the chat completions create method
  2529. mock_create = AsyncMock(return_value=chat_completion)
  2530. with monkeypatch.context() as mp:
  2531. mp.setattr(client._client.chat.completions, "create", mock_create) # type: ignore[reportPrivateUsage]
  2532. await client.create(
  2533. messages=[UserMessage(content="Add 1 and 2", source="user")],
  2534. tools=[pass_tool, add_tool],
  2535. tool_choice="auto", # Let model choose
  2536. )
  2537. # Verify the correct API call was made
  2538. mock_create.assert_called_once()
  2539. call_args = mock_create.call_args
  2540. # Check that tool_choice was set correctly
  2541. assert "tool_choice" in call_args.kwargs
  2542. assert call_args.kwargs["tool_choice"] == "auto"
  2543. @pytest.mark.asyncio
  2544. async def test_mock_tool_choice_none(monkeypatch: pytest.MonkeyPatch) -> None:
  2545. """Test tool_choice parameter with None setting using mocks."""
  2546. def _pass_function(input: str) -> str:
  2547. """Simple passthrough function."""
  2548. return f"Processed: {input}"
  2549. model = "gpt-4o"
  2550. # Mock successful completion
  2551. chat_completion = ChatCompletion(
  2552. id="id1",
  2553. choices=[
  2554. Choice(
  2555. finish_reason="stop",
  2556. index=0,
  2557. message=ChatCompletionMessage(
  2558. role="assistant",
  2559. content="I can help you with that!",
  2560. tool_calls=None,
  2561. ),
  2562. )
  2563. ],
  2564. created=1234567890,
  2565. model=model,
  2566. object="chat.completion",
  2567. usage=CompletionUsage(completion_tokens=10, prompt_tokens=5, total_tokens=15),
  2568. )
  2569. client = OpenAIChatCompletionClient(model=model, api_key="test")
  2570. # Define tools
  2571. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2572. # Create mock for the chat completions create method
  2573. mock_create = AsyncMock(return_value=chat_completion)
  2574. with monkeypatch.context() as mp:
  2575. mp.setattr(client._client.chat.completions, "create", mock_create) # type: ignore[reportPrivateUsage]
  2576. await client.create(
  2577. messages=[UserMessage(content="Hello there", source="user")],
  2578. tools=[pass_tool],
  2579. tool_choice="none",
  2580. )
  2581. # Verify the correct API call was made
  2582. mock_create.assert_called_once()
  2583. call_args = mock_create.call_args
  2584. # Check that tool_choice was set to "none" (disabling tool usage)
  2585. assert "tool_choice" in call_args.kwargs
  2586. assert call_args.kwargs["tool_choice"] == "none"
  2587. @pytest.mark.asyncio
  2588. async def test_mock_tool_choice_validation_error() -> None:
  2589. """Test tool_choice validation with invalid tool reference."""
  2590. def _pass_function(input: str) -> str:
  2591. """Simple passthrough function."""
  2592. return f"Processed: {input}"
  2593. def _add_numbers(a: int, b: int) -> int:
  2594. """Add two numbers together."""
  2595. return a + b
  2596. def _different_function(text: str) -> str:
  2597. """Different function."""
  2598. return text
  2599. client = OpenAIChatCompletionClient(model="gpt-4o", api_key="test")
  2600. # Define tools
  2601. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2602. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2603. different_tool = FunctionTool(_different_function, description="Different tool", name="_different_function")
  2604. messages = [UserMessage(content="Hello there", source="user")]
  2605. # Test with a tool that's not in the tools list
  2606. with pytest.raises(
  2607. ValueError, match="tool_choice references '_different_function' but it's not in the provided tools"
  2608. ):
  2609. await client.create(
  2610. messages=messages,
  2611. tools=[pass_tool, add_tool],
  2612. tool_choice=different_tool, # This tool is not in the tools list
  2613. )
  2614. @pytest.mark.asyncio
  2615. async def test_mock_tool_choice_required(monkeypatch: pytest.MonkeyPatch) -> None:
  2616. """Test tool_choice parameter with 'required' setting using mocks."""
  2617. def _pass_function(input: str) -> str:
  2618. """Simple passthrough function."""
  2619. return f"Processed: {input}"
  2620. def _add_numbers(a: int, b: int) -> int:
  2621. """Add two numbers together."""
  2622. return a + b
  2623. model = "gpt-4o"
  2624. # Mock successful completion with tool calls (required forces tool usage)
  2625. chat_completion = ChatCompletion(
  2626. id="id1",
  2627. choices=[
  2628. Choice(
  2629. finish_reason="tool_calls",
  2630. index=0,
  2631. message=ChatCompletionMessage(
  2632. role="assistant",
  2633. content=None,
  2634. tool_calls=[
  2635. ChatCompletionMessageToolCall(
  2636. id="1",
  2637. type="function",
  2638. function=Function(
  2639. name="_pass_function",
  2640. arguments=json.dumps({"input": "hello"}),
  2641. ),
  2642. )
  2643. ],
  2644. ),
  2645. )
  2646. ],
  2647. created=1234567890,
  2648. model=model,
  2649. object="chat.completion",
  2650. usage=CompletionUsage(completion_tokens=10, prompt_tokens=5, total_tokens=15),
  2651. )
  2652. client = OpenAIChatCompletionClient(model=model, api_key="test")
  2653. # Define tools
  2654. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2655. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2656. # Create mock for the chat completions create method
  2657. mock_create = AsyncMock(return_value=chat_completion)
  2658. with monkeypatch.context() as mp:
  2659. mp.setattr(client._client.chat.completions, "create", mock_create) # type: ignore[reportPrivateUsage]
  2660. await client.create(
  2661. messages=[UserMessage(content="Process some text", source="user")],
  2662. tools=[pass_tool, add_tool],
  2663. tool_choice="required", # Force tool usage
  2664. )
  2665. # Verify the correct API call was made
  2666. mock_create.assert_called_once()
  2667. call_args = mock_create.call_args
  2668. # Check that tool_choice was set correctly
  2669. assert "tool_choice" in call_args.kwargs
  2670. assert call_args.kwargs["tool_choice"] == "required"
  2671. # Integration tests for tool_choice using the actual OpenAI API
  2672. @pytest.mark.asyncio
  2673. async def test_openai_tool_choice_specific_tool_integration() -> None:
  2674. """Test tool_choice parameter with a specific tool using the actual OpenAI API."""
  2675. api_key = os.getenv("OPENAI_API_KEY")
  2676. if not api_key:
  2677. pytest.skip("OPENAI_API_KEY not found in environment variables")
  2678. def _pass_function(input: str) -> str:
  2679. """Simple passthrough function."""
  2680. return f"Processed: {input}"
  2681. def _add_numbers(a: int, b: int) -> int:
  2682. """Add two numbers together."""
  2683. return a + b
  2684. model = "gpt-4o-mini"
  2685. client = OpenAIChatCompletionClient(model=model, api_key=api_key)
  2686. # Define tools
  2687. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2688. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2689. # Test forcing use of specific tool
  2690. result = await client.create(
  2691. messages=[UserMessage(content="Process the word 'hello'", source="user")],
  2692. tools=[pass_tool, add_tool],
  2693. tool_choice=pass_tool, # Force use of specific tool
  2694. )
  2695. assert isinstance(result.content, list)
  2696. assert len(result.content) == 1
  2697. assert isinstance(result.content[0], FunctionCall)
  2698. assert result.content[0].name == "_pass_function"
  2699. assert result.finish_reason == "function_calls"
  2700. assert result.usage is not None
  2701. @pytest.mark.asyncio
  2702. async def test_openai_tool_choice_auto_integration() -> None:
  2703. """Test tool_choice parameter with 'auto' setting using the actual OpenAI API."""
  2704. api_key = os.getenv("OPENAI_API_KEY")
  2705. if not api_key:
  2706. pytest.skip("OPENAI_API_KEY not found in environment variables")
  2707. def _pass_function(input: str) -> str:
  2708. """Simple passthrough function."""
  2709. return f"Processed: {input}"
  2710. def _add_numbers(a: int, b: int) -> int:
  2711. """Add two numbers together."""
  2712. return a + b
  2713. model = "gpt-4o-mini"
  2714. client = OpenAIChatCompletionClient(model=model, api_key=api_key)
  2715. # Define tools
  2716. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2717. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2718. # Test auto tool choice - model should choose to use add_numbers for math
  2719. result = await client.create(
  2720. messages=[UserMessage(content="What is 15 plus 27?", source="user")],
  2721. tools=[pass_tool, add_tool],
  2722. tool_choice="auto", # Let model choose
  2723. )
  2724. assert isinstance(result.content, list)
  2725. assert len(result.content) == 1
  2726. assert isinstance(result.content[0], FunctionCall)
  2727. assert result.content[0].name == "_add_numbers"
  2728. assert result.finish_reason == "function_calls"
  2729. assert result.usage is not None
  2730. # Parse arguments to verify correct values
  2731. args = json.loads(result.content[0].arguments)
  2732. assert args["a"] == 15
  2733. assert args["b"] == 27
  2734. @pytest.mark.asyncio
  2735. async def test_openai_tool_choice_none_integration() -> None:
  2736. """Test tool_choice parameter with 'none' setting using the actual OpenAI API."""
  2737. api_key = os.getenv("OPENAI_API_KEY")
  2738. if not api_key:
  2739. pytest.skip("OPENAI_API_KEY not found in environment variables")
  2740. def _pass_function(input: str) -> str:
  2741. """Simple passthrough function."""
  2742. return f"Processed: {input}"
  2743. model = "gpt-4o-mini"
  2744. client = OpenAIChatCompletionClient(model=model, api_key=api_key)
  2745. # Define tools
  2746. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2747. # Test none tool choice - model should not use any tools
  2748. result = await client.create(
  2749. messages=[UserMessage(content="Hello there, how are you?", source="user")],
  2750. tools=[pass_tool],
  2751. tool_choice="none", # Disable tool usage
  2752. )
  2753. assert isinstance(result.content, str)
  2754. assert len(result.content) > 0
  2755. assert result.finish_reason == "stop"
  2756. assert result.usage is not None
  2757. @pytest.mark.asyncio
  2758. async def test_openai_tool_choice_required_integration() -> None:
  2759. """Test tool_choice parameter with 'required' setting using the actual OpenAI API."""
  2760. api_key = os.getenv("OPENAI_API_KEY")
  2761. if not api_key:
  2762. pytest.skip("OPENAI_API_KEY not found in environment variables")
  2763. def _pass_function(input: str) -> str:
  2764. """Simple passthrough function."""
  2765. return f"Processed: {input}"
  2766. def _add_numbers(a: int, b: int) -> int:
  2767. """Add two numbers together."""
  2768. return a + b
  2769. model = "gpt-4o-mini"
  2770. client = OpenAIChatCompletionClient(model=model, api_key=api_key)
  2771. # Define tools
  2772. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2773. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2774. # Test required tool choice - model must use a tool even for general conversation
  2775. result = await client.create(
  2776. messages=[UserMessage(content="Say hello to me", source="user")],
  2777. tools=[pass_tool, add_tool],
  2778. tool_choice="required", # Force tool usage
  2779. )
  2780. assert isinstance(result.content, list)
  2781. assert len(result.content) == 1
  2782. assert isinstance(result.content[0], FunctionCall)
  2783. assert result.content[0].name in ["_pass_function", "_add_numbers"]
  2784. assert result.finish_reason == "function_calls"
  2785. assert result.usage is not None
  2786. @pytest.mark.asyncio
  2787. async def test_openai_tool_choice_validation_error_integration() -> None:
  2788. """Test tool_choice validation with invalid tool reference using the actual OpenAI API."""
  2789. api_key = os.getenv("OPENAI_API_KEY")
  2790. if not api_key:
  2791. pytest.skip("OPENAI_API_KEY not found in environment variables")
  2792. def _pass_function(input: str) -> str:
  2793. """Simple passthrough function."""
  2794. return f"Processed: {input}"
  2795. def _add_numbers(a: int, b: int) -> int:
  2796. """Add two numbers together."""
  2797. return a + b
  2798. def _different_function(text: str) -> str:
  2799. """Different function."""
  2800. return text
  2801. model = "gpt-4o-mini"
  2802. client = OpenAIChatCompletionClient(model=model, api_key=api_key)
  2803. # Define tools
  2804. pass_tool = FunctionTool(_pass_function, description="Process input text", name="_pass_function")
  2805. add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="_add_numbers")
  2806. different_tool = FunctionTool(_different_function, description="Different tool", name="_different_function")
  2807. messages = [UserMessage(content="Hello there", source="user")]
  2808. # Test with a tool that's not in the tools list
  2809. with pytest.raises(
  2810. ValueError, match="tool_choice references '_different_function' but it's not in the provided tools"
  2811. ):
  2812. await client.create(
  2813. messages=messages,
  2814. tools=[pass_tool, add_tool],
  2815. tool_choice=different_tool, # This tool is not in the tools list
  2816. )
  2817. # GPT-5 model tests
  2818. def test_gpt5_model_resolution() -> None:
  2819. """Test that GPT-5 models resolve correctly."""
  2820. assert resolve_model("gpt-5") == "gpt-5-2025-08-07"
  2821. assert resolve_model("gpt-5-mini") == "gpt-5-mini-2025-08-07"
  2822. assert resolve_model("gpt-5-nano") == "gpt-5-nano-2025-08-07"
  2823. def test_gpt5_model_info() -> None:
  2824. """Test that GPT-5 models have correct capabilities."""
  2825. from autogen_ext.models.openai._model_info import get_info
  2826. gpt5_info = get_info("gpt-5")
  2827. assert gpt5_info["vision"] is True
  2828. assert gpt5_info["function_calling"] is True
  2829. assert gpt5_info["json_output"] is True
  2830. assert gpt5_info["family"] == ModelFamily.GPT_5
  2831. assert gpt5_info["structured_output"] is True
  2832. assert gpt5_info.get("multiple_system_messages", False) is True
  2833. gpt5_mini_info = get_info("gpt-5-mini")
  2834. assert gpt5_mini_info["family"] == ModelFamily.GPT_5_MINI
  2835. gpt5_nano_info = get_info("gpt-5-nano")
  2836. assert gpt5_nano_info["family"] == ModelFamily.GPT_5_NANO
  2837. def test_gpt5_client_creation() -> None:
  2838. """Test that GPT-5 client can be created with new parameters."""
  2839. client = OpenAIChatCompletionClient(
  2840. model="gpt-5",
  2841. api_key="test-key",
  2842. )
  2843. assert client.model_info["family"] == ModelFamily.GPT_5
  2844. @pytest.mark.asyncio
  2845. async def test_gpt5_reasoning_effort_parameter() -> None:
  2846. """Test that reasoning_effort parameter is properly handled."""
  2847. # Mock the OpenAI client to avoid actual API calls
  2848. import unittest.mock
  2849. with unittest.mock.patch(
  2850. "autogen_ext.models.openai._openai_client._openai_client_from_config"
  2851. ) as mock_client_factory:
  2852. mock_client = unittest.mock.AsyncMock()
  2853. mock_client_factory.return_value = mock_client
  2854. # Mock the completion response
  2855. mock_response = unittest.mock.MagicMock()
  2856. mock_response.choices = [unittest.mock.MagicMock()]
  2857. mock_response.choices[0].message.content = "Test response"
  2858. mock_response.choices[0].message.tool_calls = None
  2859. mock_response.choices[0].message.function_call = None
  2860. mock_response.choices[0].message.model_extra = None # Add this to fix the validation error
  2861. mock_response.choices[0].finish_reason = "stop"
  2862. mock_response.choices[0].logprobs = None # Add this to avoid potential issues
  2863. mock_response.usage.prompt_tokens = 10
  2864. mock_response.usage.completion_tokens = 5
  2865. mock_response.model = "gpt-5-2025-08-07"
  2866. mock_client.chat.completions.create.return_value = mock_response
  2867. client = OpenAIChatCompletionClient(
  2868. model="gpt-5",
  2869. api_key="test-key",
  2870. )
  2871. messages = [UserMessage(content="Test message", source="user")]
  2872. # Test with reasoning_effort parameter
  2873. await client.create(messages, reasoning_effort="minimal", verbosity="low")
  2874. # Verify the client was called with the correct parameters
  2875. call_args = mock_client.chat.completions.create.call_args
  2876. assert "reasoning_effort" in call_args.kwargs
  2877. assert call_args.kwargs["reasoning_effort"] == "minimal"
  2878. assert "verbosity" in call_args.kwargs
  2879. assert call_args.kwargs["verbosity"] == "low"
  2880. def test_gpt5_model_families() -> None:
  2881. """Test that GPT-5 model families are properly defined."""
  2882. assert ModelFamily.GPT_5 == "gpt-5"
  2883. assert ModelFamily.GPT_5_MINI == "gpt-5-mini"
  2884. assert ModelFamily.GPT_5_NANO == "gpt-5-nano"
  2885. # Check that they're included in the ANY type
  2886. any_args = get_args(ModelFamily.ANY)
  2887. assert "gpt-5" in any_args
  2888. assert "gpt-5-mini" in any_args
  2889. assert "gpt-5-nano" in any_args
  2890. # TODO: add integration tests for Azure OpenAI using AAD token.