Skip to content

Commit 7865151

Browse files
authored
Remove assistant related methods from OpenAIAgent (microsoft#6866)
1 parent 8ff10a6 commit 7865151

2 files changed

Lines changed: 1 addition & 299 deletions

File tree

python/packages/autogen-ext/src/autogen_ext/agents/openai/_openai_agent.py

Lines changed: 0 additions & 215 deletions
Original file line numberDiff line numberDiff line change
@@ -746,221 +746,6 @@ def _convert_message_to_dict(self, message: OpenAIMessage) -> Dict[str, Any]:
746746
"""Convert an OpenAIMessage to a Dict[str, Any]."""
747747
return dict(message)
748748

749-
async def list_assistants(
750-
self: "OpenAIAgent",
751-
after: Optional[str] = None,
752-
before: Optional[str] = None,
753-
limit: Optional[int] = 20,
754-
order: Optional[str] = "desc",
755-
) -> Dict[str, Any]: # noqa: D102
756-
"""
757-
List all assistants using the OpenAI API.
758-
759-
Args:
760-
after (Optional[str]): Cursor for pagination (fetch after this assistant ID).
761-
before (Optional[str]): Cursor for pagination (fetch before this assistant ID).
762-
limit (Optional[int]): Number of assistants to return (1-100, default 20).
763-
order (Optional[str]): 'asc' or 'desc' by created_at (default 'desc').
764-
765-
Returns:
766-
Dict[str, Any]: The OpenAI API response containing:
767-
- object: 'list'
768-
- data: List of assistant objects
769-
- first_id: str
770-
- last_id: str
771-
- has_more: bool
772-
773-
Example:
774-
.. code-block:: python
775-
776-
import asyncio
777-
from typing import Dict, Any
778-
from autogen_ext.agents.openai import OpenAIAgent
779-
from openai import AsyncOpenAI
780-
import logging
781-
782-
783-
async def example() -> None:
784-
client = AsyncOpenAI()
785-
agent = OpenAIAgent(
786-
name="test_agent",
787-
description="Test agent",
788-
client=client,
789-
model="gpt-4",
790-
instructions="You are a helpful assistant.",
791-
)
792-
assistants: Dict[str, Any] = await agent.list_assistants(limit=5)
793-
logging.info(assistants)
794-
795-
796-
asyncio.run(example())
797-
798-
"""
799-
params = {"limit": limit, "order": order}
800-
if after:
801-
params["after"] = after
802-
if before:
803-
params["before"] = before
804-
if hasattr(self._client, "assistants"):
805-
client_any = cast(Any, self._client)
806-
response = await client_any.assistants.list(**params)
807-
if hasattr(response, "model_dump"):
808-
return cast(Dict[str, Any], response.model_dump())
809-
return cast(Dict[str, Any], dict(response))
810-
else:
811-
raise NotImplementedError("The OpenAI client does not support listing assistants.")
812-
813-
async def retrieve_assistant(self: "OpenAIAgent", assistant_id: str) -> Dict[str, Any]: # noqa: D102
814-
"""
815-
Retrieve a single assistant by its ID using the OpenAI API.
816-
817-
Args:
818-
assistant_id (str): The ID of the assistant to retrieve.
819-
820-
Returns:
821-
Dict[str, Any]: The assistant object.
822-
823-
Example:
824-
.. code-block:: python
825-
826-
import asyncio
827-
from typing import Dict, Any
828-
from autogen_ext.agents.openai import OpenAIAgent
829-
from openai import AsyncOpenAI
830-
import logging
831-
832-
833-
async def example() -> None:
834-
client = AsyncOpenAI()
835-
agent = OpenAIAgent(
836-
name="test_agent",
837-
description="Test agent",
838-
client=client,
839-
model="gpt-4",
840-
instructions="You are a helpful assistant.",
841-
)
842-
assistant: Dict[str, Any] = await agent.retrieve_assistant("asst_abc123")
843-
logging.info(assistant)
844-
845-
846-
asyncio.run(example())
847-
848-
"""
849-
if hasattr(self._client, "assistants"):
850-
client_any = cast(Any, self._client)
851-
response = await client_any.assistants.retrieve(assistant_id=assistant_id)
852-
if hasattr(response, "model_dump"):
853-
return cast(Dict[str, Any], response.model_dump())
854-
return cast(Dict[str, Any], dict(response))
855-
else:
856-
raise NotImplementedError("The OpenAI client does not support retrieving assistants.")
857-
858-
async def modify_assistant(
859-
self: "OpenAIAgent",
860-
assistant_id: str,
861-
name: Optional[str] = None,
862-
description: Optional[str] = None,
863-
instructions: Optional[str] = None,
864-
metadata: Optional[Dict[str, Any]] = None,
865-
model: Optional[str] = None,
866-
reasoning_effort: Optional[str] = None,
867-
response_format: Optional[str] = None,
868-
temperature: Optional[float] = None,
869-
tool_resources: Optional[Dict[str, Any]] = None,
870-
tools: Optional[List[Any]] = None,
871-
top_p: Optional[float] = None,
872-
**kwargs: Any,
873-
) -> Dict[str, Any]: # noqa: D102
874-
"""
875-
Modify (update) an assistant by its ID using the OpenAI API.
876-
877-
Args:
878-
assistant_id (str): The ID of the assistant to update.
879-
name (Optional[str]): New name for the assistant.
880-
description (Optional[str]): New description.
881-
instructions (Optional[str]): New instructions.
882-
metadata (Optional[dict]): New metadata.
883-
model (Optional[str]): New model.
884-
reasoning_effort (Optional[str]): New reasoning effort.
885-
response_format (Optional[str]): New response format.
886-
temperature (Optional[float]): New temperature.
887-
tool_resources (Optional[dict]): New tool resources.
888-
tools (Optional[list]): New tools.
889-
top_p (Optional[float]): New top_p value.
890-
**kwargs: Additional keyword arguments.
891-
892-
Returns:
893-
Dict[str, Any]: The updated assistant object.
894-
895-
Example:
896-
.. code-block:: python
897-
898-
import asyncio
899-
from typing import Dict, Any
900-
from autogen_ext.agents.openai import OpenAIAgent
901-
from openai import AsyncOpenAI
902-
import logging
903-
904-
905-
async def example() -> None:
906-
client = AsyncOpenAI()
907-
agent = OpenAIAgent(
908-
name="test_agent",
909-
description="Test agent",
910-
client=client,
911-
model="gpt-4",
912-
instructions="You are a helpful assistant.",
913-
)
914-
updated: Dict[str, Any] = await agent.modify_assistant(
915-
assistant_id="asst_123",
916-
instructions=(
917-
"You are an HR bot, and you have access to files to answer employee "
918-
"questions about company policies. Always response with info from either "
919-
"of the files."
920-
),
921-
tools=[{"type": "file_search"}],
922-
tool_resources={"file_search": {"vector_store_ids": []}},
923-
)
924-
logging.info(updated)
925-
926-
927-
asyncio.run(example())
928-
929-
"""
930-
params = {k: v for k, v in locals().items() if k not in {"self", "assistant_id", "kwargs"} and v is not None}
931-
params.update(kwargs)
932-
if hasattr(self._client, "assistants"):
933-
client_any = cast(Any, self._client)
934-
response = await client_any.assistants.update(assistant_id=assistant_id, **params)
935-
if hasattr(response, "model_dump"):
936-
return cast(Dict[str, Any], response.model_dump())
937-
return cast(Dict[str, Any], dict(response))
938-
else:
939-
raise NotImplementedError("The OpenAI client does not support modifying assistants.")
940-
941-
async def delete_assistant(self: "OpenAIAgent", assistant_id: str) -> Dict[str, Any]: # noqa: D102
942-
"""
943-
Delete an assistant by its ID using the OpenAI API.
944-
945-
Args:
946-
assistant_id (str): The ID of the assistant to delete.
947-
948-
Returns:
949-
Dict[str, Any]: The deletion status object.
950-
951-
Example:
952-
953-
{"id": "...", "object": "assistant.deleted", "deleted": true}
954-
"""
955-
if hasattr(self._client, "assistants"):
956-
client_any = cast(Any, self._client)
957-
response = await client_any.assistants.delete(assistant_id=assistant_id)
958-
if hasattr(response, "model_dump"):
959-
return cast(Dict[str, Any], response.model_dump())
960-
return cast(Dict[str, Any], dict(response))
961-
else:
962-
raise NotImplementedError("The OpenAI client does not support deleting assistants.")
963-
964749
@property
965750
def produced_message_types(
966751
self: "OpenAIAgent",

python/packages/autogen-ext/tests/test_openai_agent.py

Lines changed: 1 addition & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import pytest
66
from autogen_agentchat.base import Response
77
from autogen_agentchat.messages import BaseChatMessage, MultiModalMessage, TextMessage
8-
from autogen_core import CancellationToken, FunctionCall, Image
8+
from autogen_core import CancellationToken, Image
99
from autogen_core.models import UserMessage
1010
from autogen_core.tools import Tool, ToolSchema
1111
from autogen_ext.agents.openai import OpenAIAgent
@@ -325,75 +325,6 @@ async def test_tool_schema_conversion(agent: OpenAIAgent) -> None:
325325
assert "properties" in tool_schema["parameters"]
326326

327327

328-
@pytest.mark.asyncio
329-
async def test_list_assistants(agent: OpenAIAgent) -> Dict[str, Any]:
330-
client = cast(Any, agent._client) # type: ignore
331-
client.assistants = MagicMock()
332-
client.assistants.list = AsyncMock(
333-
return_value=MagicMock(model_dump=lambda: {"object": "list", "data": ["assistant1"]})
334-
)
335-
result = await agent.list_assistants(limit=1)
336-
assert result["object"] == "list"
337-
assert "assistant1" in result["data"]
338-
339-
delattr(client, "assistants")
340-
with pytest.raises(NotImplementedError):
341-
await agent.list_assistants()
342-
343-
return result
344-
345-
346-
@pytest.mark.asyncio
347-
async def test_retrieve_assistant(agent: OpenAIAgent) -> Dict[str, Any]:
348-
client = cast(Any, agent._client) # type: ignore
349-
client.assistants = MagicMock()
350-
client.assistants.retrieve = AsyncMock(return_value=MagicMock(model_dump=lambda: {"id": "asst_abc123"}))
351-
result = await agent.retrieve_assistant("asst_abc123")
352-
assert result["id"] == "asst_abc123"
353-
354-
delattr(client, "assistants")
355-
with pytest.raises(NotImplementedError):
356-
await agent.retrieve_assistant("asst_abc123")
357-
358-
return result
359-
360-
361-
@pytest.mark.asyncio
362-
async def test_modify_assistant(agent: OpenAIAgent) -> Dict[str, Any]:
363-
client = cast(Any, agent._client) # type: ignore
364-
client.assistants = MagicMock()
365-
client.assistants.update = AsyncMock(
366-
return_value=MagicMock(model_dump=lambda: {"id": "asst_123", "name": "newname"})
367-
)
368-
result = await agent.modify_assistant("asst_123", name="newname")
369-
assert result["id"] == "asst_123"
370-
assert result["name"] == "newname"
371-
372-
delattr(client, "assistants")
373-
with pytest.raises(NotImplementedError):
374-
await agent.modify_assistant("asst_123", name="newname")
375-
376-
call = FunctionCall(name="not_a_tool", arguments="{}", id="call1")
377-
exec_result = await agent._execute_tool_call(call, CancellationToken()) # type: ignore
378-
assert exec_result.is_error
379-
380-
agent._tool_map["bad_args"] = agent._tool_map["get_weather"] # type: ignore
381-
call = FunctionCall(name="bad_args", arguments="{invalid_json}", id="call2")
382-
exec_result = await agent._execute_tool_call(call, CancellationToken()) # type: ignore
383-
assert exec_result.is_error and "Invalid JSON" in exec_result.content
384-
mock_tool = MagicMock(spec=Tool)
385-
mock_tool.name = "fail_tool"
386-
mock_tool.run_json = AsyncMock(side_effect=Exception("fail"))
387-
mock_tool.return_value_as_string = MagicMock(return_value="error string")
388-
agent._tool_map["fail_tool"] = mock_tool # type: ignore
389-
390-
call = FunctionCall(name="fail_tool", arguments="{}", id="call3")
391-
exec_result = await agent._execute_tool_call(call, CancellationToken()) # type: ignore
392-
assert exec_result.is_error and "fail" in exec_result.content
393-
394-
return result
395-
396-
397328
@pytest.mark.asyncio
398329
async def test_on_messages_inner_messages(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:
399330
class DummyMsg(BaseChatMessage):
@@ -449,20 +380,6 @@ async def test_build_api_params(agent: OpenAIAgent) -> None:
449380
assert params.get("text") == {"type": "json_object"}
450381

451382

452-
@pytest.mark.asyncio
453-
async def test_delete_assistant(agent: OpenAIAgent) -> Dict[str, Any]:
454-
client = cast(Any, agent._client) # type: ignore
455-
client.assistants = MagicMock()
456-
client.assistants.delete = AsyncMock(return_value=MagicMock(model_dump=lambda: {"id": "asst_123"}))
457-
result = await agent.delete_assistant("asst_123")
458-
assert result["id"] == "asst_123"
459-
delattr(client, "assistants")
460-
with pytest.raises(NotImplementedError):
461-
await agent.delete_assistant("asst_123")
462-
463-
return result
464-
465-
466383
@pytest.mark.asyncio
467384
async def test_on_messages_previous_response_id(agent: OpenAIAgent, cancellation_token: CancellationToken) -> None:
468385
message = TextMessage(source="user", content="hi")

0 commit comments

Comments
 (0)