A programming framework for agentic AI
use agent id in apis (#85)
Jack Gerritsedb939f4d7b5
diff --git a/examples/assistant.py b/examples/assistant.pyindex 7a21ab02e..d325b02a4 100644--- a/examples/assistant.py+++ b/examples/assistant.py@@ -200,7 +200,7 @@ def assistant_chat(runtime: AgentRuntime) -> UserProxyAgent: # type: ignoredescription="A group chat manager.",runtime=runtime,memory=BufferedChatMemory(buffer_size=10),- participants=[assistant, user],+ participants=[assistant.id, user.id],)return userdiff --git a/examples/chess_game.py b/examples/chess_game.pyindex a8a7ff030..3e4c61fee 100644--- a/examples/chess_game.py+++ b/examples/chess_game.py@@ -189,7 +189,7 @@ def chess_game(runtime: AgentRuntime) -> None: # type: ignoredescription="A chess game between two agents.",runtime=runtime,memory=BufferedChatMemory(buffer_size=10),- participants=[white, black], # white goes first+ participants=[white.id, black.id], # white goes first)diff --git a/examples/coder_reviewer.py b/examples/coder_reviewer.pyindex 9a38260d3..92e9c53e3 100644--- a/examples/coder_reviewer.py+++ b/examples/coder_reviewer.py@@ -41,7 +41,7 @@ def coder_reviewer(runtime: AgentRuntime) -> None:name="Manager",description="A manager that orchestrates a back-and-forth converation between a coder and a reviewer.",runtime=runtime,- participants=[coder, reviewer], # The order of the participants indicates the order of speaking.+ participants=[coder.id, reviewer.id], # The order of the participants indicates the order of speaking.memory=BufferedChatMemory(buffer_size=10),termination_word="APPROVE",on_message_received=lambda message: print(f"{'-'*80}\n{message.source}: {message.content}"),diff --git a/examples/futures.py b/examples/futures.pyindex f810d9490..7e7cac1ed 100644--- a/examples/futures.py+++ b/examples/futures.py@@ -3,7 +3,7 @@ from dataclasses import dataclassfrom agnext.application import SingleThreadedAgentRuntimefrom agnext.components import TypeRoutedAgent, message_handler-from agnext.core import Agent, AgentRuntime, CancellationToken+from agnext.core import AgentProxy, AgentRuntime, CancellationToken@dataclass@@ -13,8 +13,8 @@ class MessageType:class Inner(TypeRoutedAgent): # type: ignore- def __init__(self, name: str, router: AgentRuntime) -> None: # type: ignore- super().__init__(name, "The inner agent", router)+ def __init__(self, name: str, runtime: AgentRuntime) -> None: # type: ignore+ super().__init__(name, "The inner agent", runtime)@message_handler() # type: ignoreasync def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignore@@ -22,26 +22,26 @@ class Inner(TypeRoutedAgent): # type: ignoreclass Outer(TypeRoutedAgent): # type: ignore- def __init__(self, name: str, router: AgentRuntime, inner: Agent) -> None: # type: ignore- super().__init__(name, "The outter agent", router)+ def __init__(self, name: str, runtime: AgentRuntime, inner: AgentProxy) -> None: # type: ignore+ super().__init__(name, "The outter agent", runtime)self._inner = inner@message_handler() # type: ignoreasync def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignore- inner_response = self._send_message(message, self._inner)+ inner_response = self._send_message(message, self._inner.id)inner_message = await inner_responseassert isinstance(inner_message, MessageType)return MessageType(body=f"Outer: {inner_message.body}", sender=self.metadata["name"])async def main() -> None:- router = SingleThreadedAgentRuntime()- inner = Inner("inner", router)- outer = Outer("outer", router, inner)- response = router.send_message(MessageType(body="Hello", sender="external"), outer)+ runtime = SingleThreadedAgentRuntime()+ inner = Inner("inner", runtime)+ outer = Outer("outer", runtime, AgentProxy(inner, runtime))+ response = runtime.send_message(MessageType(body="Hello", sender="external"), outer)while not response.done():- await router.process_next()+ await runtime.process_next()print(await response)diff --git a/examples/orchestrator.py b/examples/orchestrator.pyindex ab31f8cd9..8eb8bf011 100644--- a/examples/orchestrator.py+++ b/examples/orchestrator.py@@ -140,9 +140,9 @@ def software_development(runtime: AgentRuntime) -> OrchestratorChat: # type: ig"OrchestratorChat","A software development team.",runtime,- orchestrator=orchestrator,- planner=planner,- specialists=[developer, product_manager, tester],+ orchestrator=orchestrator.id,+ planner=planner.id,+ specialists=[developer.id, product_manager.id, tester.id],)diff --git a/examples/software_consultancy.py b/examples/software_consultancy.pyindex ae33e039f..2044f743a 100644--- a/examples/software_consultancy.py+++ b/examples/software_consultancy.py@@ -230,7 +230,7 @@ def software_consultancy(runtime: AgentRuntime, user_agent: Agent) -> None: # truntime=runtime,memory=HeadAndTailChatMemory(head_size=1, tail_size=10),# model_client=OpenAI(model="gpt-4-turbo"),- participants=[developer, product_manager, ux_designer, illustrator, user_agent],+ participants=[developer.id, product_manager.id, ux_designer.id, illustrator.id, user_agent.id],)diff --git a/src/agnext/application/_single_threaded_agent_runtime.py b/src/agnext/application/_single_threaded_agent_runtime.pyindex 9dcbc7e7b..455690b4d 100644--- a/src/agnext/application/_single_threaded_agent_runtime.py+++ b/src/agnext/application/_single_threaded_agent_runtime.py@@ -5,7 +5,7 @@ from collections.abc import Sequencefrom dataclasses import dataclassfrom typing import Any, Awaitable, Dict, List, Mapping, Set-from ..core import Agent, AgentMetadata, AgentRuntime, CancellationToken+from ..core import Agent, AgentId, AgentMetadata, AgentRuntime, CancellationTokenfrom ..core.exceptions import MessageDroppedExceptionfrom ..core.intervention import DropMessage, InterventionHandler@@ -77,18 +77,14 @@ class SingleThreadedAgentRuntime(AgentRuntime):def send_message(self,message: Any,- recipient: Agent,+ recipient: Agent | AgentId,*,- sender: Agent | None = None,+ sender: Agent | AgentId | None = None,cancellation_token: CancellationToken | None = None,) -> Future[Any | None]:if cancellation_token is None:cancellation_token = CancellationToken()- logger.info(- f"Sending message of type {type(message).__name__} to {recipient.metadata['name']}: {message.__dict__}"- )-# event_logger.info(# MessageEvent(# payload=message,@@ -99,6 +95,14 @@ class SingleThreadedAgentRuntime(AgentRuntime):# )# )+ recipient = self._get_agent(recipient)+ if sender is not None:+ sender = self._get_agent(sender)++ logger.info(+ f"Sending message of type {type(message).__name__} to {recipient.metadata['name']}: {message.__dict__}"+ )+future = asyncio.get_event_loop().create_future()if recipient not in self._agents:future.set_exception(Exception("Recipient not found"))@@ -119,12 +123,15 @@ class SingleThreadedAgentRuntime(AgentRuntime):self,message: Any,*,- sender: Agent | None = None,+ sender: Agent | AgentId | None = None,cancellation_token: CancellationToken | None = None,) -> Future[None]:if cancellation_token is None:cancellation_token = CancellationToken()+ if sender is not None:+ sender = self._get_agent(sender)+logger.info(f"Publishing message of type {type(message).__name__} to all subscribers: {message.__dict__}")# event_logger.info(@@ -300,11 +307,21 @@ class SingleThreadedAgentRuntime(AgentRuntime):# Yield control to the message loop to allow other tasks to runawait asyncio.sleep(0)- def agent_metadata(self, agent: Agent) -> AgentMetadata:- return agent.metadata+ def agent_metadata(self, agent: Agent | AgentId) -> AgentMetadata:+ return self._get_agent(agent).metadata++ def agent_save_state(self, agent: Agent | AgentId) -> Mapping[str, Any]:+ return self._get_agent(agent).save_state()- def agent_save_state(self, agent: Agent) -> Mapping[str, Any]:- return agent.save_state()+ def agent_load_state(self, agent: Agent | AgentId, state: Mapping[str, Any]) -> None:+ self._get_agent(agent).load_state(state)++ def _get_agent(self, agent_or_id: Agent | AgentId) -> Agent:+ if isinstance(agent_or_id, Agent):+ return agent_or_id++ for agent in self._agents:+ if agent.metadata["name"] == agent_or_id.name:+ return agent- def agent_load_state(self, agent: Agent, state: Mapping[str, Any]) -> None:- agent.load_state(state)+ raise ValueError(f"Agent with name {agent_or_id} not found")diff --git a/src/agnext/chat/agents/chat_completion_agent.py b/src/agnext/chat/agents/chat_completion_agent.pyindex e9cd9e806..d602990ec 100644--- a/src/agnext/chat/agents/chat_completion_agent.py+++ b/src/agnext/chat/agents/chat_completion_agent.py@@ -186,7 +186,7 @@ class ChatCompletionAgent(TypeRoutedAgent):# Send a function call message to itself.response = await self._send_message(message=FunctionCallMessage(content=response.content, source=self.metadata["name"]),- recipient=self,+ recipient=self.id,cancellation_token=cancellation_token,)# Make an assistant message from the response.@@ -232,7 +232,7 @@ class ChatCompletionAgent(TypeRoutedAgent):)approval_response = await self._send_message(message=approval_request,- recipient=self._tool_approver,+ recipient=self._tool_approver.id,cancellation_token=cancellation_token,)if not isinstance(approval_response, ToolApprovalResponse):diff --git a/src/agnext/chat/patterns/group_chat.py b/src/agnext/chat/patterns/group_chat.pyindex 70d086c0d..db8703192 100644--- a/src/agnext/chat/patterns/group_chat.py+++ b/src/agnext/chat/patterns/group_chat.py@@ -1,7 +1,7 @@from typing import Any, List, Protocol, Sequencefrom ...components import TypeRoutedAgent, message_handler-from ...core import Agent, AgentRuntime, CancellationToken+from ...core import AgentId, AgentRuntime, CancellationTokenfrom ..types import Reset, RespondNow, TextMessage@@ -19,7 +19,7 @@ class GroupChat(TypeRoutedAgent):name: str,description: str,runtime: AgentRuntime,- participants: Sequence[Agent],+ participants: Sequence[AgentId],num_rounds: int,output: GroupChatOutput,) -> None:diff --git a/src/agnext/chat/patterns/group_chat_manager.py b/src/agnext/chat/patterns/group_chat_manager.pyindex caed484fc..3302ceec7 100644--- a/src/agnext/chat/patterns/group_chat_manager.py+++ b/src/agnext/chat/patterns/group_chat_manager.py@@ -2,7 +2,7 @@ from typing import Any, Callable, List, Mappingfrom ...components import TypeRoutedAgent, message_handlerfrom ...components.models import ChatCompletionClient-from ...core import Agent, AgentRuntime, CancellationToken+from ...core import AgentId, AgentProxy, AgentRuntime, CancellationTokenfrom ..memory import ChatMemoryfrom ..types import (PublishNow,@@ -40,29 +40,31 @@ class GroupChatManager(TypeRoutedAgent):name: str,description: str,runtime: AgentRuntime,- participants: List[Agent],+ participants: List[AgentId],memory: ChatMemory,model_client: ChatCompletionClient | None = None,termination_word: str = "TERMINATE",- transitions: Mapping[Agent, List[Agent]] = {},+ transitions: Mapping[AgentId, List[AgentId]] = {},on_message_received: Callable[[TextMessage], None] | None = None,):super().__init__(name, description, runtime)self._memory = memoryself._client = model_client- self._participants = participants+ self._participants = [AgentProxy(x, runtime) for x in participants]self._termination_word = termination_wordfor key, value in transitions.items():+ proxy = AgentProxy(key, runtime)if not value:# Make sure no empty transitions are provided.- raise ValueError(f"Empty transition list provided for {key.metadata['name']}.")- if key not in participants:+ raise ValueError(f"Empty transition list provided for {proxy.metadata['name']}.")+ if proxy.id not in participants:# Make sure all keys are in the list of participants.- raise ValueError(f"Transition key {key.metadata['name']} not found in participants.")+ raise ValueError(f"Transition key {proxy.metadata['name']} not found in participants.")for v in value:- if v not in participants:+ proxy = AgentProxy(v, runtime)+ if proxy.id not in participants:# Make sure all values are in the list of participants.- raise ValueError(f"Transition value {v.metadata['name']} not found in participants.")+ raise ValueError(f"Transition value {proxy.metadata['name']} not found in participants.")self._tranistiions = transitionsself._on_message_received = on_message_received@@ -107,15 +109,15 @@ class GroupChatManager(TypeRoutedAgent):candidates = self._participantsif last_speaker_index is not None:last_speaker = self._participants[last_speaker_index]- if self._tranistiions.get(last_speaker) is not None:- candidates = self._tranistiions[last_speaker]+ if self._tranistiions.get(last_speaker.id) is not None:+ candidates = [AgentProxy(x, self._runtime) for x in self._tranistiions[last_speaker.id]]if len(candidates) == 1:speaker = candidates[0]else:speaker = await select_speaker(self._memory, self._client, candidates)# Send the message to the selected speaker to ask it to publish a response.- await self._send_message(PublishNow(), speaker)+ await self._send_message(PublishNow(), speaker.id)def save_state(self) -> Mapping[str, Any]:return {diff --git a/src/agnext/chat/patterns/group_chat_utils.py b/src/agnext/chat/patterns/group_chat_utils.pyindex fca967835..d480a2a89 100644--- a/src/agnext/chat/patterns/group_chat_utils.py+++ b/src/agnext/chat/patterns/group_chat_utils.py@@ -4,12 +4,12 @@ import refrom typing import Dict, Listfrom ...components.models import ChatCompletionClient, SystemMessage-from ...core import Agent+from ...core import AgentProxyfrom ..memory import ChatMemoryfrom ..types import TextMessage-async def select_speaker(memory: ChatMemory, client: ChatCompletionClient, agents: List[Agent]) -> Agent:+async def select_speaker(memory: ChatMemory, client: ChatCompletionClient, agents: List[AgentProxy]) -> AgentProxy:"""Selects the next speaker in a group chat using a ChatCompletion client."""# TODO: Handle multi-modal messages.@@ -47,7 +47,7 @@ Read the above conversation. Then select the next role from {participants} to plreturn agent-def mentioned_agents(message_content: str, agents: List[Agent]) -> Dict[str, int]:+def mentioned_agents(message_content: str, agents: List[AgentProxy]) -> Dict[str, int]:"""Counts the number of times each agent is mentioned in the provided message content.Agent names will match under any of the following conditions (all case-sensitive):- Exact name matchdiff --git a/src/agnext/chat/patterns/orchestrator_chat.py b/src/agnext/chat/patterns/orchestrator_chat.pyindex 95c90f16a..3ecc4d369 100644--- a/src/agnext/chat/patterns/orchestrator_chat.py+++ b/src/agnext/chat/patterns/orchestrator_chat.py@@ -2,7 +2,7 @@ import jsonfrom typing import Any, Sequence, Tuplefrom ...components import TypeRoutedAgent, message_handler-from ...core import Agent, AgentRuntime, CancellationToken+from ...core import AgentId, AgentProxy, AgentRuntime, CancellationTokenfrom ..types import Reset, RespondNow, ResponseFormat, TextMessage__all__ = ["OrchestratorChat"]@@ -14,17 +14,17 @@ class OrchestratorChat(TypeRoutedAgent):name: str,description: str,runtime: AgentRuntime,- orchestrator: Agent,- planner: Agent,- specialists: Sequence[Agent],+ orchestrator: AgentId,+ planner: AgentId,+ specialists: Sequence[AgentId],max_turns: int = 30,max_stalled_turns_before_retry: int = 2,max_retry_attempts: int = 1,) -> None:super().__init__(name, description, runtime)- self._orchestrator = orchestrator- self._planner = planner- self._specialists = specialists+ self._orchestrator = AgentProxy(orchestrator, runtime)+ self._planner = AgentProxy(planner, runtime)+ self._specialists = [AgentProxy(x, runtime) for x in specialists]self._max_turns = max_turnsself._max_stalled_turns_before_retry = max_stalled_turns_before_retryself._max_retry_attempts_before_educated_guess = max_retry_attempts@@ -55,7 +55,7 @@ class OrchestratorChat(TypeRoutedAgent):while total_turns < self._max_turns:# Reset all agents.for agent in [*self._specialists, self._orchestrator]:- await self._send_message(Reset(), agent)+ await self._send_message(Reset(), agent.id)# Create the task specs.task_specs = f"""@@ -77,7 +77,7 @@ Some additional points to consider:# Send the task specs to the orchestrator and specialists.for agent in [*self._specialists, self._orchestrator]:- await self._send_message(TextMessage(content=task_specs, source=self.metadata["name"]), agent)+ await self._send_message(TextMessage(content=task_specs, source=self.metadata["name"]), agent.id)# Inner loop.stalled_turns = 0@@ -133,7 +133,7 @@ Some additional points to consider:for agent in [*self._specialists, self._orchestrator]:_ = await self._send_message(TextMessage(content=subtask, source=self.metadata["name"]),- agent,+ agent.id,)# Find the speaker.@@ -145,7 +145,7 @@ Some additional points to consider:raise ValueError(f"Invalid next speaker: {data['next_speaker']['answer']}") from e# Ask speaker to speak.- speaker_response = await self._send_message(RespondNow(), speaker)+ speaker_response = await self._send_message(RespondNow(), speaker.id)assert speaker_response is not None# Update all other agents with the speaker's response.@@ -155,7 +155,7 @@ Some additional points to consider:content=speaker_response.content,source=speaker_response.source,),- agent,+ agent.id,)# Increment the total turns.@@ -168,7 +168,7 @@ Some additional points to consider:async def _prepare_task(self, task: str, sender: str) -> Tuple[str, str, str, str]:# Reset planner.- await self._send_message(Reset(), self._planner)+ await self._send_message(Reset(), self._planner.id)# A reusable description of the team.team = "\n".join([agent.metadata["name"] + ": " + agent.metadata["description"] for agent in self._specialists])@@ -203,8 +203,8 @@ When answering this survey, keep in mind that "facts" will typically be specific""".strip()# Ask the planner to obtain prior knowledge about facts.- await self._send_message(TextMessage(content=closed_book_prompt, source=sender), self._planner)- facts_response = await self._send_message(RespondNow(), self._planner)+ await self._send_message(TextMessage(content=closed_book_prompt, source=sender), self._planner.id)+ facts_response = await self._send_message(RespondNow(), self._planner.id)facts = str(facts_response.content)@@ -216,8 +216,8 @@ When answering this survey, keep in mind that "facts" will typically be specificBased on the team composition, and known and unknown facts, please devise a short bullet-point plan for addressing the original request. Remember, there is no requirement to involve all team members -- a team member's particular expertise may not be needed for this task.""".strip()# Send second messag eto the planner.- await self._send_message(TextMessage(content=plan_prompt, source=sender), self._planner)- plan_response = await self._send_message(RespondNow(), self._planner)+ await self._send_message(TextMessage(content=plan_prompt, source=sender), self._planner.id)+ plan_response = await self._send_message(RespondNow(), self._planner.id)plan = str(plan_response.content)return team, names, facts, plan@@ -269,11 +269,11 @@ Please output an answer in pure JSON format according to the following schema. Trequest = step_promptwhile True:# Send a message to the orchestrator.- await self._send_message(TextMessage(content=request, source=sender), self._orchestrator)+ await self._send_message(TextMessage(content=request, source=sender), self._orchestrator.id)# Request a response.step_response = await self._send_message(RespondNow(response_format=ResponseFormat.json_object),- self._orchestrator,+ self._orchestrator.id,)# TODO: use typed dictionary.try:@@ -332,9 +332,9 @@ Please output an answer in pure JSON format according to the following schema. T{facts}""".strip()# Send a message to the orchestrator.- await self._send_message(TextMessage(content=new_facts_prompt, source=sender), self._orchestrator)+ await self._send_message(TextMessage(content=new_facts_prompt, source=sender), self._orchestrator.id)# Request a response.- new_facts_response = await self._send_message(RespondNow(), self._orchestrator)+ new_facts_response = await self._send_message(RespondNow(), self._orchestrator.id)return str(new_facts_response.content)async def _educated_guess(self, facts: str, sender: str) -> Any:@@ -359,12 +359,12 @@ Please output an answer in pure JSON format according to the following schema. T# Send a message to the orchestrator.await self._send_message(TextMessage(content=request, source=sender),- self._orchestrator,+ self._orchestrator.id,)# Request a response.response = await self._send_message(RespondNow(response_format=ResponseFormat.json_object),- self._orchestrator,+ self._orchestrator.id,)try:result = json.loads(str(response.content))@@ -391,7 +391,7 @@ Team membership:{team}""".strip()# Send a message to the orchestrator.- await self._send_message(TextMessage(content=new_plan_prompt, source=sender), self._orchestrator)+ await self._send_message(TextMessage(content=new_plan_prompt, source=sender), self._orchestrator.id)# Request a response.- new_plan_response = await self._send_message(RespondNow(), self._orchestrator)+ new_plan_response = await self._send_message(RespondNow(), self._orchestrator.id)return str(new_plan_response.content)diff --git a/src/agnext/chat/patterns/two_agent_chat.py b/src/agnext/chat/patterns/two_agent_chat.pyindex 69cf54648..20aa6eaaa 100644--- a/src/agnext/chat/patterns/two_agent_chat.py+++ b/src/agnext/chat/patterns/two_agent_chat.py@@ -1,4 +1,4 @@-from ...core import Agent, AgentRuntime+from ...core import AgentId, AgentRuntimefrom .group_chat import GroupChat, GroupChatOutput@@ -10,8 +10,8 @@ class TwoAgentChat(GroupChat):name: str,description: str,runtime: AgentRuntime,- first_speaker: Agent,- second_speaker: Agent,+ first_speaker: AgentId,+ second_speaker: AgentId,num_rounds: int,output: GroupChatOutput,) -> None:diff --git a/src/agnext/core/__init__.py b/src/agnext/core/__init__.pyindex 01b3d3456..37cd231a5 100644--- a/src/agnext/core/__init__.py+++ b/src/agnext/core/__init__.py@@ -6,8 +6,18 @@ from ._agent import Agentfrom ._agent_id import AgentIdfrom ._agent_metadata import AgentMetadatafrom ._agent_props import AgentChildren+from ._agent_proxy import AgentProxyfrom ._agent_runtime import AgentRuntimefrom ._base_agent import BaseAgentfrom ._cancellation_token import CancellationToken-__all__ = ["Agent", "AgentId", "AgentMetadata", "AgentRuntime", "BaseAgent", "CancellationToken", "AgentChildren"]+__all__ = [+ "Agent",+ "AgentId",+ "AgentProxy",+ "AgentMetadata",+ "AgentRuntime",+ "BaseAgent",+ "CancellationToken",+ "AgentChildren",+]diff --git a/src/agnext/core/_agent.py b/src/agnext/core/_agent.pyindex 39caa9acb..e4068f95b 100644--- a/src/agnext/core/_agent.py+++ b/src/agnext/core/_agent.py@@ -1,5 +1,6 @@from typing import Any, Mapping, Protocol, runtime_checkable+from ._agent_id import AgentIdfrom ._agent_metadata import AgentMetadatafrom ._cancellation_token import CancellationToken@@ -11,6 +12,11 @@ class Agent(Protocol):"""Metadata of the agent."""...+ @property+ def id(self) -> AgentId:+ """ID of the agent."""+ ...+async def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any:"""Message handler for the agent. This should only be called by the runtime, not by other agents.diff --git a/src/agnext/core/_agent_proxy.py b/src/agnext/core/_agent_proxy.pyindex 78cefdce3..aee414336 100644--- a/src/agnext/core/_agent_proxy.py+++ b/src/agnext/core/_agent_proxy.py@@ -9,7 +9,7 @@ from ._cancellation_token import CancellationTokenclass AgentProxy:- def __init__(self, agent: Agent, runtime: AgentRuntime):+ def __init__(self, agent: Agent | AgentId, runtime: AgentRuntime):self._agent = agentself._runtime = runtimediff --git a/src/agnext/core/_agent_runtime.py b/src/agnext/core/_agent_runtime.pyindex 964ed2416..acba09c7d 100644--- a/src/agnext/core/_agent_runtime.py+++ b/src/agnext/core/_agent_runtime.py@@ -2,6 +2,7 @@ from asyncio import Futurefrom typing import Any, Mapping, Protocolfrom ._agent import Agent+from ._agent_id import AgentIdfrom ._agent_metadata import AgentMetadatafrom ._cancellation_token import CancellationToken@@ -24,9 +25,9 @@ class AgentRuntime(Protocol):def send_message(self,message: Any,- recipient: Agent,+ recipient: Agent | AgentId,*,- sender: Agent | None = None,+ sender: Agent | AgentId | None = None,cancellation_token: CancellationToken | None = None,) -> Future[Any]: ...@@ -35,7 +36,7 @@ class AgentRuntime(Protocol):self,message: Any,*,- sender: Agent | None = None,+ sender: Agent | AgentId | None = None,cancellation_token: CancellationToken | None = None,) -> Future[None]: ...@@ -43,8 +44,8 @@ class AgentRuntime(Protocol):def load_state(self, state: Mapping[str, Any]) -> None: ...- def agent_metadata(self, agent: Agent) -> AgentMetadata: ...+ def agent_metadata(self, agent: Agent | AgentId) -> AgentMetadata: ...- def agent_save_state(self, agent: Agent) -> Mapping[str, Any]: ...+ def agent_save_state(self, agent: Agent | AgentId) -> Mapping[str, Any]: ...- def agent_load_state(self, agent: Agent, state: Mapping[str, Any]) -> None: ...+ def agent_load_state(self, agent: Agent | AgentId, state: Mapping[str, Any]) -> None: ...diff --git a/src/agnext/core/_base_agent.py b/src/agnext/core/_base_agent.pyindex 939b0313d..313d37dbb 100644--- a/src/agnext/core/_base_agent.py+++ b/src/agnext/core/_base_agent.py@@ -1,25 +1,20 @@import warningsfrom abc import ABC, abstractmethodfrom asyncio import Future-from typing import Any, Mapping, Sequence, TypeVar+from typing import Any, Mapping, Sequencefrom ._agent import Agent+from ._agent_id import AgentIdfrom ._agent_metadata import AgentMetadatafrom ._agent_runtime import AgentRuntimefrom ._cancellation_token import CancellationToken-ConsumesT = TypeVar("ConsumesT")-ProducesT = TypeVar("ProducesT", covariant=True)--OtherConsumesT = TypeVar("OtherConsumesT")-OtherProducesT = TypeVar("OtherProducesT")-class BaseAgent(ABC, Agent):def __init__(self, name: str, description: str, subscriptions: Sequence[type], router: AgentRuntime) -> None:self._name = nameself._description = description- self._router = router+ self._runtime = routerself._subscriptions = subscriptionsrouter.add_agent(self)@@ -31,6 +26,10 @@ class BaseAgent(ABC, Agent):subscriptions=self._subscriptions,)+ @property+ def id(self) -> AgentId:+ return AgentId(self._name, namespace="")+@abstractmethodasync def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any: ...@@ -38,14 +37,14 @@ class BaseAgent(ABC, Agent):def _send_message(self,message: Any,- recipient: Agent,+ recipient: AgentId,*,cancellation_token: CancellationToken | None = None,) -> Future[Any]:if cancellation_token is None:cancellation_token = CancellationToken()- future = self._router.send_message(+ future = self._runtime.send_message(message,sender=self,recipient=recipient,@@ -62,7 +61,7 @@ class BaseAgent(ABC, Agent):) -> Future[None]:if cancellation_token is None:cancellation_token = CancellationToken()- future = self._router.publish_message(message, sender=self, cancellation_token=cancellation_token)+ future = self._runtime.publish_message(message, sender=self, cancellation_token=cancellation_token)return futuredef save_state(self) -> Mapping[str, Any]:diff --git a/tests/test_cancellation.py b/tests/test_cancellation.pyindex feb928ef6..1c0a72d66 100644--- a/tests/test_cancellation.py+++ b/tests/test_cancellation.py@@ -4,7 +4,7 @@ from dataclasses import dataclassimport pytestfrom agnext.application import SingleThreadedAgentRuntimefrom agnext.components import TypeRoutedAgent, message_handler-from agnext.core import Agent, AgentRuntime, CancellationToken+from agnext.core import AgentId, AgentRuntime, CancellationToken@dataclass@@ -34,7 +34,7 @@ class LongRunningAgent(TypeRoutedAgent): # type: ignoreraiseclass NestingLongRunningAgent(TypeRoutedAgent): # type: ignore- def __init__(self, name: str, router: AgentRuntime, nested_agent: Agent) -> None: # type: ignore+ def __init__(self, name: str, router: AgentRuntime, nested_agent: AgentId) -> None: # type: ignoresuper().__init__(name, "A nesting long running agent", router)self.called = Falseself.cancelled = False@@ -79,7 +79,7 @@ async def test_nested_cancellation_only_outer_called() -> None:router = SingleThreadedAgentRuntime()long_running = LongRunningAgent("name", router)- nested = NestingLongRunningAgent("nested", router, long_running)+ nested = NestingLongRunningAgent("nested", router, long_running.id)token = CancellationToken()response = router.send_message(MessageType(), nested, cancellation_token=token)@@ -102,7 +102,7 @@ async def test_nested_cancellation_inner_called() -> None:router = SingleThreadedAgentRuntime()long_running = LongRunningAgent("name", router)- nested = NestingLongRunningAgent("nested", router, long_running)+ nested = NestingLongRunningAgent("nested", router, long_running.id)token = CancellationToken()response = router.send_message(MessageType(), nested, cancellation_token=token)