docs: document how to use agents

ref: N25B-300
This commit is contained in:
2025-11-21 13:28:37 +01:00
parent 1c510c661e
commit 98d087417f
3 changed files with 32 additions and 10 deletions

View File

@@ -9,6 +9,10 @@ _agent_directory: dict[str, "BaseAgent"] = {}
@dataclass
class InternalMessage:
"""
Represents a message to an agent.
"""
to: str
sender: str
body: str
@@ -16,6 +20,11 @@ class InternalMessage:
class AgentDirectory:
"""
Helper class to keep track of which agents are registered.
Used for handling message routing.
"""
@staticmethod
def register(name: str, agent: "BaseAgent"):
_agent_directory[name] = agent
@@ -26,6 +35,17 @@ class AgentDirectory:
class BaseAgent(ABC):
"""
Abstract base class for all agents. To make a new agent, inherit from
`control_backend.agents.BaseAgent`, not this class. That ensures that a
logger is present with the correct name pattern.
When subclassing, the `setup()` method needs to be overwritten. To handle
messages from other agents, overwrite the `handle_message()` method. To
send messages to other agents, use the `send()` method. To add custom
behaviors/tasks to the agent, use the `add_background_task()` method.
"""
logger: logging.Logger
def __init__(self, name: str):
@@ -39,7 +59,7 @@ class BaseAgent(ABC):
@abstractmethod
async def setup(self):
"""Override this to initialize resources."""
"""Overwrite this to initialize resources."""
pass
async def start(self):
@@ -59,6 +79,9 @@ class BaseAgent(ABC):
self.logger.info(f"Agent {self.name} stopped")
async def send(self, message: InternalMessage):
"""
Sends a message to another agent.
"""
target = AgentDirectory.get(message.to)
if target:
await target.inbox.put(message)
@@ -76,7 +99,7 @@ class BaseAgent(ABC):
raise NotImplementedError
async def add_background_task(self, coro):
"""Helper to run cyclic behaviors."""
"""Helper to add a behavior to the agent."""
task = asyncio.create_task(coro)
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)