A programming framework for agentic AI
Refactor chat (#60)
Eric Zhu7ef502a33e87
diff --git a/examples/assistant.py b/examples/assistant.pyindex 7b82583cc..676239b39 100644--- a/examples/assistant.py+++ b/examples/assistant.py@@ -10,7 +10,6 @@ from typing import Any, Listimport aiofilesimport openaifrom agnext.application import SingleThreadedAgentRuntime-from agnext.chat.agents.base import BaseChatAgentfrom agnext.chat.agents.oai_assistant import OpenAIAssistantAgentfrom agnext.chat.patterns.group_chat import GroupChatOutputfrom agnext.chat.patterns.two_agent_chat import TwoAgentChat@@ -38,7 +37,7 @@ class TwoAgentChatOutput(GroupChatOutput): # type: ignoresep = "-" * 50-class UserProxyAgent(BaseChatAgent, TypeRoutedAgent): # type: ignore+class UserProxyAgent(TypeRoutedAgent): # type: ignoredef __init__(self,name: str,@@ -52,7 +51,7 @@ class UserProxyAgent(BaseChatAgent, TypeRoutedAgent): # type: ignorename=name,description="A human user",runtime=runtime,- )+ ) # type: ignoreself._client = clientself._assistant_id = assistant_idself._thread_id = thread_iddiff --git a/examples/futures.py b/examples/futures.pyindex 765fabfdc..84325b4cb 100644--- a/examples/futures.py+++ b/examples/futures.py@@ -12,22 +12,22 @@ class MessageType:sender: str-class Inner(TypeRoutedAgent):- def __init__(self, name: str, router: AgentRuntime) -> None:- super().__init__(name, router)+class Inner(TypeRoutedAgent): # type: ignore+ def __init__(self, name: str, router: AgentRuntime) -> None: # type: ignore+ super().__init__(name, "The inner agent", router)- @message_handler()- async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:+ @message_handler() # type: ignore+ async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignorereturn MessageType(body=f"Inner: {message.body}", sender=self.name)-class Outer(TypeRoutedAgent):- def __init__(self, name: str, router: AgentRuntime, inner: Agent) -> None:- super().__init__(name, router)+class Outer(TypeRoutedAgent): # type: ignore+ def __init__(self, name: str, router: AgentRuntime, inner: Agent) -> None: # type: ignore+ super().__init__(name, "The outter agent", router)self._inner = inner- @message_handler()- async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:+ @message_handler() # type: ignore+ async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignoreinner_response = self._send_message(message, self._inner)inner_message = await inner_responseassert isinstance(inner_message, MessageType)diff --git a/src/agnext/chat/agents/__init__.py b/src/agnext/chat/agents/__init__.pyindex e69de29bb..5846b5a20 100644--- a/src/agnext/chat/agents/__init__.py+++ b/src/agnext/chat/agents/__init__.py@@ -0,0 +1,4 @@+from .chat_completion_agent import ChatCompletionAgent+from .oai_assistant import OpenAIAssistantAgent++__all__ = ["ChatCompletionAgent", "OpenAIAssistantAgent"]diff --git a/src/agnext/chat/agents/base.py b/src/agnext/chat/agents/base.pydeleted file mode 100644index 5ee360528..000000000--- a/src/agnext/chat/agents/base.py+++ /dev/null@@ -1,14 +0,0 @@-from agnext.core import AgentRuntime, BaseAgent---class BaseChatAgent(BaseAgent):- """The BaseAgent class for the chat API."""-- def __init__(self, name: str, description: str, runtime: AgentRuntime) -> None:- super().__init__(name, runtime)- self._description = description-- @property- def description(self) -> str:- """The description of the agent."""- return self._descriptiondiff --git a/src/agnext/chat/agents/chat_completion_agent.py b/src/agnext/chat/agents/chat_completion_agent.pyindex a6a45e035..c46d78d57 100644--- a/src/agnext/chat/agents/chat_completion_agent.py+++ b/src/agnext/chat/agents/chat_completion_agent.py@@ -25,10 +25,9 @@ from ..types import (TextMessage,)from ..utils import convert_messages_to_llm_messages-from .base import BaseChatAgent-class ChatCompletionAgent(BaseChatAgent, TypeRoutedAgent):+class ChatCompletionAgent(TypeRoutedAgent):def __init__(self,name: str,@@ -40,6 +39,7 @@ class ChatCompletionAgent(BaseChatAgent, TypeRoutedAgent):tools: Sequence[Tool] = [],) -> None:super().__init__(name, description, runtime)+ self._description = descriptionself._system_messages = system_messagesself._client = model_clientself._memory = memorydiff --git a/src/agnext/chat/agents/oai_assistant.py b/src/agnext/chat/agents/oai_assistant.pyindex 7a75059e1..bd569f663 100644--- a/src/agnext/chat/agents/oai_assistant.py+++ b/src/agnext/chat/agents/oai_assistant.py@@ -4,13 +4,12 @@ import openaifrom openai import AsyncAssistantEventHandlerfrom openai.types.beta import AssistantResponseFormatParam-from agnext.chat.agents.base import BaseChatAgent-from agnext.chat.types import Reset, RespondNow, ResponseFormat, TextMessage-from agnext.components import TypeRoutedAgent, message_handler-from agnext.core import AgentRuntime, CancellationToken+from ...components import TypeRoutedAgent, message_handler+from ...core import AgentRuntime, CancellationToken+from ..types import Reset, RespondNow, ResponseFormat, TextMessage-class OpenAIAssistantAgent(BaseChatAgent, TypeRoutedAgent):+class OpenAIAssistantAgent(TypeRoutedAgent):def __init__(self,name: str,diff --git a/src/agnext/chat/patterns/group_chat.py b/src/agnext/chat/patterns/group_chat.pyindex 33d3c8c68..55e8bd07d 100644--- a/src/agnext/chat/patterns/group_chat.py+++ b/src/agnext/chat/patterns/group_chat.py@@ -1,8 +1,7 @@from typing import Any, List, Protocol, Sequencefrom ...components import TypeRoutedAgent, message_handler-from ...core import AgentRuntime, CancellationToken-from ..agents.base import BaseChatAgent+from ...core import Agent, AgentRuntime, CancellationTokenfrom ..types import Reset, RespondNow, TextMessage@@ -14,17 +13,18 @@ class GroupChatOutput(Protocol):def reset(self) -> None: ...-class GroupChat(BaseChatAgent, TypeRoutedAgent):+class GroupChat(TypeRoutedAgent):def __init__(self,name: str,description: str,runtime: AgentRuntime,- agents: Sequence[BaseChatAgent],+ participants: Sequence[Agent],num_rounds: int,output: GroupChatOutput,) -> None:- self._agents = agents+ self._description = description+ self._participants = participantsself._num_rounds = num_roundsself._history: List[Any] = []self._output = output@@ -32,7 +32,7 @@ class GroupChat(BaseChatAgent, TypeRoutedAgent):@propertydef subscriptions(self) -> Sequence[type]:- agent_sublists = [agent.subscriptions for agent in self._agents]+ agent_sublists = [agent.subscriptions for agent in self._participants]return [Reset, RespondNow] + [item for sublist in agent_sublists for item in sublist]@message_handler()@@ -55,10 +55,10 @@ class GroupChat(BaseChatAgent, TypeRoutedAgent):while round < self._num_rounds:# TODO: add support for advanced speaker selection.# Select speaker (round-robin for now).- speaker = self._agents[round % len(self._agents)]+ speaker = self._participants[round % len(self._participants)]# Send the last message to all agents except the previous speaker.- for agent in [agent for agent in self._agents if agent is not prev_speaker]:+ for agent in [agent for agent in self._participants if agent is not prev_speaker]:# TODO gather and await_ = await self._send_message(self._history[-1],diff --git a/src/agnext/chat/patterns/orchestrator_chat.py b/src/agnext/chat/patterns/orchestrator_chat.pyindex 6bc9999ff..427750332 100644--- a/src/agnext/chat/patterns/orchestrator_chat.py+++ b/src/agnext/chat/patterns/orchestrator_chat.py@@ -2,22 +2,21 @@ import jsonfrom typing import Any, Sequence, Tuplefrom ...components import TypeRoutedAgent, message_handler-from ...core import AgentRuntime, CancellationToken-from ..agents.base import BaseChatAgent+from ...core import Agent, AgentRuntime, CancellationTokenfrom ..types import Reset, RespondNow, ResponseFormat, TextMessage__all__ = ["OrchestratorChat"]-class OrchestratorChat(BaseChatAgent, TypeRoutedAgent):+class OrchestratorChat(TypeRoutedAgent):def __init__(self,name: str,description: str,runtime: AgentRuntime,- orchestrator: BaseChatAgent,- planner: BaseChatAgent,- specialists: Sequence[BaseChatAgent],+ orchestrator: Agent,+ planner: Agent,+ specialists: Sequence[Agent],max_turns: int = 30,max_stalled_turns_before_retry: int = 2,max_retry_attempts: int = 1,diff --git a/src/agnext/chat/patterns/two_agent_chat.py b/src/agnext/chat/patterns/two_agent_chat.pyindex a1d45a804..69cf54648 100644--- a/src/agnext/chat/patterns/two_agent_chat.py+++ b/src/agnext/chat/patterns/two_agent_chat.py@@ -1,7 +1,5 @@-from agnext.chat.patterns.group_chat import GroupChat, GroupChatOutput--from ...core import AgentRuntime-from ..agents.base import BaseChatAgent+from ...core import Agent, AgentRuntime+from .group_chat import GroupChat, GroupChatOutput# TODO: rewrite this with a new message type calling for add to message@@ -12,8 +10,8 @@ class TwoAgentChat(GroupChat):name: str,description: str,runtime: AgentRuntime,- first_speaker: BaseChatAgent,- second_speaker: BaseChatAgent,+ first_speaker: Agent,+ second_speaker: Agent,num_rounds: int,output: GroupChatOutput,) -> None:diff --git a/src/agnext/chat/types.py b/src/agnext/chat/types.pyindex 308f135db..a338d85b3 100644--- a/src/agnext/chat/types.py+++ b/src/agnext/chat/types.py@@ -4,8 +4,8 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import List, Union-from agnext.components import FunctionCall, Image-from agnext.components.models import FunctionExecutionResultMessage+from ..components import FunctionCall, Image+from ..components.models import FunctionExecutionResultMessage@dataclass(kw_only=True)diff --git a/src/agnext/chat/utils.py b/src/agnext/chat/utils.pyindex cfee683a7..d07924666 100644--- a/src/agnext/chat/utils.py+++ b/src/agnext/chat/utils.py@@ -2,19 +2,19 @@ from typing import List, Optional, Unionfrom typing_extensions import Literal-from agnext.chat.types import (- FunctionCallMessage,- Message,- MultiModalMessage,- TextMessage,-)-from agnext.components.models import (+from ..components.models import (AssistantMessage,FunctionExecutionResult,FunctionExecutionResultMessage,LLMMessage,UserMessage,)+from .types import (+ FunctionCallMessage,+ Message,+ MultiModalMessage,+ TextMessage,+)def convert_content_message_to_assistant_message(diff --git a/src/agnext/components/_type_routed_agent.py b/src/agnext/components/_type_routed_agent.pyindex 88bbdb35f..2d62bc735 100644--- a/src/agnext/components/_type_routed_agent.py+++ b/src/agnext/components/_type_routed_agent.py@@ -21,8 +21,8 @@ from typing import (runtime_checkable,)-from agnext.core import AgentRuntime, BaseAgent, CancellationToken-from agnext.core.exceptions import CantHandleException+from ..core import AgentRuntime, BaseAgent, CancellationToken+from ..core.exceptions import CantHandleExceptionlogger = logging.getLogger("agnext")@@ -132,7 +132,7 @@ def message_handler(class TypeRoutedAgent(BaseAgent):- def __init__(self, name: str, router: AgentRuntime) -> None:+ def __init__(self, name: str, description: str, runtime: AgentRuntime) -> None:# Self is already bound to the handlersself._handlers: Dict[Type[Any],@@ -147,7 +147,7 @@ class TypeRoutedAgent(BaseAgent):for target_type in message_handler.target_types:self._handlers[target_type] = message_handler- super().__init__(name, router)+ super().__init__(name, description, runtime)@propertydef subscriptions(self) -> Sequence[Type[Any]]:diff --git a/src/agnext/core/_agent.py b/src/agnext/core/_agent.pyindex 8869669f7..c4189e683 100644--- a/src/agnext/core/_agent.py+++ b/src/agnext/core/_agent.py@@ -1,6 +1,6 @@from typing import Any, Mapping, Protocol, Sequence, runtime_checkable-from agnext.core._cancellation_token import CancellationToken+from ._cancellation_token import CancellationToken@runtime_checkable@@ -14,6 +14,13 @@ class Agent(Protocol):"""...+ @property+ def description(self) -> str:+ """Description of the agent.++ A human-readable description of the agent."""+ ...+@propertydef subscriptions(self) -> Sequence[type]:"""Types of messages that this agent can receive."""diff --git a/src/agnext/core/_base_agent.py b/src/agnext/core/_base_agent.pyindex f570f2b3a..7b3aa74f1 100644--- a/src/agnext/core/_base_agent.py+++ b/src/agnext/core/_base_agent.py@@ -3,10 +3,9 @@ from abc import ABC, abstractmethodfrom asyncio import Futurefrom typing import Any, Mapping, Sequence, TypeVar-from agnext.core._agent_runtime import AgentRuntime-from agnext.core._cancellation_token import CancellationToken-from ._agent import Agent+from ._agent_runtime import AgentRuntime+from ._cancellation_token import CancellationTokenConsumesT = TypeVar("ConsumesT")ProducesT = TypeVar("ProducesT", covariant=True)@@ -16,8 +15,9 @@ OtherProducesT = TypeVar("OtherProducesT")class BaseAgent(ABC, Agent):- def __init__(self, name: str, router: AgentRuntime) -> None:+ def __init__(self, name: str, description: str, router: AgentRuntime) -> None:self._name = name+ self._description = descriptionself._router = routerrouter.add_agent(self)@@ -25,6 +25,10 @@ class BaseAgent(ABC, Agent):def name(self) -> str:return self._name+ @property+ def description(self) -> str:+ return self._description+@property@abstractmethoddef subscriptions(self) -> Sequence[type]:diff --git a/tests/test_cancellation.py b/tests/test_cancellation.pyindex 2f888554f..ab0a61bc6 100644--- a/tests/test_cancellation.py+++ b/tests/test_cancellation.py@@ -15,14 +15,14 @@ class MessageType:# To do cancellation, only the token should be interacted with as a user# If you cancel a future, it may not work as you expect.-class LongRunningAgent(TypeRoutedAgent):- def __init__(self, name: str, router: AgentRuntime) -> None:- super().__init__(name, router)+class LongRunningAgent(TypeRoutedAgent): # type: ignore+ def __init__(self, name: str, router: AgentRuntime) -> None: # type: ignore+ super().__init__(name, "A long running agent", router)self.called = Falseself.cancelled = False- @message_handler()- async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:+ @message_handler() # type: ignore+ async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignoreself.called = Truesleep = asyncio.ensure_future(asyncio.sleep(100))cancellation_token.link_future(sleep)@@ -33,15 +33,15 @@ class LongRunningAgent(TypeRoutedAgent):self.cancelled = Trueraise-class NestingLongRunningAgent(TypeRoutedAgent):- def __init__(self, name: str, router: AgentRuntime, nested_agent: Agent) -> None:- super().__init__(name, router)+class NestingLongRunningAgent(TypeRoutedAgent): # type: ignore+ def __init__(self, name: str, router: AgentRuntime, nested_agent: Agent) -> None: # type: ignore+ super().__init__(name, "A nesting long running agent", router)self.called = Falseself.cancelled = Falseself._nested_agent = nested_agent- @message_handler()- async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:+ @message_handler() # type: ignore+ async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignoreself.called = Trueresponse = self._send_message(message, self._nested_agent, cancellation_token=cancellation_token)try:diff --git a/tests/test_intervention.py b/tests/test_intervention.pyindex b0ccd83f9..c23c415bd 100644--- a/tests/test_intervention.py+++ b/tests/test_intervention.py@@ -12,25 +12,25 @@ from agnext.core.intervention import DefaultInterventionHandler, DropMessageclass MessageType:...-class LoopbackAgent(TypeRoutedAgent):- def __init__(self, name: str, router: AgentRuntime) -> None:- super().__init__(name, router)+class LoopbackAgent(TypeRoutedAgent): # type: ignore+ def __init__(self, name: str, router: AgentRuntime) -> None: # type: ignore+ super().__init__(name, "A loop back agent.", router)self.num_calls = 0- @message_handler()- async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:+ @message_handler() # type: ignore+ async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignoreself.num_calls += 1return message@pytest.mark.asyncioasync def test_intervention_count_messages() -> None:- class DebugInterventionHandler(DefaultInterventionHandler):+ class DebugInterventionHandler(DefaultInterventionHandler): # type: ignoredef __init__(self) -> None:self.num_messages = 0- async def on_send(self, message: MessageType, *, sender: Agent | None, recipient: Agent) -> MessageType:+ async def on_send(self, message: MessageType, *, sender: Agent | None, recipient: Agent) -> MessageType: # type: ignoreself.num_messages += 1return message@@ -49,9 +49,9 @@ async def test_intervention_count_messages() -> None:@pytest.mark.asyncioasync def test_intervention_drop_send() -> None:- class DropSendInterventionHandler(DefaultInterventionHandler):- async def on_send(self, message: MessageType, *, sender: Agent | None, recipient: Agent) -> MessageType | type[DropMessage]:- return DropMessage+ class DropSendInterventionHandler(DefaultInterventionHandler): # type: ignore+ async def on_send(self, message: MessageType, *, sender: Agent | None, recipient: Agent) -> MessageType | type[DropMessage]: # type: ignore+ return DropMessage # type: ignorehandler = DropSendInterventionHandler()router = SingleThreadedAgentRuntime(before_send=handler)@@ -71,9 +71,9 @@ async def test_intervention_drop_send() -> None:@pytest.mark.asyncioasync def test_intervention_drop_response() -> None:- class DropResponseInterventionHandler(DefaultInterventionHandler):- async def on_response(self, message: MessageType, *, sender: Agent, recipient: Agent | None) -> MessageType | type[DropMessage]:- return DropMessage+ class DropResponseInterventionHandler(DefaultInterventionHandler): # type: ignore+ async def on_response(self, message: MessageType, *, sender: Agent, recipient: Agent | None) -> MessageType | type[DropMessage]: # type: ignore+ return DropMessage # type: ignorehandler = DropResponseInterventionHandler()router = SingleThreadedAgentRuntime(before_send=handler)diff --git a/tests/test_runtime.py b/tests/test_runtime.pyindex 5acf11ed5..5f2edaafd 100644--- a/tests/test_runtime.py+++ b/tests/test_runtime.py@@ -5,15 +5,15 @@ from agnext.application import SingleThreadedAgentRuntimefrom agnext.core import AgentRuntime, BaseAgent, CancellationToken-class NoopAgent(BaseAgent):- def __init__(self, name: str, router: AgentRuntime) -> None:- super().__init__(name, router)+class NoopAgent(BaseAgent): # type: ignore+ def __init__(self, name: str, router: AgentRuntime) -> None: # type: ignore+ super().__init__(name, "A no op agent", router)@propertydef subscriptions(self) -> Sequence[type]:return []- async def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any:+ async def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any: # type: ignoreraise NotImplementedErrordiff --git a/tests/test_state.py b/tests/test_state.pyindex 52e6bff4c..63c170468 100644--- a/tests/test_state.py+++ b/tests/test_state.py@@ -5,16 +5,16 @@ from agnext.application import SingleThreadedAgentRuntimefrom agnext.core import AgentRuntime, BaseAgent, CancellationToken-class StatefulAgent(BaseAgent):- def __init__(self, name: str, runtime: AgentRuntime) -> None:- super().__init__(name, runtime)+class StatefulAgent(BaseAgent): # type: ignore+ def __init__(self, name: str, runtime: AgentRuntime) -> None: # type: ignore+ super().__init__(name, "A stateful agent", runtime)self.state = 0@propertydef subscriptions(self) -> Sequence[type]:return []- async def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any:+ async def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any: # type: ignoreraise NotImplementedErrordef save_state(self) -> Mapping[str, Any]: