A programming framework for agentic AI
`ChatAgent` declares the types of messages it produces (#3991)
Eric Zhu4a49844996f9
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.pyindex a94db9e91..a5dece3f6 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py@@ -207,6 +207,13 @@ class AssistantAgent(BaseChatAgent):)self._model_context: List[LLMMessage] = []+ @property+ def produced_message_types(self) -> List[type[ChatMessage]]:+ """The types of messages that the assistant agent produces."""+ if self._handoffs:+ return [TextMessage, HandoffMessage, StopMessage]+ return [TextMessage, StopMessage]+async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:# Add messages to the model context.for msg in messages:diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.pyindex 77bf4c02c..bc5352867 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from typing import Sequence+from typing import List, Sequencefrom autogen_core.base import CancellationToken@@ -30,6 +30,12 @@ class BaseChatAgent(ChatAgent, ABC):describe the agent's capabilities and how to interact with it."""return self._description+ @property+ @abstractmethod+ def produced_message_types(self) -> List[type[ChatMessage]]:+ """The types of messages that the agent produces."""+ ...+@abstractmethodasync def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:"""Handle incoming messages and return a response message."""diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.pyindex 07cb45c4d..c5c216e52 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py@@ -20,6 +20,11 @@ class CodeExecutorAgent(BaseChatAgent):super().__init__(name=name, description=description)self._code_executor = code_executor+ @property+ def produced_message_types(self) -> List[type[ChatMessage]]:+ """The types of messages that the code executor agent produces."""+ return [TextMessage]+async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:# Extract code blocks from the messages.code_blocks: List[CodeBlock] = []diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_chat_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_chat_agent.pyindex d82539540..689f6e6d5 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_chat_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_chat_agent.py@@ -1,4 +1,4 @@-from typing import Protocol, Sequence, runtime_checkable+from typing import List, Protocol, Sequence, runtime_checkablefrom autogen_core.base import CancellationToken@@ -24,6 +24,11 @@ class ChatAgent(TaskRunner, Protocol):describe the agent's capabilities and how to interact with it."""...+ @property+ def produced_message_types(self) -> List[type[ChatMessage]]:+ """The types of messages that the agent produces."""+ ...+async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:"""Handle incoming messages and return a response message."""...diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.pyindex acf5e9d2f..e2970ffe6 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.py@@ -36,6 +36,11 @@ class ChatAgentContainer(SequentialRoutedAgent):to the delegate agent and publish the response."""# Pass the messages in the buffer to the delegate agent.response = await self._agent.on_messages(self._message_buffer, ctx.cancellation_token)+ if not any(isinstance(response, msg_type) for msg_type in self._agent.produced_message_types):+ raise ValueError(+ f"The agent {self._agent.name} produced an unexpected message type: {type(response)}. "+ f"Expected one of: {self._agent.produced_message_types}"+ )# Publish the response.self._message_buffer.clear()diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.pyindex 694584706..872f12e2b 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py@@ -86,6 +86,10 @@ class Swarm(BaseGroupChat):super().__init__(participants, termination_condition=termination_condition, group_chat_manager_class=SwarmGroupChatManager)+ # The first participant must be able to produce handoff messages.+ first_participant = self._participants[0]+ if HandoffMessage not in first_participant.produced_message_types:+ raise ValueError("The first participant must be able to produce a handoff messages.")def _create_group_chat_manager_factory(self,diff --git a/python/packages/autogen-agentchat/tests/test_assistant_agent.py b/python/packages/autogen-agentchat/tests/test_assistant_agent.pyindex bff941b90..332a7bab1 100644--- a/python/packages/autogen-agentchat/tests/test_assistant_agent.py+++ b/python/packages/autogen-agentchat/tests/test_assistant_agent.py@@ -158,6 +158,7 @@ async def test_handoffs(monkeypatch: pytest.MonkeyPatch) -> None:tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],handoffs=[handoff],)+ assert HandoffMessage in tool_use_agent.produced_message_typesresponse = await tool_use_agent.on_messages([TextMessage(content="task", source="user")], cancellation_token=CancellationToken())diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.pyindex d209de3bd..1d04c78b6 100644--- a/python/packages/autogen-agentchat/tests/test_group_chat.py+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py@@ -62,6 +62,10 @@ class _EchoAgent(BaseChatAgent):super().__init__(name, description)self._last_message: str | None = None+ @property+ def produced_message_types(self) -> List[type[ChatMessage]]:+ return [TextMessage]+async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:if len(messages) > 0:assert isinstance(messages[0], TextMessage)@@ -78,6 +82,10 @@ class _StopAgent(_EchoAgent):self._count = 0self._stop_at = stop_at+ @property+ def produced_message_types(self) -> List[type[ChatMessage]]:+ return [TextMessage, StopMessage]+async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:self._count += 1if self._count < self._stop_at:@@ -415,6 +423,10 @@ class _HandOffAgent(BaseChatAgent):super().__init__(name, description)self._next_agent = next_agent+ @property+ def produced_message_types(self) -> List[type[ChatMessage]]:+ return [HandoffMessage]+async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:return HandoffMessage(content=f"Transferred to {self._next_agent}.", target=self._next_agent, source=self.name)diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/agents.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/agents.ipynbindex b6da9dd88..0e58c2522 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/agents.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/agents.ipynb@@ -248,7 +248,7 @@],"source": ["import asyncio\n",- "from typing import Sequence\n",+ "from typing import List, Sequence\n","\n","from autogen_agentchat.agents import BaseChatAgent\n","from autogen_agentchat.messages import (\n",@@ -262,6 +262,10 @@" def __init__(self, name: str) -> None:\n"," super().__init__(name, \"A human user.\")\n","\n",+ " @property\n",+ " def produced_message_types(self) -> List[type[ChatMessage]]:\n",+ " return [TextMessage, StopMessage]\n",+ "\n"," async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:\n"," user_input = await asyncio.get_event_loop().run_in_executor(None, input, \"Enter your response: \")\n"," if \"TERMINATE\" in user_input:\n",@@ -312,7 +316,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.12.6"+ "version": "3.11.5"}},"nbformat": 4,diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynbindex e85715d2b..f5a5358aa 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynb@@ -38,7 +38,7 @@"outputs": [],"source": ["import asyncio\n",- "from typing import Sequence\n",+ "from typing import List, Sequence\n","\n","from autogen_agentchat.agents import (\n"," BaseChatAgent,\n",@@ -71,6 +71,10 @@" def __init__(self, name: str) -> None:\n"," super().__init__(name, \"A human user.\")\n","\n",+ " @property\n",+ " def produced_message_types(self) -> List[type[ChatMessage]]:\n",+ " return [TextMessage, StopMessage]\n",+ "\n"," async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> ChatMessage:\n"," user_input = await asyncio.get_event_loop().run_in_executor(None, input, \"Enter your response: \")\n"," if \"TERMINATE\" in user_input:\n",@@ -269,7 +273,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.12.6"+ "version": "3.11.5"}},"nbformat": 4,