当前位置: 首页 > article >正文

Autogen_core源码:_agent.py

目录

    • _agent.py代码
    • 代码解释
      • 导入模块
      • 定义 `Agent` 协议
      • 定义属性
      • 定义方法
        • `on_message` 方法
        • `save_state` 方法
        • `load_state` 方法
        • `close` 方法
      • 总结
    • 代码示例
      • 示例 1:实现 `Agent` 协议的简单类
      • 示例 2:检查对象是否实现 `Agent` 协议

_agent.py代码

from typing import Any, Mapping, Protocol, runtime_checkable

from ._agent_id import AgentId
from ._agent_metadata import AgentMetadata
from ._message_context import MessageContext


@runtime_checkable
class Agent(Protocol):
    @property
    def metadata(self) -> AgentMetadata:
        """Metadata of the agent."""
        ...

    @property
    def id(self) -> AgentId:
        """ID of the agent."""
        ...

    async def on_message(self, message: Any, ctx: MessageContext) -> Any:
        """Message handler for the agent. This should only be called by the runtime, not by other agents.

        Args:
            message (Any): Received message. Type is one of the types in `subscriptions`.
            ctx (MessageContext): Context of the message.

        Returns:
            Any: Response to the message. Can be None.

        Raises:
            asyncio.CancelledError: If the message was cancelled.
            CantHandleException: If the agent cannot handle the message.
        """
        ...

    async def save_state(self) -> Mapping[str, Any]:
        """Save the state of the agent. The result must be JSON serializable."""
        ...

    async def load_state(self, state: Mapping[str, Any]) -> None:
        """Load in the state of the agent obtained from `save_state`.

        Args:
            state (Mapping[str, Any]): State of the agent. Must be JSON serializable.
        """

        ...

    async def close(self) -> None:
        """Called when the runtime is closed"""
        ...

代码解释

这段代码定义了一个名为 Agent 的协议(Protocol),协议在 Python 中用于定义接口规范,它描述了一个对象应该具备的属性和方法,但不提供具体的实现。下面详细解释代码逻辑和功能:

导入模块

from typing import Any, Mapping, Protocol, runtime_checkable

from._agent_id import AgentId
from._agent_metadata import AgentMetadata
from._message_context import MessageContext
  • typing 模块中的 Any 表示任意类型,Mapping 表示映射类型(如字典),Protocol 用于定义协议,runtime_checkable 装饰器允许在运行时检查一个对象是否实现了该协议。
  • . 包中导入 AgentIdAgentMetadataMessageContext 类,这些类可能用于表示代理的 ID、元数据和消息上下文。

定义 Agent 协议

@runtime_checkable
class Agent(Protocol):
  • @runtime_checkable 装饰器使得可以在运行时使用 isinstance() 函数来检查一个对象是否实现了 Agent 协议。
  • Agent 类继承自 Protocol,表示这是一个协议类。

定义属性

    @property
    def metadata(self) -> AgentMetadata:
        """Metadata of the agent."""
       ...

    @property
    def id(self) -> AgentId:
        """ID of the agent."""
       ...
  • metadata 属性:返回一个 AgentMetadata 类型的对象,表示代理的元数据。
  • id 属性:返回一个 AgentId 类型的对象,表示代理的 ID。

定义方法

on_message 方法
    async def on_message(self, message: Any, ctx: MessageContext) -> Any:
        """Message handler for the agent. This should only be called by the runtime, not by other agents.

        Args:
            message (Any): Received message. Type is one of the types in `subscriptions`.
            ctx (MessageContext): Context of the message.

        Returns:
            Any: Response to the message. Can be None.

        Raises:
            asyncio.CancelledError: If the message was cancelled.
            CantHandleException: If the agent cannot handle the message.
        """
       ...
  • 这是一个异步方法,用于处理接收到的消息。
  • message 参数表示接收到的消息,类型可以是任意类型。
  • ctx 参数表示消息的上下文,类型为 MessageContext
  • 方法返回一个任意类型的对象,表示对消息的响应,也可以返回 None
  • 方法可能会抛出 asyncio.CancelledError 异常,表示消息被取消,还可能抛出 CantHandleException 异常,表示代理无法处理该消息。
save_state 方法
    async def save_state(self) -> Mapping[str, Any]:
        """Save the state of the agent. The result must be JSON serializable."""
       ...
  • 这是一个异步方法,用于保存代理的状态。
  • 方法返回一个映射类型的对象,键为字符串,值为任意类型,且该对象必须是 JSON 可序列化的。
load_state 方法
    async def load_state(self, state: Mapping[str, Any]) -> None:
        """Load in the state of the agent obtained from `save_state`.

        Args:
            state (Mapping[str, Any]): State of the agent. Must be JSON serializable.
        """
       ...
  • 这是一个异步方法,用于加载代理的状态。
  • state 参数是一个映射类型的对象,键为字符串,值为任意类型,且该对象必须是 JSON 可序列化的。
close 方法
    async def close(self) -> None:
        """Called when the runtime is closed"""
       ...
  • 这是一个异步方法,当运行时关闭时调用,用于执行一些清理操作。

总结

这段代码定义了一个 Agent 协议,描述了一个代理对象应该具备的属性和方法,包括代理的元数据、ID、消息处理、状态保存和加载以及关闭操作。任何实现了这些属性和方法的类都可以被视为一个 Agent 对象,并且可以使用 isinstance() 函数在运行时进行检查。这个协议可以作为其他代理类的接口规范,确保它们具备必要的功能。

代码示例

示例 1:实现 Agent 协议的简单类

import asyncio
from typing import Any, Mapping
from autogen_core import AgentId,AgentMetadata,MessageContext,CancellationToken,Agent

class CantHandleException(Exception):
    pass

class SimpleAgent:
    def __init__(self, agent_id: AgentId, metadata: AgentMetadata):
        self._id = agent_id
        self._metadata = metadata
        self._state = {}

    @property
    def metadata(self) -> AgentMetadata:
        return self._metadata

    @property
    def id(self) -> AgentId:
        return self._id

    async def on_message(self, message: Any, ctx: MessageContext) -> Any:
        try:
            # 简单示例,只是返回消息的字符串形式
            return str(message)
        except Exception:
            raise CantHandleException("Can't handle this message")

    async def save_state(self) -> Mapping[str, Any]:
        return self._state

    async def load_state(self, state: Mapping[str, Any]) -> None:
        self._state = state

    async def close(self) -> None:
        print(f"Agent {self._id} is closing.")




# 使用示例
if __name__ == "__main__":
    agent_id = AgentId("test_agent","default")
    metadata = AgentMetadata(type="Test Agent", key = "default", description="A simple test agent")
    agent = SimpleAgent(agent_id, metadata)

    message = {"key": "value"}
    ctx = MessageContext(sender=AgentId("sender_agent","default"), topic_id=None, is_rpc=False, message_id="", cancellation_token=CancellationToken())

    async def test_agent():
        response = await agent.on_message(message, ctx)
        print(f"Response: {response}")

        state = await agent.save_state()
        print(f"Saved state: {state}")

        new_state = {"new_key": "new_value"}
        await agent.load_state(new_state)
        print(f"Loaded state: {await agent.save_state()}")

        await agent.close()

    await test_agent()

Response: {'key': 'value'}
Saved state: {}
Loaded state: {'new_key': 'new_value'}
Agent test_agent/default is closing.

示例 2:检查对象是否实现 Agent 协议

class SimpleAgent:
    def __init__(self, agent_id: AgentId, metadata: AgentMetadata):
        self._id = agent_id
        self._metadata = metadata

    @property
    def metadata(self) -> AgentMetadata:
        return self._metadata

    @property
    def id(self) -> AgentId:
        return self._id

    async def on_message(self, message: Any, ctx: MessageContext) -> Any:
        return str(message)

    async def save_state(self) -> Mapping[str, Any]:
        return {}

    async def load_state(self, state: Mapping[str, Any]) -> None:
        pass

    async def close(self) -> None:
        pass


agent_id = AgentId("test_agent","default")
metadata = AgentMetadata(type="Test Agent", key = "default", description="A simple test agent")
agent = SimpleAgent(agent_id, metadata)

if isinstance(agent, Agent):
    print("The object implements the Agent protocol.")
else:
    print("The object does not implement the Agent protocol.")

The object implements the Agent protocol.

http://www.kler.cn/a/529261.html

相关文章:

  • 科技快讯 | OpenAI首次向免费用户开放推理模型;特朗普与黄仁勋会面;雷军回应“10后小学生深情表白小米SU7”
  • OpenAI o3-mini全面解析:最新免费推理模型重磅发布
  • C# 数组和列表的基本知识及 LINQ 查询
  • 网件r7000刷回原厂固件合集测评
  • 告别复杂,拥抱简洁:用plusDays(7)代替plus(7, ChronoUnit.DAYS)
  • 群晖搭建Gitea教程(使用系统自带的postgresql)
  • H3CNE-33-BGP
  • 【Rust自学】19.1. 摆脱安全性限制的unsafe Rust
  • “新月智能武器系统”CIWS,开启智能武器的新纪元
  • spring和Mybatis的逆向工程
  • 在5G网络中使用IEEE 1588实现保持时间同步
  • 2025开源DouyinLiveRecorder全平台直播间录制工具整合包,多直播同时录制、教学直播录制、教学视频推送、简单易用不占内存
  • FLTK - FLTK1.4.1 - demo - bitmap
  • Redis脑裂问题详解及解决方案
  • 十分钟快速上手 markdown
  • DRM系列四:初始化drm设备--drm_dev_init
  • Linux+Docer 容器化部署之 Shell 语法入门篇 【Shell基本运算符】
  • 深度学习之“向量范数和距离度量”
  • 【VMware】VMware安装ubuntu-22.04虚拟机
  • 一觉醒来全球编码能力下降100000倍,新手小白的我决定科普C语言——函数
  • Clock Controller of RH850/F1KH-D8, RH850/F1KM-S4, RH850/F1KM-S2
  • 15JavaWeb——Maven高级篇
  • 深入剖析 HTML5 新特性:语义化标签和表单控件完全指南
  • 78-《磨盘草》
  • 代码随想录算法训练营第四十一天-动态规划-股票-123.买卖股票的最佳时机III
  • 帝国CMS8.0终极栏目转换或批量改顺序成功后不能返回地址的解决方案