Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Activate deactivate agents #4800

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,9 @@ async def save_state(self) -> Mapping[str, Any]:
async def load_state(self, state: Mapping[str, Any]) -> None:
"""Restore agent from saved state. Default implementation for stateless agents."""
BaseState.model_validate(state)

async def activate(self) -> None:
pass

async def deactivate(self) -> None:
pass
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,11 @@ async def save_state(self) -> Mapping[str, Any]:
async def load_state(self, state: Mapping[str, Any]) -> None:
"""Restore agent from saved state"""
...

async def activate(self) -> None:
"""Lazily called the first time a runtime sends a message to this agent"""
...

async def deactivate(self) -> None:
"""Called when the runtime is stopped or any stop method is called"""
...
8 changes: 8 additions & 0 deletions python/packages/autogen-core/src/autogen_core/_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,11 @@ async def load_state(self, state: Mapping[str, Any]) -> None:
"""

...

async def activate(self) -> None:
"""Lazily called the first time a runtime sends a message to this agent"""
...

async def deactivate(self) -> None:
"""Called when the runtime is stopped or any stop method is called"""
...
6 changes: 6 additions & 0 deletions python/packages/autogen-core/src/autogen_core/_base_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ async def load_state(self, state: Mapping[str, Any]) -> None:
warnings.warn("load_state not implemented", stacklevel=2)
pass

async def activate(self) -> None:
pass

async def deactivate(self) -> None:
pass

@classmethod
async def register(
cls,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ def __init__(
str, Callable[[], Agent | Awaitable[Agent]] | Callable[[AgentRuntime, AgentId], Agent | Awaitable[Agent]]
] = {}
self._instantiated_agents: Dict[AgentId, Agent] = {}
self._activated_agents: set[AgentId] = set()
self._intervention_handlers = intervention_handlers
self._outstanding_tasks = Counter()
self._background_tasks: Set[Task[Any]] = set()
Expand Down Expand Up @@ -327,6 +328,11 @@ async def _process_send(self, message_envelope: SendMessageEnvelope) -> None:
# )
# )
recipient_agent = await self._get_agent(recipient)

if recipient not in self._activated_agents:
self._activated_agents.add(recipient)
await recipient_agent.activate()

message_context = MessageContext(
sender=message_envelope.sender,
topic_id=None,
Expand Down Expand Up @@ -396,6 +402,10 @@ async def _process_publish(self, message_envelope: PublishMessageEnvelope) -> No
)
agent = await self._get_agent(agent_id)

if agent_id not in self._activated_agents:
self._activated_agents.add(agent_id)
await agent.activate()

async def _on_message(agent: Agent, message_context: MessageContext) -> Any:
with self._tracer_helper.trace_block("process", agent.id, parent=None):
with MessageHandlerContext.populate_context(agent.id):
Expand Down Expand Up @@ -532,6 +542,13 @@ async def stop(self) -> None:
"""Stop the runtime message processing loop."""
if self._run_context is None:
raise RuntimeError("Runtime is not started")

# deactivate all the agents that have been activated
for agent_id in self._activated_agents:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Considering we just want shutdown, would be easier to just iterate _instantiated_agents here instead

agent = await self._get_agent(agent_id)
await agent.deactivate()
self._activated_agents.clear()

await self._run_context.stop()
self._run_context = None

Expand All @@ -541,13 +558,27 @@ async def stop_when_idle(self) -> None:
if self._run_context is None:
raise RuntimeError("Runtime is not started")
await self._run_context.stop_when_idle()

# deactivate all the agents that have been activated
for agent_id in self._activated_agents:
agent = await self._get_agent(agent_id)
await agent.deactivate()
self._activated_agents.clear()

self._run_context = None

async def stop_when(self, condition: Callable[[], bool]) -> None:
"""Stop the runtime message processing loop when the condition is met."""
if self._run_context is None:
raise RuntimeError("Runtime is not started")
await self._run_context.stop_when(condition)

# deactivate all the agents that have been activated
for agent_id in self._activated_agents:
agent = await self._get_agent(agent_id)
await agent.deactivate()
self._activated_agents.clear()

self._run_context = None

async def agent_metadata(self, agent: AgentId) -> AgentMetadata:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class MultimodalWebSurfer(BaseChatAgent):


When :meth:`on_messages` or :meth:`on_messages_stream` is called, the following occurs:
1) If this is the first call, the browser is initialized and the page is loaded. This is done in :meth:`_lazy_init`. The browser is only closed when :meth:`close` is called.
1) If this is the first call, the browser is initialized and the page is loaded. This is done in :meth:`_lazy_init`. The browser is only closed when :meth:`deactivate` is called.
2) The method :meth:`_generate_reply` is called, which then creates the final response as below.
3) The agent takes a screenshot of the page, extracts the interactive elements, and prepares a set-of-mark screenshot with bounding boxes around the interactive elements.
4) The agent makes a call to the :attr:`model_client` with the SOM screenshot, history of messages, and the list of available tools.
Expand Down Expand Up @@ -132,7 +132,7 @@ async def main() -> None:
stream = agent_team.run_stream(task="Navigate to the AutoGen readme on GitHub.")
await Console(stream)
# Close the browser controlled by the agent
await web_surfer_agent.close()
await web_surfer_agent.deactivate()


asyncio.run(main())
Expand Down Expand Up @@ -285,7 +285,7 @@ async def _lazy_init(
await self._set_debug_dir(self.debug_dir)
self.did_lazy_init = True

async def close(self) -> None:
async def deactivate(self) -> None:
"""
Close the browser and the page.
Should be called when the agent is no longer needed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ async def recv(self) -> agent_worker_pb2.Message:


class GrpcWorkerAgentRuntime(AgentRuntime):
# TODO: Needs to handle agent activate()/deactivate() calls
def __init__(
self,
host_address: str,
Expand Down
Loading