Skip to content

A programming framework for agentic AI

Refactor agentchat to separate base interfaces from implementations (#3877)

Eric Zhu8a4930a9be33
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py
index 21813ed4e..e5f1bd8b6 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py
@@ -1,29 +1,9 @@
-from ._base_chat_agent import (
- BaseChatAgent,
- BaseMessage,
- BaseToolUseChatAgent,
- ChatMessage,
- MultiModalMessage,
- StopMessage,
- TextMessage,
- ToolCallMessage,
- ToolCallResultMessage,
-)
from ._code_executor_agent import CodeExecutorAgent
from ._coding_assistant_agent import CodingAssistantAgent
from ._tool_use_assistant_agent import ToolUseAssistantAgent
__all__ = [
- "BaseChatAgent",
- "BaseMessage",
- "BaseToolUseChatAgent",
- "ChatMessage",
"CodeExecutorAgent",
"CodingAssistantAgent",
- "MultiModalMessage",
- "StopMessage",
- "TextMessage",
- "ToolCallMessage",
- "ToolCallResultMessage",
"ToolUseAssistantAgent",
]
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.py
index 3c695dc0b..c38facbe5 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
@@ -3,7 +3,8 @@ from typing import List, Sequence
from autogen_core.base import CancellationToken
from autogen_core.components.code_executor import CodeBlock, CodeExecutor, extract_markdown_code_blocks
-from ._base_chat_agent import BaseChatAgent, ChatMessage, TextMessage
+from ..base import BaseChatAgent
+from ..messages import ChatMessage, TextMessage
class CodeExecutorAgent(BaseChatAgent):
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_coding_assistant_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_coding_assistant_agent.py
index 36edd0bcd..b93621519 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_coding_assistant_agent.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_coding_assistant_agent.py
@@ -9,7 +9,8 @@ from autogen_core.components.models import (
UserMessage,
)
-from ._base_chat_agent import BaseChatAgent, ChatMessage, MultiModalMessage, StopMessage, TextMessage
+from ..base import BaseChatAgent
+from ..messages import ChatMessage, MultiModalMessage, StopMessage, TextMessage
class CodingAssistantAgent(BaseChatAgent):
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_tool_use_assistant_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_tool_use_assistant_agent.py
index 0453abc59..bb6ace764 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_tool_use_assistant_agent.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_tool_use_assistant_agent.py
@@ -12,8 +12,8 @@ from autogen_core.components.models import (
)
from autogen_core.components.tools import Tool
-from ._base_chat_agent import (
- BaseToolUseChatAgent,
+from ..base import BaseToolUseChatAgent
+from ..messages import (
ChatMessage,
MultiModalMessage,
StopMessage,
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/base/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/__init__.py
new file mode 100644
index 000000000..3b942afbd
--- /dev/null
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/__init__.py
@@ -0,0 +1,14 @@
+from ._base_chat_agent import BaseChatAgent, BaseToolUseChatAgent
+from ._base_task import TaskResult, TaskRunner
+from ._base_team import Team
+from ._base_termination import TerminatedException, TerminationCondition
+
+__all__ = [
+ "BaseChatAgent",
+ "BaseToolUseChatAgent",
+ "Team",
+ "TerminatedException",
+ "TerminationCondition",
+ "TaskResult",
+ "TaskRunner",
+]
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_chat_agent.py
similarity index 60%
rename from python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py
rename to python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_chat_agent.py
index b52745968..184e9061a 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_chat_agent.py
@@ -2,59 +2,13 @@ from abc import ABC, abstractmethod
from typing import List, Sequence
from autogen_core.base import CancellationToken
-from autogen_core.components import FunctionCall, Image
-from autogen_core.components.models import FunctionExecutionResult
from autogen_core.components.tools import Tool
-from pydantic import BaseModel
+from ..messages import ChatMessage
+from ._base_task import TaskResult, TaskRunner
-class BaseMessage(BaseModel):
- """A base message."""
- source: str
- """The name of the agent that sent this message."""
-
-
-class TextMessage(BaseMessage):
- """A text message."""
-
- content: str
- """The content of the message."""
-
-
-class MultiModalMessage(BaseMessage):
- """A multimodal message."""
-
- content: List[str | Image]
- """The content of the message."""
-
-
-class ToolCallMessage(BaseMessage):
- """A message containing a list of function calls."""
-
- content: List[FunctionCall]
- """The list of function calls."""
-
-
-class ToolCallResultMessage(BaseMessage):
- """A message containing the results of function calls."""
-
- content: List[FunctionExecutionResult]
- """The list of function execution results."""
-
-
-class StopMessage(BaseMessage):
- """A message requesting stop of a conversation."""
-
- content: str
- """The content for the stop message."""
-
-
-ChatMessage = TextMessage | MultiModalMessage | StopMessage | ToolCallMessage | ToolCallResultMessage
-"""A message used by agents in a team."""
-
-
-class BaseChatAgent(ABC):
+class BaseChatAgent(TaskRunner, ABC):
"""Base class for a chat agent that can participant in a team."""
def __init__(self, name: str, description: str) -> None:
@@ -81,6 +35,12 @@ class BaseChatAgent(ABC):
"""Handle incoming messages and return a response message."""
...
+ async def run(
+ self, task: str, *, source: str = "user", cancellation_token: CancellationToken | None = None
+ ) -> TaskResult:
+ # TODO: Implement this method.
+ raise NotImplementedError
+
class BaseToolUseChatAgent(BaseChatAgent):
"""Base class for a chat agent that can use tools.
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_task.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_task.py
new file mode 100644
index 000000000..103721557
--- /dev/null
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_task.py
@@ -0,0 +1,20 @@
+from dataclasses import dataclass
+from typing import Protocol, Sequence
+
+from ..messages import ChatMessage
+
+
+@dataclass
+class TaskResult:
+ """Result of running a task."""
+
+ messages: Sequence[ChatMessage]
+ """Messages produced by the task."""
+
+
+class TaskRunner(Protocol):
+ """A task runner."""
+
+ async def run(self, task: str) -> TaskResult:
+ """Run the task."""
+ ...
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_team.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_team.py
new file mode 100644
index 000000000..5c3677fdc
--- /dev/null
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_team.py
@@ -0,0 +1,10 @@
+from typing import Protocol
+
+from ._base_task import TaskResult, TaskRunner
+from ._base_termination import TerminationCondition
+
+
+class Team(TaskRunner, Protocol):
+ async def run(self, task: str, *, termination_condition: TerminationCondition | None = None) -> TaskResult:
+ """Run the team on a given task until the termination condition is met."""
+ ...
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_termination.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_termination.py
similarity index 61%
rename from python/packages/autogen-agentchat/src/autogen_agentchat/teams/_termination.py
rename to python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_termination.py
index 78e20a93b..0d0a056ea 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_termination.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_base_termination.py
@@ -2,7 +2,7 @@ import asyncio
from abc import ABC, abstractmethod
from typing import List, Sequence
-from ..agents import ChatMessage, MultiModalMessage, StopMessage, TextMessage
+from ..messages import ChatMessage, StopMessage
class TerminatedException(BaseException): ...
@@ -127,89 +127,3 @@ class _OrTerminationCondition(TerminationCondition):
async def reset(self) -> None:
for condition in self._conditions:
await condition.reset()
-
-
-class StopMessageTermination(TerminationCondition):
- """Terminate the conversation if a StopMessage is received."""
-
- def __init__(self) -> None:
- self._terminated = False
-
- @property
- def terminated(self) -> bool:
- return self._terminated
-
- async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
- if self._terminated:
- raise TerminatedException("Termination condition has already been reached")
- for message in messages:
- if isinstance(message, StopMessage):
- self._terminated = True
- return StopMessage(content="Stop message received", source="StopMessageTermination")
- return None
-
- async def reset(self) -> None:
- self._terminated = False
-
-
-class MaxMessageTermination(TerminationCondition):
- """Terminate the conversation after a maximum number of messages have been exchanged.
-
- Args:
- max_messages: The maximum number of messages allowed in the conversation.
- """
-
- def __init__(self, max_messages: int) -> None:
- self._max_messages = max_messages
- self._message_count = 0
-
- @property
- def terminated(self) -> bool:
- return self._message_count >= self._max_messages
-
- async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
- if self.terminated:
- raise TerminatedException("Termination condition has already been reached")
- self._message_count += len(messages)
- if self._message_count >= self._max_messages:
- return StopMessage(
- content=f"Maximal number of messages {self._max_messages} reached, current message count: {self._message_count}",
- source="MaxMessageTermination",
- )
- return None
-
- async def reset(self) -> None:
- self._message_count = 0
-
-
-class TextMentionTermination(TerminationCondition):
- """Terminate the conversation if a specific text is mentioned.
-
- Args:
- text: The text to look for in the messages.
- """
-
- def __init__(self, text: str) -> None:
- self._text = text
- self._terminated = False
-
- @property
- def terminated(self) -> bool:
- return self._terminated
-
- async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
- if self._terminated:
- raise TerminatedException("Termination condition has already been reached")
- for message in messages:
- if isinstance(message, TextMessage | StopMessage) and self._text in message.content:
- self._terminated = True
- return StopMessage(content=f"Text '{self._text}' mentioned", source="TextMentionTermination")
- elif isinstance(message, MultiModalMessage):
- for item in message.content:
- if isinstance(item, str) and self._text in item:
- self._terminated = True
- return StopMessage(content=f"Text '{self._text}' mentioned", source="TextMentionTermination")
- return None
-
- async def reset(self) -> None:
- self._terminated = False
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/logging/_console_log_handler.py b/python/packages/autogen-agentchat/src/autogen_agentchat/logging/_console_log_handler.py
index 5ff7c689a..d0fb4ab08 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/logging/_console_log_handler.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/logging/_console_log_handler.py
@@ -3,7 +3,7 @@ import logging
import sys
from datetime import datetime
-from ..agents import ChatMessage, StopMessage, TextMessage
+from ..messages import ChatMessage, StopMessage, TextMessage
from ..teams._events import (
ContentPublishEvent,
SelectSpeakerEvent,
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py b/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py
new file mode 100644
index 000000000..6aac22248
--- /dev/null
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py
@@ -0,0 +1,62 @@
+from typing import List
+
+from autogen_core.components import FunctionCall, Image
+from autogen_core.components.models import FunctionExecutionResult
+from pydantic import BaseModel
+
+
+class BaseMessage(BaseModel):
+ """A base message."""
+
+ source: str
+ """The name of the agent that sent this message."""
+
+
+class TextMessage(BaseMessage):
+ """A text message."""
+
+ content: str
+ """The content of the message."""
+
+
+class MultiModalMessage(BaseMessage):
+ """A multimodal message."""
+
+ content: List[str | Image]
+ """The content of the message."""
+
+
+class ToolCallMessage(BaseMessage):
+ """A message containing a list of function calls."""
+
+ content: List[FunctionCall]
+ """The list of function calls."""
+
+
+class ToolCallResultMessage(BaseMessage):
+ """A message containing the results of function calls."""
+
+ content: List[FunctionExecutionResult]
+ """The list of function execution results."""
+
+
+class StopMessage(BaseMessage):
+ """A message requesting stop of a conversation."""
+
+ content: str
+ """The content for the stop message."""
+
+
+ChatMessage = TextMessage | MultiModalMessage | StopMessage | ToolCallMessage | ToolCallResultMessage
+"""A message used by agents in a team."""
+
+
+__all__ = [
+ "BaseMessage",
+ "TextMessage",
+ "MultiModalMessage",
+ "ToolCallMessage",
+ "ToolCallResultMessage",
+ "StopMessage",
+ "ChatMessage",
+]
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py
index f1a79cff7..e305a9e5c 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py
@@ -1,9 +1,8 @@
from ._group_chat._round_robin_group_chat import RoundRobinGroupChat
from ._group_chat._selector_group_chat import SelectorGroupChat
-from ._termination import MaxMessageTermination, StopMessageTermination, TerminationCondition, TextMentionTermination
+from ._terminations import MaxMessageTermination, StopMessageTermination, TextMentionTermination
__all__ = [
- "TerminationCondition",
"MaxMessageTermination",
"TextMentionTermination",
"StopMessageTermination",
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_base_team.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_base_team.py
deleted file mode 100644
index 312524b8c..000000000
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_base_team.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from dataclasses import dataclass
-from typing import List, Protocol
-
-from ..agents import ChatMessage
-from ._termination import TerminationCondition
-
-
-@dataclass
-class TeamRunResult:
- messages: List[ChatMessage]
- """The messages generated by the team."""
-
-
-class BaseTeam(Protocol):
- async def run(self, task: str, *, termination_condition: TerminationCondition | None = None) -> TeamRunResult:
- """Run the team on a given task until the termination condition is met."""
- ...
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_events.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_events.py
index acdc9bdbd..5bfeff417 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_events.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_events.py
@@ -1,7 +1,7 @@
from autogen_core.base import AgentId
from pydantic import BaseModel, ConfigDict
-from ..agents import MultiModalMessage, StopMessage, TextMessage, ToolCallMessage, ToolCallResultMessage
+from ..messages import MultiModalMessage, StopMessage, TextMessage, ToolCallMessage, ToolCallResultMessage
class ContentPublishEvent(BaseModel):
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_chat_agent_container.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_chat_agent_container.py
index 3ec378f73..275e505d6 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_chat_agent_container.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_chat_agent_container.py
@@ -8,7 +8,8 @@ from autogen_core.components.models import FunctionExecutionResult
from autogen_core.components.tool_agent import ToolException
from ... import EVENT_LOGGER_NAME
-from ...agents import BaseChatAgent, MultiModalMessage, StopMessage, TextMessage, ToolCallMessage, ToolCallResultMessage
+from ...base import BaseChatAgent
+from ...messages import MultiModalMessage, StopMessage, TextMessage, ToolCallMessage, ToolCallResultMessage
from .._events import ContentPublishEvent, ContentRequestEvent, ToolCallEvent, ToolCallResultEvent
from ._sequential_routed_agent import SequentialRoutedAgent
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py
index 633fc0f85..08f44a1af 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py
@@ -8,15 +8,14 @@ from autogen_core.components import ClosureAgent, TypeSubscription
from autogen_core.components.tool_agent import ToolAgent
from autogen_core.components.tools import Tool
-from ...agents import BaseChatAgent, BaseToolUseChatAgent, ChatMessage, TextMessage
-from .._base_team import BaseTeam, TeamRunResult
+from ...base import BaseChatAgent, BaseToolUseChatAgent, TaskResult, Team, TerminationCondition
+from ...messages import ChatMessage, TextMessage
from .._events import ContentPublishEvent, ContentRequestEvent
-from .._termination import TerminationCondition
from ._base_chat_agent_container import BaseChatAgentContainer
from ._base_group_chat_manager import BaseGroupChatManager
-class BaseGroupChat(BaseTeam, ABC):
+class BaseGroupChat(Team, ABC):
"""The base class for group chat teams.
To implement a group chat team, first create a subclass of :class:`BaseGroupChatManager` and then
@@ -69,7 +68,7 @@ class BaseGroupChat(BaseTeam, ABC):
return _factory
- async def run(self, task: str, *, termination_condition: TerminationCondition | None = None) -> TeamRunResult:
+ async def run(self, task: str, *, termination_condition: TerminationCondition | None = None) -> TaskResult:
"""Run the team and return the result."""
# Create intervention handler for termination.
@@ -170,4 +169,4 @@ class BaseGroupChat(BaseTeam, ABC):
await runtime.stop_when_idle()
# Return the result.
- return TeamRunResult(messages=group_chat_messages)
+ return TaskResult(messages=group_chat_messages)
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py
index 38170053a..5f59e9e63 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py
@@ -6,8 +6,8 @@ from autogen_core.base import MessageContext, TopicId
from autogen_core.components import event
from ... import EVENT_LOGGER_NAME
+from ...base import TerminationCondition
from .._events import ContentPublishEvent, ContentRequestEvent, TerminationEvent
-from .._termination import TerminationCondition
from ._sequential_routed_agent import SequentialRoutedAgent
event_logger = logging.getLogger(EVENT_LOGGER_NAME)
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py
index 6ebacaac3..daab98602 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py
@@ -1,8 +1,7 @@
from typing import Callable, List
-from ...agents import BaseChatAgent
+from ...base import BaseChatAgent, TerminationCondition
from .._events import ContentPublishEvent
-from .._termination import TerminationCondition
from ._base_group_chat import BaseGroupChat
from ._base_group_chat_manager import BaseGroupChatManager
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
index 473b92f32..f000cbd69 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
@@ -5,9 +5,9 @@ from typing import Callable, Dict, List
from autogen_core.components.models import ChatCompletionClient, SystemMessage
from ... import EVENT_LOGGER_NAME, TRACE_LOGGER_NAME
-from ...agents import BaseChatAgent, MultiModalMessage, StopMessage, TextMessage
+from ...base import BaseChatAgent, TerminationCondition
+from ...messages import MultiModalMessage, StopMessage, TextMessage
from .._events import ContentPublishEvent, SelectSpeakerEvent
-from .._termination import TerminationCondition
from ._base_group_chat import BaseGroupChat
from ._base_group_chat_manager import BaseGroupChatManager
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_terminations.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_terminations.py
new file mode 100644
index 000000000..191e14f85
--- /dev/null
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_terminations.py
@@ -0,0 +1,90 @@
+from typing import Sequence
+
+from ..base import TerminatedException, TerminationCondition
+from ..messages import ChatMessage, MultiModalMessage, StopMessage, TextMessage
+
+
+class StopMessageTermination(TerminationCondition):
+ """Terminate the conversation if a StopMessage is received."""
+
+ def __init__(self) -> None:
+ self._terminated = False
+
+ @property
+ def terminated(self) -> bool:
+ return self._terminated
+
+ async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
+ if self._terminated:
+ raise TerminatedException("Termination condition has already been reached")
+ for message in messages:
+ if isinstance(message, StopMessage):
+ self._terminated = True
+ return StopMessage(content="Stop message received", source="StopMessageTermination")
+ return None
+
+ async def reset(self) -> None:
+ self._terminated = False
+
+
+class MaxMessageTermination(TerminationCondition):
+ """Terminate the conversation after a maximum number of messages have been exchanged.
+
+ Args:
+ max_messages: The maximum number of messages allowed in the conversation.
+ """
+
+ def __init__(self, max_messages: int) -> None:
+ self._max_messages = max_messages
+ self._message_count = 0
+
+ @property
+ def terminated(self) -> bool:
+ return self._message_count >= self._max_messages
+
+ async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
+ if self.terminated:
+ raise TerminatedException("Termination condition has already been reached")
+ self._message_count += len(messages)
+ if self._message_count >= self._max_messages:
+ return StopMessage(
+ content=f"Maximal number of messages {self._max_messages} reached, current message count: {self._message_count}",
+ source="MaxMessageTermination",
+ )
+ return None
+
+ async def reset(self) -> None:
+ self._message_count = 0
+
+
+class TextMentionTermination(TerminationCondition):
+ """Terminate the conversation if a specific text is mentioned.
+
+ Args:
+ text: The text to look for in the messages.
+ """
+
+ def __init__(self, text: str) -> None:
+ self._text = text
+ self._terminated = False
+
+ @property
+ def terminated(self) -> bool:
+ return self._terminated
+
+ async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
+ if self._terminated:
+ raise TerminatedException("Termination condition has already been reached")
+ for message in messages:
+ if isinstance(message, TextMessage | StopMessage) and self._text in message.content:
+ self._terminated = True
+ return StopMessage(content=f"Text '{self._text}' mentioned", source="TextMentionTermination")
+ elif isinstance(message, MultiModalMessage):
+ for item in message.content:
+ if isinstance(item, str) and self._text in item:
+ self._terminated = True
+ return StopMessage(content=f"Text '{self._text}' mentioned", source="TextMentionTermination")
+ return None
+
+ async def reset(self) -> None:
+ self._terminated = False
diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.py
index 21fb2ad40..54e759663 100644
--- a/python/packages/autogen-agentchat/tests/test_group_chat.py
+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py
@@ -7,15 +7,13 @@ from typing import Any, AsyncGenerator, List, Sequence
import pytest
from autogen_agentchat import EVENT_LOGGER_NAME
from autogen_agentchat.agents import (
- BaseChatAgent,
- ChatMessage,
CodeExecutorAgent,
CodingAssistantAgent,
- StopMessage,
- TextMessage,
ToolUseAssistantAgent,
)
+from autogen_agentchat.base import BaseChatAgent
from autogen_agentchat.logging import FileLogHandler
+from autogen_agentchat.messages import ChatMessage, StopMessage, TextMessage
from autogen_agentchat.teams import (
RoundRobinGroupChat,
SelectorGroupChat,
diff --git a/python/packages/autogen-agentchat/tests/test_termination_condition.py b/python/packages/autogen-agentchat/tests/test_termination_condition.py
index fe850542f..c3f575d34 100644
--- a/python/packages/autogen-agentchat/tests/test_termination_condition.py
+++ b/python/packages/autogen-agentchat/tests/test_termination_condition.py
@@ -1,5 +1,5 @@
import pytest
-from autogen_agentchat.agents import StopMessage, TextMessage
+from autogen_agentchat.messages import StopMessage, TextMessage
from autogen_agentchat.teams import MaxMessageTermination, StopMessageTermination, TextMentionTermination
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.ipynb
index 649c90dc3..55fc8c203 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
@@ -16,7 +16,7 @@
"\n",
"AgentChat provides a set of preset Agents, each with variations in how an agent might respond to received messages. \n",
"\n",
- "Each agent inherits from a {py:class}`~autogen_agentchat.agents.BaseChatAgent` class with a few generic properties:\n",
+ "Each agent inherits from a {py:class}`~autogen_agentchat.base.BaseChatAgent` class with a few generic properties:\n",
"\n",
"- `name`: The name of the agent. This is used by the team to uniquely identify the agent. It should be unique within the team.\n",
"- `description`: The description of the agent. This is used by the team to make decisions about which agents to use. The description should detail the agent's capabilities and how to interact with it.\n",
@@ -30,7 +30,7 @@
"To learn more about the runtime in `autogen-core`, see the [autogen-core documentation on agents and runtime](../../core-user-guide/framework/agent-and-agent-runtime.ipynb).\n",
"```\n",
"\n",
- "Each agent also implements an {py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_messages` method that defines the behavior of the agent in response to a message.\n",
+ "Each agent also implements an {py:meth}`~autogen_agentchat.base.BaseChatAgent.on_messages` method that defines the behavior of the agent in response to a message.\n",
"\n",
"\n",
"To begin, let us import the required classes and set up a model client that will be used by agents.\n"
@@ -45,8 +45,9 @@
"import logging\n",
"\n",
"from autogen_agentchat import EVENT_LOGGER_NAME\n",
- "from autogen_agentchat.agents import CodingAssistantAgent, TextMessage, ToolUseAssistantAgent\n",
+ "from autogen_agentchat.agents import CodingAssistantAgent, ToolUseAssistantAgent\n",
"from autogen_agentchat.logging import ConsoleLogHandler\n",
+ "from autogen_agentchat.messages import TextMessage\n",
"from autogen_agentchat.teams import MaxMessageTermination, RoundRobinGroupChat, SelectorGroupChat\n",
"from autogen_core.base import CancellationToken\n",
"from autogen_core.components.models import OpenAIChatCompletionClient\n",
@@ -250,8 +251,8 @@
"import asyncio\n",
"from typing import Sequence\n",
"\n",
- "from autogen_agentchat.agents import (\n",
- " BaseChatAgent,\n",
+ "from autogen_agentchat.base import BaseChatAgent\n",
+ "from autogen_agentchat.messages import (\n",
" ChatMessage,\n",
" StopMessage,\n",
" TextMessage,\n",
@@ -298,7 +299,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "agnext",
+ "display_name": ".venv",
"language": "python",
"name": "python3"
},
@@ -312,7 +313,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.9"
+ "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.ipynb
index 7636f14d9..399fb5a4d 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
@@ -41,13 +41,11 @@
"from typing import Sequence\n",
"\n",
"from autogen_agentchat.agents import (\n",
- " BaseChatAgent,\n",
- " ChatMessage,\n",
" CodingAssistantAgent,\n",
- " StopMessage,\n",
- " TextMessage,\n",
" ToolUseAssistantAgent,\n",
")\n",
+ "from autogen_agentchat.base import BaseChatAgent\n",
+ "from autogen_agentchat.messages import ChatMessage, StopMessage, TextMessage\n",
"from autogen_agentchat.teams import SelectorGroupChat, StopMessageTermination\n",
"from autogen_core.base import CancellationToken\n",
"from autogen_core.components.tools import FunctionTool\n",
@@ -270,7 +268,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/teams.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb
index ce30aee61..d957a90c5 100644
--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb
+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb
@@ -194,7 +194,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "agnext",
+ "display_name": ".venv",
"language": "python",
"name": "python3"
},
@@ -208,7 +208,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.9"
+ "version": "3.11.5"
}
},
"nbformat": 4,
diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb
index bdb1dccff..444e56b2b 100644
--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb
+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb
@@ -9,7 +9,7 @@
"\n",
"In the previous section, we explored how to define agents, and organize them into teams that can solve tasks by communicating (a conversation). However, conversations can go on forever, and in many cases, we need to know _when_ to stop them. This is the role of the termination condition.\n",
"\n",
- "AgentChat supports several termination condition by providing a base `TerminationCondition` class and several implementations that inherit from it.\n",
+ "AgentChat supports several termination condition by providing a base {py:class}`~autogen_agentchat.base.TerminationCondition` class and several implementations that inherit from it.\n",
"\n",
"A termination condition is a callable that takes a sequence of ChatMessage objects since the last time the condition was called, and returns a StopMessage if the conversation should be terminated, or None otherwise. Once a termination condition has been reached, it must be reset before it can be used again.\n",
"\n",
@@ -66,7 +66,7 @@
"source": [
"## MaxMessageTermination \n",
"\n",
- "The simplest termination condition is the `MaxMessageTermination` condition, which terminates the conversation after a fixed number of messages. \n"
+ "The simplest termination condition is the {py:class}`~autogen_agentchat.teams.MaxMessageTermination` condition, which terminates the conversation after a fixed number of messages. \n"
]
},
{
@@ -184,7 +184,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "agnext",
+ "display_name": ".venv",
"language": "python",
"name": "python3"
},
@@ -198,7 +198,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.9"
+ "version": "3.11.5"
}
},
"nbformat": 4,