autogen_core#
- class Agent(*args, **kwargs)[源代码]#
基类:
Protocol
- property metadata: AgentMetadata#
代理的元数据。
- async bind_id_and_runtime(id: AgentId, runtime: AgentRuntime) None [源代码]#
用于将Agent实例绑定到`AgentRuntime`的函数。
- 参数:
agent_id (AgentId) -- 代理的ID。
runtime (AgentRuntime) -- 要绑定代理的AgentRuntime实例。
- async on_message(message: Any, ctx: MessageContext) Any [源代码]#
代理的消息处理器。此方法应仅由运行时调用,而非其他代理。
- 参数:
message (Any) -- 接收到的消息。类型为`subscriptions`中的一种。
ctx (MessageContext) -- 消息上下文。
- Returns:
Any -- 对消息的响应。可为None。
- 抛出:
CancelledError -- 如果消息被取消。
CantHandleException -- 如果代理无法处理该消息。
- class AgentId(type: str | AgentType, key: str)[源代码]#
基类:
object
Agent ID 唯一标识一个代理运行时中的代理实例 - 包括分布式运行时。它是代理实例接收消息的'地址'。
更多信息请参见:Agent身份标识与生命周期
- class AgentProxy(agent: AgentId, runtime: AgentRuntime)[源代码]#
基类:
object
一个辅助类,允许你使用
AgentId
来代替其关联的Agent
- property metadata: Awaitable[AgentMetadata]#
该代理的元数据
- class AgentRuntime(*args, **kwargs)[源代码]#
基类:
Protocol
- async send_message(message: Any, recipient: AgentId, *, sender: AgentId | None = None, cancellation_token: CancellationToken | None = None, message_id: str | None = None) Any [源代码]#
向代理发送消息并获取响应。
- 参数:
message (Any) -- 要发送的消息。
recipient (AgentId) -- 接收消息的代理。
sender (AgentId | None, optional) -- 发送消息的代理。**仅**当消息不是由任何代理发送时(例如直接从外部发送到运行时)才应为None。默认为None。
cancellation_token (CancellationToken | None, optional) -- 用于取消进行中的操作的令牌。默认为None。
- 抛出:
CantHandleException -- 如果接收方无法处理该消息。
UndeliverableException -- 如果消息无法送达。
Other -- 接收方引发的任何其他异常。
- Returns:
Any -- 来自代理的响应。
- async publish_message(message: Any, topic_id: TopicId, *, sender: AgentId | None = None, cancellation_token: CancellationToken | None = None, message_id: str | None = None) None [源代码]#
向给定命名空间中的所有代理发布消息,如果未提供命名空间,则使用发送者的命名空间。
发布消息不期望获得响应。
- 参数:
message (Any) -- 要发布的消息。
topic_id (TopicId) -- 发布消息的主题。
sender (AgentId | None, optional) -- 发送消息的代理。默认为None。
cancellation_token (CancellationToken | None, optional) -- 用于取消进行中的操作的令牌。默认为None。
message_id (str | None, optional) -- 消息ID。如果为None,将生成新的消息ID。默认为None。此消息ID必须唯一,建议使用UUID。
- 抛出:
UndeliverableException -- 如果消息无法送达。
- async register_factory(type: str | AgentType, agent_factory: Callable[[], T | Awaitable[T]], *, expected_class: type[T] | None = None) AgentType [源代码]#
向运行时注册与特定类型关联的代理工厂。该类型必须唯一。此API不添加任何订阅。
备注
这是一个底层API,通常应使用代理类的`register`方法代替,因为该方法还会自动处理订阅。
示例:
from dataclasses import dataclass from autogen_core import AgentRuntime, MessageContext, RoutedAgent, event from autogen_core.models import UserMessage @dataclass class MyMessage: content: str class MyAgent(RoutedAgent): def __init__(self) -> None: super().__init__("My core agent") @event async def handler(self, message: UserMessage, context: MessageContext) -> None: print("Event received: ", message.content) async def my_agent_factory(): return MyAgent() async def main() -> None: runtime: AgentRuntime = ... # type: ignore await runtime.register_factory("my_agent", lambda: MyAgent()) import asyncio asyncio.run(main())
- async register_agent_instance(agent_instance: Agent, agent_id: AgentId) AgentId [源代码]#
向运行时注册一个代理实例。类型可以重复使用,但每个agent_id必须唯一。同一类型下的所有代理实例必须是相同的对象类型。此API不会添加任何订阅。
备注
这是一个底层API,通常应该使用代理类的`register_instance`方法,因为该方法还会自动处理订阅。
示例:
from dataclasses import dataclass from autogen_core import AgentId, AgentRuntime, MessageContext, RoutedAgent, event from autogen_core.models import UserMessage @dataclass class MyMessage: content: str class MyAgent(RoutedAgent): def __init__(self) -> None: super().__init__("My core agent") @event async def handler(self, message: UserMessage, context: MessageContext) -> None: print("Event received: ", message.content) async def main() -> None: runtime: AgentRuntime = ... # type: ignore agent = MyAgent() await runtime.register_agent_instance( agent_instance=agent, agent_id=AgentId(type="my_agent", key="default") ) import asyncio asyncio.run(main())
- async try_get_underlying_agent_instance(id: AgentId, type: Type[T] = Agent) T [源代码]#
尝试通过名称和命名空间获取底层代理实例。通常不推荐这样做(因此名称较长),但在某些情况下可能有用。
如果底层代理不可访问,将引发异常。
- 参数:
id (AgentId) -- 代理ID。
type (Type[T], optional) -- 代理的预期类型。默认为Agent。
- Returns:
T -- 具体的代理实例。
- 抛出:
LookupError -- 如果找不到代理。
NotAccessibleError -- 如果代理不可访问,例如位于远程。
TypeError -- 如果代理不是预期类型。
- async get(id: AgentId, /, *, lazy: bool = True) AgentId [源代码]#
- async get(type: AgentType | str, /, key: str = 'default', *, lazy: bool = True) AgentId
- async save_state() Mapping[str, Any] [源代码]#
保存整个运行时的状态,包括所有托管代理。恢复状态的唯一方法是将其传递给:meth:load_state。
状态的结构由实现定义,可以是任何JSON可序列化对象。
- Returns:
Mapping[str, Any] -- 保存的状态。
- async load_state(state: Mapping[str, Any]) None [源代码]#
加载整个运行时的状态,包括所有托管代理。该状态应与
save_state()
方法返回的状态一致。- 参数:
state (Mapping[str, Any]) -- 已保存的状态。
- async agent_metadata(agent: AgentId) AgentMetadata [源代码]#
获取代理的元数据。
- 参数:
agent (AgentId) -- 代理ID。
- Returns:
AgentMetadata -- 代理元数据。
- async agent_save_state(agent: AgentId) Mapping[str, Any] [源代码]#
保存单个代理的状态。
状态的结构由实现定义,可以是任何可JSON序列化的对象。
- 参数:
agent (AgentId) -- 代理ID。
- Returns:
Mapping[str, Any] -- 已保存的状态。
- async add_subscription(subscription: Subscription) None [源代码]#
添加运行时在处理发布消息时应满足的新订阅
- 参数:
subscription (Subscription) -- 要添加的订阅
- async remove_subscription(id: str) None [源代码]#
从运行时移除订阅
- 参数:
id (str) -- 要移除的订阅ID
- 抛出:
LookupError -- 如果订阅不存在
- add_message_serializer(serializer: MessageSerializer[Any] | Sequence[MessageSerializer[Any]]) None [源代码]#
向运行时添加新的消息序列化序列化器
注意:这将根据 type_name 和 data_content_type 属性对序列化器进行去重
- 参数:
serializer (MessageSerializer[Any] | Sequence[MessageSerializer[Any]]) -- 要添加的序列化器/序列化器列表
- class BaseAgent(description: str)[源代码]#
-
- property metadata: AgentMetadata#
代理的元数据。
- async bind_id_and_runtime(id: AgentId, runtime: AgentRuntime) None [源代码]#
用于将Agent实例绑定到`AgentRuntime`的函数。
- 参数:
agent_id (AgentId) -- 代理的ID。
runtime (AgentRuntime) -- 要绑定代理的AgentRuntime实例。
- property runtime: AgentRuntime#
- final async on_message(message: Any, ctx: MessageContext) Any [源代码]#
代理的消息处理器。此方法应仅由运行时调用,而非其他代理。
- 参数:
message (Any) -- 接收到的消息。类型为`subscriptions`中的一种。
ctx (MessageContext) -- 消息上下文。
- Returns:
Any -- 对消息的响应。可为None。
- 抛出:
CancelledError -- 如果消息被取消。
CantHandleException -- 如果代理无法处理该消息。
- abstract async on_message_impl(message: Any, ctx: MessageContext) Any [源代码]#
- async send_message(message: Any, recipient: AgentId, *, cancellation_token: CancellationToken | None = None, message_id: str | None = None) Any [源代码]#
- async publish_message(message: Any, topic_id: TopicId, *, cancellation_token: CancellationToken | None = None) None [源代码]#
- async load_state(state: Mapping[str, Any]) None [源代码]#
从`save_state`获取的代理状态进行加载。
- 参数:
state (Mapping[str, Any]) -- 代理的状态。必须是可JSON序列化的。
- async register_instance(runtime: AgentRuntime, agent_id: AgentId, *, skip_class_subscriptions: bool = True, skip_direct_message_subscription: bool = False) AgentId [源代码]#
此函数与 register 类似,但用于注册代理实例。会创建一个基于代理 ID 的订阅并将其添加到运行时中。
- async classmethod register(runtime: AgentRuntime, type: str, factory: Callable[[], Self | Awaitable[Self]], *, skip_class_subscriptions: bool = False, skip_direct_message_subscription: bool = False) AgentType [源代码]#
Register a virtual subclass of an ABC.
Returns the subclass, to allow usage as a class decorator.
- class CacheStore[源代码]#
基类:
ABC
,Generic
[T
],ComponentBase
[BaseModel
]该协议定义了存储/缓存操作的基本接口。
子类应处理底层存储的生命周期。
- component_type: ClassVar[ComponentType] = 'cache_store'#
组件的逻辑类型。
- class InMemoryStore[源代码]#
基类:
CacheStore
[T
],Component
[InMemoryStoreConfig
]- component_provider_override: ClassVar[str | None] = 'autogen_core.InMemoryStore'#
覆盖组件的provider字符串。这应该用于防止内部模块名称成为模块名称的一部分。
- component_config_schema#
InMemoryStoreConfig
的别名
- class AgentInstantiationContext[源代码]#
基类:
object
一个提供代理实例化上下文的静态类。
这个静态类可用于在代理实例化过程中(在工厂函数或代理的类构造函数内部) 访问当前运行时和代理ID。
示例:
在工厂函数和代理构造函数中获取当前运行时和代理ID:
import asyncio from dataclasses import dataclass from autogen_core import ( AgentId, AgentInstantiationContext, MessageContext, RoutedAgent, SingleThreadedAgentRuntime, message_handler, ) @dataclass class TestMessage: content: str class TestAgent(RoutedAgent): def __init__(self, description: str): super().__init__(description) # 获取当前运行时——这里不使用但它是可用的 _ = AgentInstantiationContext.current_runtime() # 获取当前代理ID agent_id = AgentInstantiationContext.current_agent_id() print(f"Current AgentID from constructor: {agent_id}") @message_handler async def handle_test_message(self, message: TestMessage, ctx: MessageContext) -> None: print(f"Received message: {message.content}") def test_agent_factory() -> TestAgent: # 获取当前运行时——这里不使用但它是可用的 _ = AgentInstantiationContext.current_runtime() # 获取当前代理ID agent_id = AgentInstantiationContext.current_agent_id() print(f"Current AgentID from factory: {agent_id}") return TestAgent(description="Test agent") async def main() -> None: # 创建SingleThreadedAgentRuntime实例 runtime = SingleThreadedAgentRuntime() # 启动运行时 runtime.start() # 用工厂函数注册代理类型 await runtime.register_factory("test_agent", test_agent_factory) # 向代理发送消息。运行时将实例化代理并调用消息处理器 await runtime.send_message(TestMessage(content="Hello, world!"), AgentId("test_agent", "default")) # 停止运行时 await runtime.stop() asyncio.run(main())
- classmethod current_runtime() AgentRuntime [源代码]#
- class TopicId(type: str, source: str)[源代码]#
基类:
object
TopicId 定义了广播消息的作用范围。本质上,代理运行时通过其广播 API 实现了发布-订阅模型:发布消息时必须指定主题。
更多信息请参阅:主题
- type: str#
此 topic_id 包含的事件类型。遵循云事件规范。
必须匹配模式:^[w-.:=]+Z
了解更多:cloudevents/spec
- source: str#
标识事件发生的上下文环境。遵循云事件规范。
了解更多:cloudevents/spec
- class Subscription(*args, **kwargs)[源代码]#
基类:
Protocol
订阅定义了代理感兴趣的主题。
- class MessageContext(sender: AgentId | None, topic_id: TopicId | None, is_rpc: bool, cancellation_token: CancellationToken, message_id: str)[源代码]#
基类:
object
- cancellation_token: CancellationToken#
- class Image(image: Image)[源代码]#
基类:
object
表示一个图像。
示例:
从URL加载图像:
from autogen_core import Image from PIL import Image as PILImage import aiohttp import asyncio async def from_url(url: str) -> Image: async with aiohttp.ClientSession() as session: async with session.get(url) as response: content = await response.read() return Image.from_pil(PILImage.open(content)) image = asyncio.run(from_url("https://example.com/image"))
- class RoutedAgent(description: str)[源代码]#
基类:
BaseAgent
一个基类,用于根据消息类型和可选匹配函数将消息路由到相应的处理程序。
要创建路由代理,请继承此类并添加消息处理方法,这些方法需使用
event()
或rpc()
装饰器进行装饰。示例:
from dataclasses import dataclass from autogen_core import MessageContext from autogen_core import RoutedAgent, event, rpc @dataclass class Message: pass @dataclass class MessageWithContent: content: str @dataclass class Response: pass class MyAgent(RoutedAgent): def __init__(self): super().__init__("MyAgent") @event async def handle_event_message(self, message: Message, ctx: MessageContext) -> None: assert ctx.topic_id is not None await self.publish_message(MessageWithContent("event handled"), ctx.topic_id) @rpc(match=lambda message, ctx: message.content == "special") # type: ignore async def handle_special_rpc_message(self, message: MessageWithContent, ctx: MessageContext) -> Response: return Response()
- async on_message_impl(message: Any, ctx: MessageContext) Any | None [源代码]#
通过将消息路由到适当的消息处理程序来处理消息。 不要在子类中重写此方法。相反,应添加使用
event()
或rpc()
装饰器装饰的消息处理方法。
- async on_unhandled_message(message: Any, ctx: MessageContext) None [源代码]#
当接收到没有匹配消息处理程序的消息时调用。 默认实现会记录一条信息日志。
- class ClosureAgent(description: str, closure: Callable[[ClosureContext, T, MessageContext], Awaitable[Any]], *, unknown_type_policy: Literal['error', 'warn', 'ignore'] = 'warn')[源代码]#
-
- property metadata: AgentMetadata#
代理的元数据。
- property runtime: AgentRuntime#
- async on_message_impl(message: Any, ctx: MessageContext) Any [源代码]#
- async classmethod register_closure(runtime: AgentRuntime, type: str, closure: Callable[[ClosureContext, T, MessageContext], Awaitable[Any]], *, unknown_type_policy: Literal['error', 'warn', 'ignore'] = 'warn', skip_direct_message_subscription: bool = False, description: str = '', subscriptions: Callable[[], list[Subscription] | Awaitable[list[Subscription]]] | None = None) AgentType [源代码]#
闭包代理允许您使用闭包或函数定义代理,而无需定义类。它可以从运行时中提取值。
闭包可以定义预期的消息类型,或使用`Any`来接受任何类型的消息。
示例:
import asyncio from autogen_core import SingleThreadedAgentRuntime, MessageContext, ClosureAgent, ClosureContext from dataclasses import dataclass from autogen_core._default_subscription import DefaultSubscription from autogen_core._default_topic import DefaultTopicId @dataclass class MyMessage: content: str async def main(): queue = asyncio.Queue[MyMessage]() async def output_result(_ctx: ClosureContext, message: MyMessage, ctx: MessageContext) -> None: await queue.put(message) runtime = SingleThreadedAgentRuntime() await ClosureAgent.register_closure( runtime, "output_result", output_result, subscriptions=lambda: [DefaultSubscription()] ) runtime.start() await runtime.publish_message(MyMessage("Hello, world!"), DefaultTopicId()) await runtime.stop_when_idle() result = await queue.get() print(result) asyncio.run(main())
- 参数:
runtime (AgentRuntime) -- 要注册代理的运行时
type (str) -- 注册代理的代理类型
closure (Callable[[ClosureContext, T, MessageContext], Awaitable[Any]]) -- 处理消息的闭包
unknown_type_policy (Literal["error", "warn", "ignore"], optional) -- 遇到与闭包类型不匹配的类型时的处理方式。默认为"warn"。
skip_direct_message_subscription (bool, optional) -- 不为该代理添加直接消息订阅。默认为False。
description (str, optional) -- 代理功能的描述。默认为""。
subscriptions (Callable[[], list[Subscription] | Awaitable[list[Subscription]]] | None, optional) -- 该闭包代理的订阅列表。默认为None。
- Returns:
AgentType -- 已注册代理的类型
- class ClosureContext(*args, **kwargs)[源代码]#
基类:
Protocol
- message_handler(func: None | Callable[[AgentT, ReceivesT, MessageContext], Coroutine[Any, Any, ProducesT]] = None, *, strict: bool = True, match: None | Callable[[ReceivesT, MessageContext], bool] = None) Callable[[Callable[[AgentT, ReceivesT, MessageContext], Coroutine[Any, Any, ProducesT]]], MessageHandler[AgentT, ReceivesT, ProducesT]] | MessageHandler[AgentT, ReceivesT, ProducesT] [源代码]#
通用消息处理器的装饰器。
将此装饰器添加到:class:`RoutedAgent`类中用于处理事件和RPC消息的方法上。 这些方法必须遵循特定的签名规范才能生效:
方法必须是`async`异步方法
方法必须使用`@message_handler`装饰器装饰
- 方法必须恰好有3个参数:
self
message: 要处理的消息,必须使用其目标处理的消息类型进行类型提示
ctx: 一个:class:`autogen_core.MessageContext`对象
方法必须类型提示其可能返回的响应消息类型,如果不返回任何内容则可以返回`None`
处理器可以通过接受消息类型的Union来处理多种消息类型。也可以通过返回消息类型的Union来返回多种消息类型。
- 参数:
func -- 要被装饰的函数
strict -- 如果为`True`,当消息类型或返回类型不在目标类型中时会抛出异常。如果为`False`,则只记录警告
match -- 一个接收消息和上下文作为参数并返回布尔值的函数。用于消息类型之后的二级路由。对于处理相同消息类型的处理器,匹配函数会按照处理器名称的字母顺序应用,第一个匹配的处理器会被调用,其余跳过。如果为`None`,则按字母顺序调用第一个匹配该消息类型的处理器。
- event(func: None | Callable[[AgentT, ReceivesT, MessageContext], Coroutine[Any, Any, None]] = None, *, strict: bool = True, match: None | Callable[[ReceivesT, MessageContext], bool] = None) Callable[[Callable[[AgentT, ReceivesT, MessageContext], Coroutine[Any, Any, None]]], MessageHandler[AgentT, ReceivesT, None]] | MessageHandler[AgentT, ReceivesT, None] [源代码]#
事件消息处理器的装饰器。
将此装饰器添加到:class:`RoutedAgent`类中用于处理事件消息的方法上。 这些方法必须遵循特定的签名规范才能生效:
方法必须是`async`异步方法
方法必须使用`@message_handler`装饰器装饰
- 方法必须恰好有3个参数:
self
message: 要处理的事件消息,必须使用其目标处理的消息类型进行类型提示
ctx: 一个:class:`autogen_core.MessageContext`对象
方法必须返回`None`
处理器可以通过接受消息类型的Union来处理多种消息类型。
- 参数:
func -- 要被装饰的函数
strict -- 如果为`True`,当消息类型不在目标类型中时会抛出异常。如果为`False`,则只记录警告
match -- 一个接收消息和上下文作为参数并返回布尔值的函数。用于消息类型之后的二级路由。对于处理相同消息类型的处理器,匹配函数会按照处理器名称的字母顺序应用,第一个匹配的处理器会被调用,其余跳过。如果为`None`,则按字母顺序调用第一个匹配该消息类型的处理器。
- rpc(func: None | Callable[[AgentT, ReceivesT, MessageContext], Coroutine[Any, Any, ProducesT]] = None, *, strict: bool = True, match: None | Callable[[ReceivesT, MessageContext], bool] = None) Callable[[Callable[[AgentT, ReceivesT, MessageContext], Coroutine[Any, Any, ProducesT]]], MessageHandler[AgentT, ReceivesT, ProducesT]] | MessageHandler[AgentT, ReceivesT, ProducesT] [源代码]#
RPC消息处理器的装饰器。
将此装饰器添加到:class:`RoutedAgent`类中用于处理RPC消息的方法上。 这些方法必须遵循特定的签名规范才能生效:
方法必须是`async`异步方法
方法必须使用`@message_handler`装饰器装饰
- 方法必须恰好有3个参数:
self
message: 要处理的消息,必须使用其目标处理的消息类型进行类型提示
ctx: 一个:class:`autogen_core.MessageContext`对象
方法必须类型提示其可能返回的响应消息类型,如果不返回任何内容则可以返回`None`
处理器可以通过接受消息类型的Union来处理多种消息类型。也可以通过返回消息类型的Union来返回多种消息类型。
- 参数:
func -- 要被装饰的函数
strict -- 如果为`True`,当消息类型或返回类型不在目标类型中时会抛出异常。如果为`False`,则只记录警告
match -- 一个接收消息和上下文作为参数并返回布尔值的函数。用于消息类型之后的二级路由。对于处理相同消息类型的处理器,匹配函数会按照处理器名称的字母顺序应用,第一个匹配的处理器会被调用,其余跳过。如果为`None`,则按字母顺序调用第一个匹配该消息类型的处理器。
- class TypeSubscription(topic_type: str, agent_type: str | AgentType, id: str | None = None)[源代码]#
基类:
Subscription
此订阅根据主题类型匹配主题,并使用主题来源作为代理键映射到代理。
此订阅使每个来源拥有自己的代理实例。
示例:
from autogen_core import TypeSubscription subscription = TypeSubscription(topic_type="t1", agent_type="a1")
在此情况下:
类型为`t1`且来源为`s1`的topic_id将由键为`s1`的`a1`类型代理处理
类型为`t1`且来源为`s2`的topic_id将由键为`s2`的`a1`类型代理处理
- class DefaultSubscription(topic_type: str = 'default', agent_type: str | AgentType | None = None)[源代码]#
-
默认订阅设计用于那些仅需要全局作用域代理的应用程序,是一个合理的默认选择。
该主题默认使用"default"主题类型,并尝试根据实例化上下文检测要使用的代理类型。
- class DefaultTopicId(type: str = 'default', source: str | None = None)[源代码]#
基类:
TopicId
DefaultTopicId 为 TopicId 的 topic_id 和 source 字段提供了一个合理的默认值。
如果在消息处理器的上下文中创建,source 将被设置为消息处理器的 agent_id,否则将被设置为 "default"。
- default_subscription(cls: Type[BaseAgentType] | None = None) Callable[[Type[BaseAgentType]], Type[BaseAgentType]] | Type[BaseAgentType] [源代码]#
- class TypePrefixSubscription(topic_type_prefix: str, agent_type: str | AgentType, id: str | None = None)[源代码]#
基类:
Subscription
此订阅基于类型的主题前缀进行匹配,并使用主题的源作为代理键映射到代理。
此订阅会导致每个源拥有自己的代理实例。
示例:
from autogen_core import TypePrefixSubscription subscription = TypePrefixSubscription(topic_type_prefix="t1", agent_type="a1")
在此情况下:
类型为`t1`且源为`s1`的topic_id将由键为`s1`的`a1`类型代理处理
类型为`t1`且源为`s2`的topic_id将由键为`s2`的`a1`类型代理处理
类型为`t1SUFFIX`且源为`s2`的topic_id将由键为`s2`的`a1`类型代理处理
- JSON_DATA_CONTENT_TYPE = 'application/json'#
JSON 数据的内容类型。
- PROTOBUF_DATA_CONTENT_TYPE = 'application/x-protobuf'#
Protobuf 数据的内容类型。
- class SingleThreadedAgentRuntime(*, intervention_handlers: List[InterventionHandler] | None = None, tracer_provider: TracerProvider | None = None, ignore_unhandled_exceptions: bool = True)[源代码]#
基类:
AgentRuntime
一个单线程代理运行时,使用单个 asyncio 队列处理所有消息。 消息按接收顺序传递,运行时在单独的 asyncio 任务中并发处理每条消息。
备注
此运行时适用于开发和独立应用程序。 不适合高吞吐量或高并发场景。
- 参数:
intervention_handlers (List[InterventionHandler], optional) -- 可以在消息发送或发布前拦截的干预处理程序列表。默认为 None。
tracer_provider (TracerProvider, optional) -- 用于追踪的追踪器提供者。默认为 None。
ignore_unhandled_exceptions (bool, optional) -- 是否忽略代理事件处理程序中发生的未处理异常。任何后台异常将在下次调用 process_next 或等待 stop、stop_when_idle 或 stop_when 时抛出。注意,这不适用于 RPC 处理程序。默认为 True。
示例
创建运行时、注册代理、发送消息并停止运行时的简单示例:
import asyncio from dataclasses import dataclass from autogen_core import AgentId, MessageContext, RoutedAgent, SingleThreadedAgentRuntime, message_handler @dataclass class MyMessage: content: str class MyAgent(RoutedAgent): @message_handler async def handle_my_message(self, message: MyMessage, ctx: MessageContext) -> None: print(f"Received message: {message.content}") async def main() -> None: # Create a runtime and register the agent runtime = SingleThreadedAgentRuntime() await MyAgent.register(runtime, "my_agent", lambda: MyAgent("My agent")) # Start the runtime, send a message and stop the runtime runtime.start() await runtime.send_message(MyMessage("Hello, world!"), recipient=AgentId("my_agent", "default")) await runtime.stop() asyncio.run(main())
创建运行时、注册代理、发布消息并停止运行时的示例:
import asyncio from dataclasses import dataclass from autogen_core import ( DefaultTopicId, MessageContext, RoutedAgent, SingleThreadedAgentRuntime, default_subscription, message_handler, ) @dataclass class MyMessage: content: str # The agent is subscribed to the default topic. @default_subscription class MyAgent(RoutedAgent): @message_handler async def handle_my_message(self, message: MyMessage, ctx: MessageContext) -> None: print(f"Received message: {message.content}") async def main() -> None: # Create a runtime and register the agent runtime = SingleThreadedAgentRuntime() await MyAgent.register(runtime, "my_agent", lambda: MyAgent("My agent")) # Start the runtime. runtime.start() # Publish a message to the default topic that the agent is subscribed to. await runtime.publish_message(MyMessage("Hello, world!"), DefaultTopicId()) # Wait for the message to be processed and then stop the runtime. await runtime.stop_when_idle() asyncio.run(main())
- async send_message(message: Any, recipient: AgentId, *, sender: AgentId | None = None, cancellation_token: CancellationToken | None = None, message_id: str | None = None) Any [源代码]#
向代理发送消息并获取响应。
- 参数:
message (Any) -- 要发送的消息。
recipient (AgentId) -- 接收消息的代理。
sender (AgentId | None, optional) -- 发送消息的代理。**仅**当消息不是由任何代理发送时(例如直接从外部发送到运行时)才应为None。默认为None。
cancellation_token (CancellationToken | None, optional) -- 用于取消进行中的操作的令牌。默认为None。
- 抛出:
CantHandleException -- 如果接收方无法处理该消息。
UndeliverableException -- 如果消息无法送达。
Other -- 接收方引发的任何其他异常。
- Returns:
Any -- 来自代理的响应。
- async publish_message(message: Any, topic_id: TopicId, *, sender: AgentId | None = None, cancellation_token: CancellationToken | None = None, message_id: str | None = None) None [源代码]#
向给定命名空间中的所有代理发布消息,如果未提供命名空间,则使用发送者的命名空间。
发布消息不期望获得响应。
- 参数:
message (Any) -- 要发布的消息。
topic_id (TopicId) -- 发布消息的主题。
sender (AgentId | None, optional) -- 发送消息的代理。默认为None。
cancellation_token (CancellationToken | None, optional) -- 用于取消进行中的操作的令牌。默认为None。
message_id (str | None, optional) -- 消息ID。如果为None,将生成新的消息ID。默认为None。此消息ID必须唯一,建议使用UUID。
- 抛出:
UndeliverableException -- 如果消息无法送达。
- async save_state() Mapping[str, Any] [源代码]#
保存所有已实例化代理的状态。
此方法调用每个代理的
save_state()
方法,并返回一个字典, 将代理ID映射到其状态。备注
此方法当前不保存订阅状态。我们将在未来添加此功能。
- Returns:
一个将代理ID映射到其状态的字典。
- async load_state(state: Mapping[str, Any]) None [源代码]#
加载所有已实例化代理的状态。
此方法使用字典中提供的状态调用每个代理的
load_state()
方法。 字典的键是代理ID,值是由save_state()
方法返回的状态字典。备注
此方法当前不加载订阅状态。我们将在未来添加此功能。
- start() None [源代码]#
启动运行时消息处理循环。此操作在后台任务中运行。
示例:
import asyncio from autogen_core import SingleThreadedAgentRuntime async def main() -> None: runtime = SingleThreadedAgentRuntime() runtime.start() # ... do other things ... await runtime.stop() asyncio.run(main())
- async close() None [源代码]#
如果适用则调用
stop()
方法,并对所有已实例化的代理调用Agent.close()
方法
- async stop_when(condition: Callable[[], bool]) None [源代码]#
当满足条件时停止运行时消息处理循环。
警告
不建议使用此方法,此处仅为向后兼容保留。 该方法会生成一个繁忙循环来持续检查条件。 调用`stop_when_idle`或`stop`会更加高效。 如果需要基于条件停止运行时,建议使用后台任务和asyncio.Event来 在条件满足时发出信号,然后由后台任务调用stop方法。
- async agent_metadata(agent: AgentId) AgentMetadata [源代码]#
获取代理的元数据。
- 参数:
agent (AgentId) -- 代理ID。
- Returns:
AgentMetadata -- 代理元数据。
- async agent_save_state(agent: AgentId) Mapping[str, Any] [源代码]#
保存单个代理的状态。
状态的结构由实现定义,可以是任何可JSON序列化的对象。
- 参数:
agent (AgentId) -- 代理ID。
- Returns:
Mapping[str, Any] -- 已保存的状态。
- async register_factory(type: str | AgentType, agent_factory: Callable[[], T | Awaitable[T]], *, expected_class: type[T] | None = None) AgentType [源代码]#
向运行时注册与特定类型关联的代理工厂。该类型必须唯一。此API不添加任何订阅。
备注
这是一个底层API,通常应使用代理类的`register`方法代替,因为该方法还会自动处理订阅。
示例:
from dataclasses import dataclass from autogen_core import AgentRuntime, MessageContext, RoutedAgent, event from autogen_core.models import UserMessage @dataclass class MyMessage: content: str class MyAgent(RoutedAgent): def __init__(self) -> None: super().__init__("My core agent") @event async def handler(self, message: UserMessage, context: MessageContext) -> None: print("Event received: ", message.content) async def my_agent_factory(): return MyAgent() async def main() -> None: runtime: AgentRuntime = ... # type: ignore await runtime.register_factory("my_agent", lambda: MyAgent()) import asyncio asyncio.run(main())
- async register_agent_instance(agent_instance: Agent, agent_id: AgentId) AgentId [源代码]#
向运行时注册一个代理实例。类型可以重复使用,但每个agent_id必须唯一。同一类型下的所有代理实例必须是相同的对象类型。此API不会添加任何订阅。
备注
这是一个底层API,通常应该使用代理类的`register_instance`方法,因为该方法还会自动处理订阅。
示例:
from dataclasses import dataclass from autogen_core import AgentId, AgentRuntime, MessageContext, RoutedAgent, event from autogen_core.models import UserMessage @dataclass class MyMessage: content: str class MyAgent(RoutedAgent): def __init__(self) -> None: super().__init__("My core agent") @event async def handler(self, message: UserMessage, context: MessageContext) -> None: print("Event received: ", message.content) async def main() -> None: runtime: AgentRuntime = ... # type: ignore agent = MyAgent() await runtime.register_agent_instance( agent_instance=agent, agent_id=AgentId(type="my_agent", key="default") ) import asyncio asyncio.run(main())
- async try_get_underlying_agent_instance(id: AgentId, type: Type[T] = Agent) T [源代码]#
尝试通过名称和命名空间获取底层代理实例。通常不推荐这样做(因此名称较长),但在某些情况下可能有用。
如果底层代理不可访问,将引发异常。
- 参数:
id (AgentId) -- 代理ID。
type (Type[T], optional) -- 代理的预期类型。默认为Agent。
- Returns:
T -- 具体的代理实例。
- 抛出:
LookupError -- 如果找不到代理。
NotAccessibleError -- 如果代理不可访问,例如位于远程。
TypeError -- 如果代理不是预期类型。
- async add_subscription(subscription: Subscription) None [源代码]#
添加运行时在处理发布消息时应满足的新订阅
- 参数:
subscription (Subscription) -- 要添加的订阅
- async remove_subscription(id: str) None [源代码]#
从运行时移除订阅
- 参数:
id (str) -- 要移除的订阅ID
- 抛出:
LookupError -- 如果订阅不存在
- async get(id_or_type: AgentId | AgentType | str, /, key: str = 'default', *, lazy: bool = True) AgentId [源代码]#
- add_message_serializer(serializer: MessageSerializer[Any] | Sequence[MessageSerializer[Any]]) None [源代码]#
向运行时添加新的消息序列化序列化器
注意:这将根据 type_name 和 data_content_type 属性对序列化器进行去重
- 参数:
serializer (MessageSerializer[Any] | Sequence[MessageSerializer[Any]]) -- 要添加的序列化器/序列化器列表
- ROOT_LOGGER_NAME = 'autogen_core'#
根日志记录器名称。
- EVENT_LOGGER_NAME = 'autogen_core.events'#
用于结构化事件的日志记录器名称。
- TRACE_LOGGER_NAME = 'autogen_core.trace'#
用于开发者预期跟踪日志的日志记录器名称。不应依赖此日志的内容和格式。
- class Component[源代码]#
基类:
ComponentFromConfig
[ConfigT
],ComponentSchemaType
[ConfigT
],Generic
[ConfigT
]要创建组件类,具体类需继承自本类,接口需继承自ComponentBase。然后实现两个类变量:
component_config_schema
- 表示组件配置的Pydantic模型类。这也是Component的类型参数。component_type
- 组件的逻辑类型。
示例:
from __future__ import annotations from pydantic import BaseModel from autogen_core import Component class Config(BaseModel): value: str class MyComponent(Component[Config]): component_type = "custom" component_config_schema = Config def __init__(self, value: str): self.value = value def _to_config(self) -> Config: return Config(value=self.value) @classmethod def _from_config(cls, config: Config) -> MyComponent: return cls(value=config.value)
- class ComponentBase[源代码]#
基类:
ComponentToConfig
[ConfigT
],ComponentLoader
,Generic
[ConfigT
]
- class ComponentFromConfig[源代码]#
基类:
Generic
[FromConfigT
]
- class ComponentLoader[源代码]#
基类:
object
- classmethod load_component(model: ComponentModel | Dict[str, Any], expected: None = None) Self [源代码]#
- classmethod load_component(model: ComponentModel | Dict[str, Any], expected: Type[ExpectedType]) ExpectedType
从模型加载组件。该方法设计用于与
autogen_core.ComponentConfig.dump_component()
的返回类型配合使用。示例
from autogen_core import ComponentModel from autogen_core.models import ChatCompletionClient component: ComponentModel = ... # type: ignore model_client = ChatCompletionClient.load_component(component)
- 参数:
model (ComponentModel) -- 用于加载组件的模型。
model -- _description_
expected (Type[ExpectedType] | None, optional) -- 仅在直接用于 ComponentLoader 时需要显式类型。默认为 None。
- Returns:
Self -- 加载后的组件。
- 抛出:
ValueError -- 如果提供者字符串无效。
TypeError -- 提供者不是 ComponentConfigImpl 的子类,或期望类型不匹配。
- Returns:
Self | ExpectedType -- 加载后的组件。
- pydantic model ComponentModel[源代码]#
基类:
BaseModel
组件的模型类。包含实例化组件所需的全部信息。
Show JSON schema
{ "title": "ComponentModel", "description": "\u7ec4\u4ef6\u7684\u6a21\u578b\u7c7b\u3002\u5305\u542b\u5b9e\u4f8b\u5316\u7ec4\u4ef6\u6240\u9700\u7684\u5168\u90e8\u4fe1\u606f\u3002", "type": "object", "properties": { "provider": { "title": "Provider", "type": "string" }, "component_type": { "anyOf": [ { "enum": [ "model", "agent", "tool", "termination", "token_provider", "workbench" ], "type": "string" }, { "type": "string" }, { "type": "null" } ], "default": null, "title": "Component Type" }, "version": { "anyOf": [ { "type": "integer" }, { "type": "null" } ], "default": null, "title": "Version" }, "component_version": { "anyOf": [ { "type": "integer" }, { "type": "null" } ], "default": null, "title": "Component Version" }, "description": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "title": "Description" }, "label": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "title": "Label" }, "config": { "title": "Config", "type": "object" } }, "required": [ "provider", "config" ] }
- Fields:
component_type (Literal['model', 'agent', 'tool', 'termination', 'token_provider', 'workbench'] | str | None)
component_version (int | None)
config (dict[str, Any])
description (str | None)
label (str | None)
provider (str)
version (int | None)
- class ComponentSchemaType[源代码]#
基类:
Generic
[ConfigT
]- required_class_vars = ['component_config_schema', 'component_type']#
- class ComponentToConfig[源代码]#
基类:
Generic
[ToConfigT
]类必须实现的两种方法才能成为组件。
- 参数:
Protocol (ConfigT) -- 继承自
pydantic.BaseModel
的类型。
- component_type: ClassVar[Literal['model', 'agent', 'tool', 'termination', 'token_provider', 'workbench'] | str]#
组件的逻辑类型。
- dump_component() ComponentModel [源代码]#
将组件转储为可重新加载的模型。
- 抛出:
TypeError -- 如果组件是本地类。
- Returns:
ComponentModel -- 表示组件的模型。
- class InterventionHandler(*args, **kwargs)[源代码]#
基类:
Protocol
干预处理器是一个类,可用于修改、记录或丢弃正在被
autogen_core.base.AgentRuntime
处理的消息。当消息提交到运行时,处理器会被调用。
目前唯一支持此功能的运行时是
autogen_core.base.SingleThreadedAgentRuntime
。注意:从任何干预处理器方法返回 None 都会导致发出警告并被当作"无更改"处理。如果确实要丢弃消息,应显式返回
DropMessage
。示例:
from autogen_core import DefaultInterventionHandler, MessageContext, AgentId, SingleThreadedAgentRuntime from dataclasses import dataclass from typing import Any @dataclass class MyMessage: content: str class MyInterventionHandler(DefaultInterventionHandler): async def on_send(self, message: Any, *, message_context: MessageContext, recipient: AgentId) -> MyMessage: if isinstance(message, MyMessage): message.content = message.content.upper() return message runtime = SingleThreadedAgentRuntime(intervention_handlers=[MyInterventionHandler()])
- async on_send(message: Any, *, message_context: MessageContext, recipient: AgentId) Any | type[DropMessage] [源代码]#
当通过
autogen_core.base.AgentRuntime.send_message()
方法向 AgentRuntime 提交消息时调用。
- async on_publish(message: Any, *, message_context: MessageContext) Any | type[DropMessage] [源代码]#
当通过
autogen_core.base.AgentRuntime.publish_message()
方法向 AgentRuntime 发布消息时调用。
- class DefaultInterventionHandler(*args, **kwargs)[源代码]#
-
提供所有干预处理器方法默认实现的简单类,这些方法会原样返回消息。便于通过子类化仅覆盖所需方法。
- async on_send(message: Any, *, message_context: MessageContext, recipient: AgentId) Any | type[DropMessage] [源代码]#
当通过
autogen_core.base.AgentRuntime.send_message()
方法向 AgentRuntime 提交消息时调用。
- async on_publish(message: Any, *, message_context: MessageContext) Any | type[DropMessage] [源代码]#
当通过
autogen_core.base.AgentRuntime.publish_message()
方法向 AgentRuntime 发布消息时调用。