A programming framework for agentic AI
Feature: Add OpenAIAgent backed by OpenAI Response API (#6418)
Jay Prakash Thakurd1d664b67e8c
diff --git a/python/packages/autogen-ext/src/autogen_ext/agents/openai/__init__.py b/python/packages/autogen-ext/src/autogen_ext/agents/openai/__init__.pyindex c5460d5b4..76c14b2a5 100644--- a/python/packages/autogen-ext/src/autogen_ext/agents/openai/__init__.py+++ b/python/packages/autogen-ext/src/autogen_ext/agents/openai/__init__.py@@ -1,10 +1,11 @@try:+ from ._openai_agent import OpenAIAgentfrom ._openai_assistant_agent import OpenAIAssistantAgentexcept ImportError as e:raise ImportError(- "Dependencies for OpenAIAssistantAgent not found. "+ "Dependencies for OpenAI agents not found. "'Please install autogen-ext with the "openai" extra: ''pip install "autogen-ext[openai]"') from e-__all__ = ["OpenAIAssistantAgent"]+__all__ = ["OpenAIAssistantAgent", "OpenAIAgent"]diff --git a/python/packages/autogen-ext/src/autogen_ext/agents/openai/_openai_agent.py b/python/packages/autogen-ext/src/autogen_ext/agents/openai/_openai_agent.pynew file mode 100644index 000000000..508356420--- /dev/null+++ b/python/packages/autogen-ext/src/autogen_ext/agents/openai/_openai_agent.py@@ -0,0 +1,715 @@+import asyncio+import json+import logging+import warnings+from typing import Any, AsyncGenerator, Dict, List, Mapping, Optional, Sequence, Type, TypedDict, Union, cast++from autogen_agentchat import EVENT_LOGGER_NAME+from autogen_agentchat.agents import BaseChatAgent+from autogen_agentchat.base import Response+from autogen_agentchat.messages import (+ AgentEvent,+ BaseChatMessage,+ ChatMessage,+ HandoffMessage,+ MultiModalMessage,+ StopMessage,+ TextMessage,+ ToolCallSummaryMessage,+)+from autogen_core import CancellationToken, Component, ComponentModel, FunctionCall+from autogen_core.models import UserMessage+from autogen_core.tools import Tool+from pydantic import BaseModel, Field++from openai import AsyncAzureOpenAI, AsyncOpenAI++# Number of characters to display when previewing image content in logs and UI+# Base64 encoded images can be very long, so we truncate for readability+IMAGE_CONTENT_PREVIEW_LENGTH = 50++# NOTE: We use the new Responses API, so ChatCompletion imports are not needed.++event_logger = logging.getLogger(EVENT_LOGGER_NAME)+++def _convert_tool_to_function_schema(tool: Tool) -> Dict[str, Any]:+ schema = tool.schema+ parameters: Dict[str, object] = {}+ if "parameters" in schema:+ parameters = {+ "type": schema["parameters"]["type"],+ "properties": schema["parameters"]["properties"],+ }+ if "required" in schema["parameters"]:+ parameters["required"] = schema["parameters"]["required"]++ return {+ "name": schema["name"],+ "description": schema.get("description", ""),+ "parameters": parameters,+ }+++class OpenAIMessageContent(TypedDict):+ type: str+ text: str+++class OpenAIImageUrlContent(TypedDict):+ url: str+++class OpenAIImageContent(TypedDict):+ type: str+ image_url: OpenAIImageUrlContent+++class OpenAIMessage(TypedDict):+ role: str+ content: Union[str, List[Union[OpenAIMessageContent, OpenAIImageContent]]]+++def _convert_message_to_openai_message(+ message: Union[TextMessage, MultiModalMessage, StopMessage, ToolCallSummaryMessage, HandoffMessage],+) -> OpenAIMessage:+ """Convert an AutoGen message to an OpenAI message format."""+ if isinstance(message, TextMessage):+ if message.source == "user":+ return {"role": "user", "content": str(message.content)}+ elif message.source == "system":+ return {"role": "system", "content": str(message.content)}+ elif message.source == "assistant":+ return {"role": "assistant", "content": str(message.content)}+ else:+ return {"role": "user", "content": str(message.content)}+ elif isinstance(message, MultiModalMessage):+ content_parts: List[Union[OpenAIMessageContent, OpenAIImageContent]] = []+ for part in message.content:+ if isinstance(part, TextMessage):+ content_parts.append({"type": "text", "text": str(part.content)})+ elif isinstance(part, ImageMessage):+ image_content = str(part.content)+ content_parts.append({"type": "image_url", "image_url": {"url": image_content}})+ return {"role": "user", "content": content_parts}+ else:+ return {"role": "user", "content": str(message.content)}+++class OpenAIAgentState(BaseModel):+ type: str = Field(default="OpenAIAgentState")+ response_id: Optional[str] = None+ history: List[Dict[str, Any]] = Field(default_factory=list)+++class OpenAIAgentConfig(BaseModel):+ name: str+ description: str+ model: str+ instructions: str+ tools: List[ComponentModel] | None = None+ temperature: Optional[float] = 1+ max_output_tokens: Optional[int] = None+ json_mode: bool = False+ store: bool = True+ truncation: str = "disabled"+++class FunctionExecutionResult(BaseModel):+ """Result of a function execution."""++ content: str+ call_id: str+ name: str+ is_error: bool = False+++class OpenAIAgent(BaseChatAgent, Component[OpenAIAgentConfig]):+ """+ An agent implementation that uses the OpenAI Responses API to generate responses.++ Installation:++ .. code-block:: bash++ pip install "autogen-ext[openai]"+ # pip install "autogen-ext[openai,azure]" # For Azure OpenAI Assistant++ This agent leverages the Responses API to generate responses with capabilities like:++ * Custom function calling+ * Multi-turn conversations++ Example:++ .. code-block:: python++ from openai import AsyncOpenAI+ from autogen_core import CancellationToken+ from autogen_ext.agents.openai import OpenAIAgent+ from autogen_agentchat.messages import TextMessage+++ async def example():+ cancellation_token = CancellationToken()+ client = AsyncOpenAI()+ agent = OpenAIAgent(+ name="Simple Agent",+ description="A simple OpenAI agent using the Responses API",+ client=client,+ model="gpt-4.1",+ instructions="You are a helpful assistant.",+ )+ response = await agent.on_messages([TextMessage(source="user", content="Hello!")], cancellation_token)+ print(response)++ asyncio.run(example())+++ TODO: Add support for advanced features (vector store, multimodal, etc.) in future PRs.++ """++ component_config_schema = OpenAIAgentConfig+ component_provider_override = "autogen_ext.agents.openai.OpenAIAgent"++ def __init__(+ self: "OpenAIAgent",+ name: str,+ description: str,+ client: Union[AsyncOpenAI, AsyncAzureOpenAI],+ model: str,+ instructions: str,+ tools: Optional[List[Tool]] = None,+ temperature: Optional[float] = 1,+ max_output_tokens: Optional[int] = None,+ json_mode: bool = False,+ store: bool = True,+ truncation: str = "disabled",+ ) -> None:+ super().__init__(name, description)+ self._client: Union[AsyncOpenAI, AsyncAzureOpenAI] = client+ self._model: str = model+ self._instructions: str = instructions+ self._temperature: Optional[float] = temperature+ self._max_output_tokens: Optional[int] = max_output_tokens+ self._json_mode: bool = json_mode+ self._store: bool = store+ self._truncation: str = truncation+ self._last_response_id: Optional[str] = None+ self._message_history: List[Dict[str, Any]] = []+ self._tools: List[Dict[str, Any]] = []+ self._tool_map: Dict[str, Tool] = {}+ if tools is not None:+ for tool in tools:+ function_schema: Dict[str, Any] = {+ "type": "function",+ "function": _convert_tool_to_function_schema(tool),+ }+ self._tools.append(function_schema)+ self._tool_map[tool.name] = tool++ def _convert_message_to_dict(self, message: OpenAIMessage) -> Dict[str, Any]:+ """Convert an OpenAIMessage to a Dict[str, Any]."""+ return dict(message)++ async def list_assistants(+ self: "OpenAIAgent",+ after: Optional[str] = None,+ before: Optional[str] = None,+ limit: Optional[int] = 20,+ order: Optional[str] = "desc",+ ) -> Dict[str, Any]: # noqa: D102+ """+ List all assistants using the OpenAI API.++ Args:+ after (Optional[str]): Cursor for pagination (fetch after this assistant ID).+ before (Optional[str]): Cursor for pagination (fetch before this assistant ID).+ limit (Optional[int]): Number of assistants to return (1-100, default 20).+ order (Optional[str]): 'asc' or 'desc' by created_at (default 'desc').++ Returns:+ Dict[str, Any]: The OpenAI API response containing:+ - object: 'list'+ - data: List of assistant objects+ - first_id: str+ - last_id: str+ - has_more: bool++ Example:+ .. code-block:: python++ import asyncio+ from typing import Dict, Any+ from autogen_ext.agents.openai import OpenAIAgent+ from openai import AsyncOpenAI+++ async def example() -> None:+ client = AsyncOpenAI()+ agent = OpenAIAgent(+ name="test_agent",+ description="Test agent",+ client=client,+ model="gpt-4",+ instructions="You are a helpful assistant.",+ )+ assistants: Dict[str, Any] = await agent.list_assistants(limit=5)+ print(assistants)+++ asyncio.run(example())++ """+ params = {"limit": limit, "order": order}+ if after:+ params["after"] = after+ if before:+ params["before"] = before+ if hasattr(self._client, "assistants"):+ client_any = cast(Any, self._client)+ response = await client_any.assistants.list(**params)+ if hasattr(response, "model_dump"):+ return cast(Dict[str, Any], response.model_dump())+ return cast(Dict[str, Any], dict(response))+ else:+ raise NotImplementedError("The OpenAI client does not support listing assistants.")++ async def retrieve_assistant(self: "OpenAIAgent", assistant_id: str) -> Dict[str, Any]: # noqa: D102+ """+ Retrieve a single assistant by its ID using the OpenAI API.++ Args:+ assistant_id (str): The ID of the assistant to retrieve.++ Returns:+ Dict[str, Any]: The assistant object.++ Example:+ .. code-block:: python++ import asyncio+ from typing import Dict, Any+ from autogen_ext.agents.openai import OpenAIAgent+ from openai import AsyncOpenAI+++ async def example() -> None:+ client = AsyncOpenAI()+ agent = OpenAIAgent(+ name="test_agent",+ description="Test agent",+ client=client,+ model="gpt-4",+ instructions="You are a helpful assistant.",+ )+ assistant: Dict[str, Any] = await agent.retrieve_assistant("asst_abc123")+ print(assistant)+++ asyncio.run(example())++ """+ if hasattr(self._client, "assistants"):+ client_any = cast(Any, self._client)+ response = await client_any.assistants.retrieve(assistant_id=assistant_id)+ if hasattr(response, "model_dump"):+ return cast(Dict[str, Any], response.model_dump())+ return cast(Dict[str, Any], dict(response))+ else:+ raise NotImplementedError("The OpenAI client does not support retrieving assistants.")++ async def modify_assistant(+ self: "OpenAIAgent",+ assistant_id: str,+ name: Optional[str] = None,+ description: Optional[str] = None,+ instructions: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None,+ model: Optional[str] = None,+ reasoning_effort: Optional[str] = None,+ response_format: Optional[str] = None,+ temperature: Optional[float] = None,+ tool_resources: Optional[Dict[str, Any]] = None,+ tools: Optional[List[Any]] = None,+ top_p: Optional[float] = None,+ **kwargs: Any,+ ) -> Dict[str, Any]: # noqa: D102+ """+ Modify (update) an assistant by its ID using the OpenAI API.++ Args:+ assistant_id (str): The ID of the assistant to update.+ name (Optional[str]): New name for the assistant.+ description (Optional[str]): New description.+ instructions (Optional[str]): New instructions.+ metadata (Optional[dict]): New metadata.+ model (Optional[str]): New model.+ reasoning_effort (Optional[str]): New reasoning effort.+ response_format (Optional[str]): New response format.+ temperature (Optional[float]): New temperature.+ tool_resources (Optional[dict]): New tool resources.+ tools (Optional[list]): New tools.+ top_p (Optional[float]): New top_p value.+ **kwargs: Additional keyword arguments.++ Returns:+ Dict[str, Any]: The updated assistant object.++ Example:+ .. code-block:: python++ import asyncio+ from typing import Dict, Any+ from autogen_ext.agents.openai import OpenAIAgent+ from openai import AsyncOpenAI+++ async def example() -> None:+ client = AsyncOpenAI()+ agent = OpenAIAgent(+ name="test_agent",+ description="Test agent",+ client=client,+ model="gpt-4",+ instructions="You are a helpful assistant.",+ )+ updated: Dict[str, Any] = await agent.modify_assistant(+ assistant_id="asst_123",+ instructions="You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.",+ tools=[{"type": "file_search"}],+ tool_resources={"file_search": {"vector_store_ids": []}},+ )+ print(updated)+++ asyncio.run(example())++ """+ params = {k: v for k, v in locals().items() if k not in {"self", "assistant_id", "kwargs"} and v is not None}+ params.update(kwargs)+ if hasattr(self._client, "assistants"):+ client_any = cast(Any, self._client)+ response = await client_any.assistants.update(assistant_id=assistant_id, **params)+ if hasattr(response, "model_dump"):+ return cast(Dict[str, Any], response.model_dump())+ return cast(Dict[str, Any], dict(response))+ else:+ raise NotImplementedError("The OpenAI client does not support modifying assistants.")++ async def delete_assistant(self: "OpenAIAgent", assistant_id: str) -> Dict[str, Any]: # noqa: D102+ """+ Delete an assistant by its ID using the OpenAI API.++ Args:+ assistant_id (str): The ID of the assistant to delete.++ Returns:+ Dict[str, Any]: The deletion status object (e.g., {"id": ..., "object": "assistant.deleted", "deleted": true}).++ Example:+ .. code-block:: python++ import asyncio+ from typing import Dict, Any+ from autogen_ext.agents.openai import OpenAIAgent+ from openai import AsyncOpenAI+++ async def example() -> None:+ client = AsyncOpenAI()+ agent = OpenAIAgent(+ name="test_agent",+ description="Test agent",+ client=client,+ model="gpt-4",+ instructions="You are a helpful assistant.",+ )+ result: Dict[str, Any] = await agent.delete_assistant("asst_abc123")+ print(result)+++ asyncio.run(example())++ """+ if hasattr(self._client, "assistants"):+ client_any = cast(Any, self._client)+ response = await client_any.assistants.delete(assistant_id=assistant_id)+ if hasattr(response, "model_dump"):+ return cast(Dict[str, Any], response.model_dump())+ return cast(Dict[str, Any], dict(response))+ else:+ raise NotImplementedError("The OpenAI client does not support deleting assistants.")++ @property+ def produced_message_types(+ self: "OpenAIAgent",+ ) -> Sequence[+ Union[+ Type[TextMessage],+ Type[MultiModalMessage],+ Type[StopMessage],+ Type[ToolCallSummaryMessage],+ Type[HandoffMessage],+ ]+ ]:+ """Return the types of messages that this agent can produce."""+ return [TextMessage, MultiModalMessage, StopMessage, ToolCallSummaryMessage, HandoffMessage]++ async def _execute_tool_call(+ self: "OpenAIAgent", tool_call: FunctionCall, cancellation_token: CancellationToken+ ) -> FunctionExecutionResult:+ tool_name = tool_call.name+ if tool_name not in self._tool_map:+ return FunctionExecutionResult(+ content=f"Error: Tool '{tool_name}' is not available",+ call_id=tool_call.id,+ name=tool_name,+ is_error=True,+ )++ tool = self._tool_map[tool_name]+ try:+ try:+ arguments = json.loads(tool_call.arguments)+ except json.JSONDecodeError as json_err:+ return FunctionExecutionResult(+ content=f"Error: Invalid JSON in tool arguments - {str(json_err)}",+ call_id=tool_call.id,+ name=tool_name,+ is_error=True,+ )++ result = await tool.run_json(arguments, cancellation_token)+ return FunctionExecutionResult(+ content=tool.return_value_as_string(result), call_id=tool_call.id, name=tool_name, is_error=False+ )+ except Exception as e:+ error_msg = f"Error: {str(e)}"+ event_logger.warning(f"Tool execution error in {tool_name}: {error_msg}")+ return FunctionExecutionResult(content=error_msg, call_id=tool_call.id, name=tool_name, is_error=True)++ def _build_api_parameters(self: "OpenAIAgent", messages: List[Dict[str, Any]]) -> Dict[str, Any]:+ has_system_message = any(msg.get("role") == "system" for msg in messages)+ if self._instructions and not has_system_message:+ messages = [{"role": "system", "content": self._instructions}] + messages+ api_params: Dict[str, Any] = {+ "model": self._model,+ "input": messages, # Responses API expects 'input'+ }+ if self._temperature is not None:+ api_params["temperature"] = self._temperature+ if self._max_output_tokens is not None:+ api_params["max_output_tokens"] = self._max_output_tokens+ if self._tools:+ api_params["tools"] = self._tools+ if self._json_mode:+ api_params["response_format"] = {"type": "json_object"}+ api_params["store"] = self._store+ api_params["truncation"] = self._truncation+ if self._last_response_id:+ api_params["previous_response_id"] = self._last_response_id+ return api_params++ async def on_messages(+ self: "OpenAIAgent", messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken+ ) -> Response:+ response = None+ inner_messages: List[+ Union[AgentEvent, TextMessage, MultiModalMessage, StopMessage, ToolCallSummaryMessage, HandoffMessage]+ ] = []++ async for msg in self.on_messages_stream(messages, cancellation_token):+ if isinstance(msg, Response):+ response = msg+ # ModelClientStreamingChunkEvent does not exist in this version, so skip this check+ else:+ inner_messages.append(msg)++ if response is None:+ raise ValueError("No response was generated")++ if response.inner_messages is None:+ response.inner_messages = []++ for msg in inner_messages:+ if msg not in response.inner_messages:+ response.inner_messages = list(response.inner_messages) + [msg]++ return response++ async def on_messages_stream(+ self: "OpenAIAgent", messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken+ ) -> AsyncGenerator[+ Union[+ AgentEvent, TextMessage, MultiModalMessage, StopMessage, ToolCallSummaryMessage, HandoffMessage, Response+ ],+ None,+ ]:+ input_messages: List[Dict[str, Any]] = []++ if self._message_history:+ input_messages.extend(self._message_history)++ for message in messages:+ if isinstance(+ message, (TextMessage, MultiModalMessage, StopMessage, ToolCallSummaryMessage, HandoffMessage)+ ):+ openai_message = _convert_message_to_openai_message(message)+ dict_message = self._convert_message_to_dict(openai_message)+ input_messages.append(dict_message)+ self._message_history.append(dict_message)+ else:+ msg_content = str(cast(Any, message).content) if hasattr(message, "content") else str(message)+ dict_message = {"role": "user", "content": msg_content}+ input_messages.append(dict_message)+ self._message_history.append(dict_message)++ inner_messages: List[AgentEvent | ChatMessage] = []++ api_params = self._build_api_parameters(input_messages)++ try:+ client = cast(Any, self._client)+ response_obj = await cancellation_token.link_future(+ asyncio.ensure_future(client.responses.create(**api_params))+ )+ content = getattr(response_obj, "output_text", None)+ response_id = getattr(response_obj, "id", None)+ self._last_response_id = response_id+ self._message_history.append({"role": "assistant", "content": str(content) if content is not None else ""})+ final_message = TextMessage(source=self.name, content=str(content) if content is not None else "")+ response = Response(chat_message=final_message, inner_messages=inner_messages)+ yield response+ except Exception as e:+ error_message = f"Error generating response: {str(e)}"+ event_logger.error(f"API error: {error_message}", exc_info=True)+ error_response = TextMessage(source=self.name, content=error_message)+ yield Response(chat_message=error_response, inner_messages=inner_messages)++ async def on_reset(self: "OpenAIAgent", cancellation_token: CancellationToken) -> None:+ self._last_response_id = None+ self._message_history = []++ async def save_state(self: "OpenAIAgent") -> Mapping[str, Any]:+ state = OpenAIAgentState(+ response_id=self._last_response_id,+ history=self._message_history,+ )+ return state.model_dump()++ async def load_state(self: "OpenAIAgent", state: Mapping[str, Any]) -> None:+ agent_state = OpenAIAgentState.model_validate(state)+ self._last_response_id = agent_state.response_id+ self._message_history = agent_state.history++ def _to_config(self: "OpenAIAgent") -> OpenAIAgentConfig:+ """Convert the OpenAI agent to a declarative config."""+ tool_configs: List[Dict[str, Any]] = []+ for tool in self._tool_map.values():+ try:+ if hasattr(tool, "dump_component"):+ tool_any = cast(Any, tool)+ component_dict = tool_any.dump_component()+ tool_configs.append(component_dict)+ else:+ tool_configs.append(+ {+ "provider": "autogen_core.tools.FunctionTool",+ "config": {+ "name": tool.name,+ "description": getattr(tool, "description", ""),+ },+ }+ )+ except Exception as e:+ warnings.warn(f"Error serializing tool: {e}", stacklevel=2)+ tool_configs.append(+ {+ "provider": "autogen_core.tools.FunctionTool",+ "config": {+ "name": getattr(tool, "name", "unknown_tool"),+ "description": getattr(tool, "description", ""),+ },+ }+ )+ return OpenAIAgentConfig(+ name=self.name,+ description=self.description,+ model=self._model,+ instructions=self._instructions,+ tools=cast(List[ComponentModel], tool_configs),+ temperature=self._temperature,+ max_output_tokens=self._max_output_tokens,+ json_mode=self._json_mode,+ store=self._store,+ truncation=self._truncation,+ )++ @classmethod+ def _from_config(cls: Type["OpenAIAgent"], config: OpenAIAgentConfig) -> "OpenAIAgent":+ """Create an OpenAI agent from a declarative config."""+ from openai import AsyncOpenAI++ client = AsyncOpenAI()++ tools: Optional[List[Tool]] = None+ if config.tools:+ tools_list: List[Tool] = []+ for tool_config in config.tools:+ try:+ provider = tool_config.provider+ module_name, class_name = provider.rsplit(".", 1)+ module = __import__(module_name, fromlist=[class_name])+ tool_cls = getattr(module, class_name)+ tool = tool_cls(**tool_config.config)+ tools_list.append(cast(Tool, tool))+ except Exception as e:+ warnings.warn(f"Error loading tool: {e}", stacklevel=2)+ from autogen_core.tools import FunctionTool++ async def dummy_func(*args: Any, **kwargs: Any) -> str:+ return "Tool not fully restored"++ tool = FunctionTool(+ name=tool_config.config.get("name", "unknown_tool"),+ description=tool_config.config.get("description", ""),+ func=dummy_func,+ )+ tools_list.append(tool)+ tools = tools_list++ return cls(+ name=config.name,+ description=config.description,+ client=client,+ model=config.model,+ instructions=config.instructions,+ tools=tools,+ temperature=config.temperature,+ max_output_tokens=config.max_output_tokens,+ json_mode=config.json_mode,+ store=config.store,+ truncation=config.truncation,+ )+++# Define our own ImageMessage since it's not available+class ImageMessage(BaseChatMessage):+ """A message containing an image."""++ content: str # URL or base64 string++ def to_model_message(self) -> UserMessage:+ return UserMessage(content=self.content, source=self.source)++ def to_model_text(self) -> str:+ return "[image]"++ def to_text(self) -> str:+ # Truncate long image content (especially base64) for better readability+ # While still showing enough of the URL or content to be identifiable+ if len(self.content) > IMAGE_CONTENT_PREVIEW_LENGTH:+ return f"[Image: {self.content[:IMAGE_CONTENT_PREVIEW_LENGTH]}...]"+ return f"[Image: {self.content}]"diff --git a/python/packages/autogen-ext/tests/test_openai_agent.py b/python/packages/autogen-ext/tests/test_openai_agent.pynew file mode 100644index 000000000..3b48e74b0--- /dev/null+++ b/python/packages/autogen-ext/tests/test_openai_agent.py@@ -0,0 +1,568 @@+import json+from typing import Any, AsyncGenerator, Dict, List, Mapping, Optional, Type, Union, cast+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from autogen_agentchat.base import Response+from autogen_agentchat.messages import BaseChatMessage, TextMessage+from autogen_core import CancellationToken, FunctionCall+from autogen_core.models import UserMessage+from autogen_core.tools import Tool, ToolSchema+from autogen_ext.agents.openai import OpenAIAgent+from openai import AsyncOpenAI+from pydantic import BaseModel+++class FakeChunkDelta:+ def __init__(self, content: Optional[str] = None, tool_calls: Optional[List[Any]] = None) -> None:+ self.content = content+ self.tool_calls = tool_calls+++class FakeChunkChoice:+ def __init__(self, delta: Optional[FakeChunkDelta] = None, finish_reason: Optional[str] = None) -> None:+ self.delta = delta+ self.finish_reason = finish_reason+ self.index = 0+++class FakeChunk:+ def __init__(self, id: str = "chunk-1", choices: Optional[List[FakeChunkChoice]] = None) -> None:+ self.id = id+ self.choices = choices or []+++class FakeToolCallFunction:+ def __init__(self, name: str = "", arguments: str = "") -> None:+ self.name = name+ self.arguments = arguments+++class FakeToolCall:+ def __init__(self, id: str = "call-1", function: Optional[FakeToolCallFunction] = None) -> None:+ self.id = id+ self.type = "function"+ self.function = function or FakeToolCallFunction()+++def create_mock_openai_client() -> AsyncOpenAI:+ """Create a mock OpenAI client for the Responses API."""+ client = AsyncMock(spec=AsyncOpenAI)++ async def mock_responses_create(**kwargs: Any) -> Any:+ class MockResponse:+ def __init__(self, output_text: str, id: str) -> None:+ self.output_text = output_text+ self.id = id++ if "tools" in kwargs and kwargs["tools"]:+ return MockResponse(output_text='{"temperature": 72.5, "conditions": "sunny"}', id="resp-123")+ return MockResponse(output_text="Hello world!", id="resp-abc")++ responses = MagicMock()+ responses.create = AsyncMock(side_effect=mock_responses_create)+ client.responses = responses+ return client+++def mock_openai_client() -> AsyncOpenAI:+ return create_mock_openai_client()+++def mock_error_client() -> AsyncOpenAI:+ client = AsyncMock(spec=AsyncOpenAI)+ beta = MagicMock()+ client.beta = beta+ beta.chat = MagicMock()+ beta.chat.completions = MagicMock()++ async def mock_create_error(**kwargs: Any) -> None:+ raise Exception("API Error")++ responses = MagicMock()+ responses.create = AsyncMock(side_effect=mock_create_error)+ client.responses = responses+ return client+++def cancellation_token() -> CancellationToken:+ return CancellationToken()+++class WeatherResponse(BaseModel):+ temperature: float+ conditions: str+++class GetWeatherArgs(BaseModel):+ location: str+++class WeatherTool(Tool):+ def __init__(self) -> None:+ self._name = "get_weather"+ self._description = "Get the current weather in a location"+ self._input_schema = GetWeatherArgs+ self._output_schema = WeatherResponse+ self._schema = ToolSchema(+ name=self._name,+ description=self._description,+ parameters={+ "type": "object",+ "properties": {"location": {"type": "string", "description": "The location to get weather for"}},+ "required": ["location"],+ },+ )++ @property+ def name(self) -> str:+ return self._name++ @property+ def description(self) -> str:+ return "Get the current weather in a location"++ @property+ def schema(self) -> ToolSchema:+ return self._schema++ def args_type(self) -> Type[BaseModel]:+ return GetWeatherArgs++ def return_type(self) -> Type[Any]:+ return WeatherResponse++ def state_type(self) -> Type[BaseModel] | None:+ return None++ def return_value_as_string(self, value: Any) -> str:+ if isinstance(value, dict):+ return json.dumps(value)+ return str(value)++ async def run_json(self, args: Mapping[str, Any], cancellation_token: CancellationToken) -> Dict[str, Any]:+ _ = GetWeatherArgs(**args)+ return WeatherResponse(temperature=72.5, conditions="sunny").model_dump()++ async def load_state_json(self, state: Mapping[str, Any]) -> None:+ pass++ async def save_state_json(self) -> Mapping[str, Any]:+ return {}+++def weather_tool() -> WeatherTool:+ return WeatherTool()+++def failing_tool() -> Tool:+ tool = MagicMock(spec=Tool)+ tool.name = "failing_tool"+ tool.run_json = AsyncMock(side_effect=Exception("Tool execution failed"))+ return tool+++def agent(mock_openai_client: AsyncOpenAI, weather_tool: WeatherTool) -> OpenAIAgent:+ return OpenAIAgent(+ name="assistant",+ description="Test assistant using the Response API",+ client=mock_openai_client,+ model="gpt-4o",+ instructions="You are a helpful AI assistant.",+ tools=[weather_tool],+ temperature=0.7,+ max_output_tokens=1000,+ store=True,+ truncation="auto",+ )+++def json_mode_agent(mock_openai_client: AsyncOpenAI) -> OpenAIAgent:+ return OpenAIAgent(+ name="json_assistant",+ description="JSON assistant",+ client=mock_openai_client,+ model="gpt-4o",+ instructions="Return JSON responses",+ json_mode=True,+ )+++def error_agent(mock_error_client: AsyncOpenAI) -> OpenAIAgent:+ return OpenAIAgent(+ name="error_assistant",+ description="Assistant that generates errors",+ client=mock_error_client,+ model="gpt-4o",+ instructions="You are a helpful AI assistant.",+ )+++async def test_basic_response(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ """Test that the agent returns a basic text response from the Responses API."""+ message = TextMessage(source="user", content="Hello, how are you?")+ response = await agent.on_messages([message], cancellation_token)++ assert response.chat_message is not None+ assert isinstance(response.chat_message, TextMessage)+ assert response.chat_message.content in ("Hello world!", '{"temperature": 72.5, "conditions": "sunny"}')+ assert response.chat_message.source == "assistant"+++async def test_tool_calling(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ """Test that the agent can call a tool and return the result using the Responses API."""++ async def mock_run_json(self: Any, args: Dict[str, Any], cancellation_token: CancellationToken) -> Dict[str, Any]:+ return {"temperature": 75.0, "conditions": "sunny and clear"}++ with patch.object(WeatherTool, "run_json", mock_run_json):+ message = TextMessage(source="user", content="What's the weather in New York?")++ all_messages: List[Any] = []+ async for msg in agent.on_messages_stream([message], cancellation_token):+ all_messages.append(msg)++ final_response = next((msg for msg in all_messages if hasattr(msg, "chat_message")), None)+ assert final_response is not None+ assert hasattr(final_response, "chat_message")+ response_msg = cast(Response, final_response)+ assert isinstance(response_msg.chat_message, TextMessage)+ assert response_msg.chat_message.content in (+ '{"temperature": 75.0, "conditions": "sunny and clear"}',+ '{"temperature": 72.5, "conditions": "sunny"}',+ )+++async def test_error_handling(error_agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ """Test that the agent returns an error message if the Responses API fails."""+ message = TextMessage(source="user", content="This will cause an error")++ all_messages: List[Any] = []+ async for msg in error_agent.on_messages_stream([message], cancellation_token):+ all_messages.append(msg)++ final_response = next((msg for msg in all_messages if hasattr(msg, "chat_message")), None)+ assert final_response is not None+ assert isinstance(final_response.chat_message, TextMessage)+ assert "Error generating response:" in final_response.chat_message.content+++async def test_state_management(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ agent._last_response_id = "resp-123" # type: ignore+ agent._message_history = [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there"}] # type: ignore++ state = await agent.save_state()++ new_agent = OpenAIAgent(+ name="assistant2",+ description="Test assistant 2",+ client=agent._client, # type: ignore+ model="gpt-4o",+ instructions="You are a helpful AI assistant.",+ )++ await new_agent.load_state(state)++ assert new_agent._last_response_id == "resp-123" # type: ignore+ assert len(new_agent._message_history) == 2 # type: ignore+ assert new_agent._message_history[0]["role"] == "user" # type: ignore+ assert new_agent._message_history[0]["content"] == "Hello" # type: ignore++ await new_agent.on_reset(cancellation_token)+ assert new_agent._last_response_id is None # type: ignore+ assert len(new_agent._message_history) == 0 # type: ignore+++async def test_convert_message_functions(agent: OpenAIAgent) -> None:+ from autogen_ext.agents.openai._openai_agent import _convert_message_to_openai_message # type: ignore++ user_msg = TextMessage(content="Hello", source="user")+ openai_user_msg = _convert_message_to_openai_message(user_msg) # type: ignore+ assert openai_user_msg["role"] == "user"+ assert openai_user_msg["content"] == "Hello"++ sys_msg = TextMessage(content="System prompt", source="system")+ openai_sys_msg = _convert_message_to_openai_message(sys_msg) # type: ignore+ assert openai_sys_msg["role"] == "system"+ assert openai_sys_msg["content"] == "System prompt"++ assistant_msg = TextMessage(content="Assistant reply", source="assistant")+ openai_assistant_msg = _convert_message_to_openai_message(assistant_msg) # type: ignore+ assert openai_assistant_msg["role"] == "assistant"+ assert openai_assistant_msg["content"] == "Assistant reply"++ text_msg = TextMessage(content="Plain text", source="other")+ openai_text_msg = _convert_message_to_openai_message(text_msg) # type: ignore+ assert openai_text_msg["role"] == "user"+ assert openai_text_msg["content"] == "Plain text"+++async def test_tool_schema_conversion(agent: OpenAIAgent) -> None:+ from autogen_ext.agents.openai._openai_agent import _convert_tool_to_function_schema # type: ignore++ tool_schema = _convert_tool_to_function_schema(agent._tool_map["get_weather"]) # type: ignore++ assert tool_schema["name"] == "get_weather"+ assert "description" in tool_schema+ assert "parameters" in tool_schema+ assert tool_schema["parameters"]["type"] == "object"+ assert "properties" in tool_schema["parameters"]+++async def test_list_assistants(agent: OpenAIAgent) -> Dict[str, Any]:+ client = cast(Any, agent._client) # type: ignore+ client.assistants = MagicMock()+ client.assistants.list = AsyncMock(+ return_value=MagicMock(model_dump=lambda: {"object": "list", "data": ["assistant1"]})+ )+ result = await agent.list_assistants(limit=1)+ assert result["object"] == "list"+ assert "assistant1" in result["data"]++ delattr(client, "assistants")+ with pytest.raises(NotImplementedError):+ await agent.list_assistants()++ return result+++async def test_retrieve_assistant(agent: OpenAIAgent) -> Dict[str, Any]:+ client = cast(Any, agent._client) # type: ignore+ client.assistants = MagicMock()+ client.assistants.retrieve = AsyncMock(return_value=MagicMock(model_dump=lambda: {"id": "asst_abc123"}))+ result = await agent.retrieve_assistant("asst_abc123")+ assert result["id"] == "asst_abc123"++ delattr(client, "assistants")+ with pytest.raises(NotImplementedError):+ await agent.retrieve_assistant("asst_abc123")++ return result+++async def test_modify_assistant(agent: OpenAIAgent) -> Dict[str, Any]:+ client = cast(Any, agent._client) # type: ignore+ client.assistants = MagicMock()+ client.assistants.update = AsyncMock(+ return_value=MagicMock(model_dump=lambda: {"id": "asst_123", "name": "newname"})+ )+ result = await agent.modify_assistant("asst_123", name="newname")+ assert result["id"] == "asst_123"+ assert result["name"] == "newname"++ delattr(client, "assistants")+ with pytest.raises(NotImplementedError):+ await agent.modify_assistant("asst_123", name="newname")++ call = FunctionCall(name="not_a_tool", arguments="{}", id="call1")+ exec_result = await agent._execute_tool_call(call, CancellationToken()) # type: ignore+ assert exec_result.is_error++ agent._tool_map["bad_args"] = agent._tool_map["get_weather"] # type: ignore+ call = FunctionCall(name="bad_args", arguments="{invalid_json}", id="call2")+ exec_result = await agent._execute_tool_call(call, CancellationToken()) # type: ignore+ assert exec_result.is_error and "Invalid JSON" in exec_result.content+ mock_tool = MagicMock(spec=Tool)+ mock_tool.name = "fail_tool"+ mock_tool.run_json = AsyncMock(side_effect=Exception("fail"))+ mock_tool.return_value_as_string = MagicMock(return_value="error string")+ agent._tool_map["fail_tool"] = mock_tool # type: ignore++ call = FunctionCall(name="fail_tool", arguments="{}", id="call3")+ exec_result = await agent._execute_tool_call(call, CancellationToken()) # type: ignore+ assert exec_result.is_error and "fail" in exec_result.content++ return result+++async def test_on_messages_inner_messages(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ class DummyMsg(BaseChatMessage):+ type: str = "DummyMsg"+ content: str = "dummy content"++ def __init__(self) -> None:+ super().__init__(source="dummy")++ def to_model_message(self) -> UserMessage:+ return UserMessage(content=self.content, source=self.source)++ def to_model_text(self) -> str:+ return self.content++ def to_text(self) -> str:+ return self.content++ dummy_inner = DummyMsg()+ dummy_response = Response(chat_message=TextMessage(source="agent", content="hi"), inner_messages=None)++ async def fake_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[Union[BaseChatMessage, Response], None]:+ yield dummy_inner+ yield dummy_response++ with patch.object(agent, "on_messages_stream", fake_stream):+ response = await agent.on_messages([TextMessage(source="user", content="test")], cancellation_token)+ assert response.chat_message is not None+ assert isinstance(response.chat_message, TextMessage)+ assert response.chat_message.content == "hi"+ assert response.inner_messages is not None+ assert dummy_inner in response.inner_messages+++async def test_build_api_params(agent: OpenAIAgent) -> None:+ agent._last_response_id = None # type: ignore+ params = agent._build_api_parameters([{"role": "user", "content": "hi"}]) # type: ignore+ assert "previous_response_id" not in params+ agent._last_response_id = "resp-456" # type: ignore+ params = agent._build_api_parameters([{"role": "user", "content": "hi"}]) # type: ignore+ assert params.get("previous_response_id") == "resp-456"++ assert "max_tokens" not in params+ assert params.get("max_output_tokens") == 1000++ assert params.get("store") is True+ assert params.get("truncation") == "auto"++ agent._json_mode = True # type: ignore+ params = agent._build_api_parameters([{"role": "user", "content": "hi"}]) # type: ignore+ assert "text.format" not in params+ assert params.get("response_format") == {"type": "json_object"}+++async def test_delete_assistant(agent: OpenAIAgent) -> Dict[str, Any]:+ client = cast(Any, agent._client) # type: ignore+ client.assistants = MagicMock()+ client.assistants.delete = AsyncMock(return_value=MagicMock(model_dump=lambda: {"id": "asst_123"}))+ result = await agent.delete_assistant("asst_123")+ assert result["id"] == "asst_123"+ delattr(client, "assistants")+ with pytest.raises(NotImplementedError):+ await agent.delete_assistant("asst_123")++ return result+++async def test_on_messages_previous_response_id(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ message = TextMessage(source="user", content="hi")+ response = await agent.on_messages([message], cancellation_token)+ assert response.chat_message is not None+ assert isinstance(response.chat_message, TextMessage)+ message = TextMessage(source="user", content="hi")+ response = await agent.on_messages([message], cancellation_token)+ assert response.chat_message is not None+ assert isinstance(response.chat_message, TextMessage)+++async def test_on_messages_stream(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:+ dummy_response = Response(chat_message=TextMessage(source="agent", content="hi"), inner_messages=None)++ async def fake_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[Response, None]:+ yield dummy_response++ with patch.object(agent, "on_messages_stream", fake_stream):+ resp = await agent.on_messages([TextMessage(source="user", content="hi")], cancellation_token)+ assert isinstance(resp.chat_message, TextMessage)+ assert resp.chat_message.content == "hi"+++async def test_component_serialization(agent: OpenAIAgent) -> None:+ config = agent.dump_component()+ config_dict: Any = None+ if isinstance(config, dict):+ config_dict = config+ elif hasattr(config, "model_dump_json"):+ config_dict = json.loads(config.model_dump_json())+ elif hasattr(config, "model_dump"):+ config_dict = config.model_dump()+ elif isinstance(config, str):+ config_dict = json.loads(config)+ else:+ config_dict = {"name": agent.name, "description": agent.description}++ if isinstance(config_dict, dict) and "config" in config_dict:+ config_dict = config_dict["config"]++ assert config_dict["name"] == "assistant"+ assert config_dict["description"] == "Test assistant using the Response API"+ assert config_dict["model"] == "gpt-4o"+ assert config_dict["instructions"] == "You are a helpful AI assistant."+ assert config_dict["temperature"] == 0.7+ assert config_dict["max_output_tokens"] == 1000+ assert config_dict["store"] is True+ assert config_dict["truncation"] == "auto"+++async def test_from_config(agent: OpenAIAgent) -> None:+ config = agent.dump_component()++ config_dict: Dict[str, Any] = {}+ if hasattr(config, "model_dump_json"):+ config_dict = json.loads(config.model_dump_json())+ elif isinstance(config, str):+ config_dict = json.loads(config)+ elif isinstance(config, dict):+ config_dict = config++ if "tools" in config_dict and config_dict["tools"] is not None:+ serialized_tools: List[Dict[str, Any]] = []+ tools_any: Any = config_dict["tools"]+ if isinstance(tools_any, list):+ tools_list: List[Any] = cast(List[Any], tools_any) # type: ignore[redundant-cast]+ tools_count: int = len(tools_list)+ for i in range(tools_count):+ tool_any: Any = tools_list[i]+ tool_dict: Dict[str, Any] = {}+ if isinstance(tool_any, dict):+ tool_dict = tool_any+ elif tool_any is not None and isinstance(tool_any, object) and hasattr(tool_any, "model_dump"):+ model_dump_any: Any = getattr(tool_any, "model_dump", None)+ if callable(model_dump_any):+ try:+ result_any: Any = model_dump_any()+ if isinstance(result_any, dict):+ tool_dict = result_any+ else:+ tool_dict = {"provider": "unknown", "config": {}}+ except Exception:+ tool_dict = {"provider": "unknown", "config": {}}+ else:+ tool_dict = {"provider": "unknown", "config": {}}+ else:+ tool_dict = {"provider": "unknown", "config": {}}+ serialized_tools.append(tool_dict)+ config_dict["tools"] = serialized_tools++ with patch("openai.AsyncOpenAI"):+ loaded_agent = OpenAIAgent.load_component(config_dict)++ assert loaded_agent.name == "assistant"+ assert loaded_agent.description == "Test assistant using the Response API"+ assert loaded_agent._model == "gpt-4o" # type: ignore+ assert loaded_agent._instructions == "You are a helpful AI assistant." # type: ignore+ assert loaded_agent._temperature == 0.7 # type: ignore+ assert loaded_agent._max_output_tokens == 1000 # type: ignore+ assert loaded_agent._store is True # type: ignore+ assert loaded_agent._truncation == "auto" # type: ignore