autogen_core._agent_instantiation 源代码
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Any, ClassVar, Generator
from ._agent_id import AgentId
from ._agent_runtime import AgentRuntime
[文档]
class AgentInstantiationContext:
"""一个提供代理实例化上下文的静态类。
这个静态类可用于在代理实例化过程中(在工厂函数或代理的类构造函数内部)
访问当前运行时和代理ID。
示例:
在工厂函数和代理构造函数中获取当前运行时和代理ID:
.. code-block:: python
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())
"""
def __init__(self) -> None:
raise RuntimeError(
"AgentInstantiationContext cannot be instantiated. It is a static class that provides context management for agent instantiation."
)
_AGENT_INSTANTIATION_CONTEXT_VAR: ClassVar[ContextVar[tuple[AgentRuntime, AgentId]]] = ContextVar(
"_AGENT_INSTANTIATION_CONTEXT_VAR"
)
@classmethod
@contextmanager
def populate_context(cls, ctx: tuple[AgentRuntime, AgentId]) -> Generator[None, Any, None]:
""":meta private:"""
token = AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.set(ctx)
try:
yield
finally:
AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)
[文档]
@classmethod
def current_runtime(cls) -> AgentRuntime:
try:
return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[0]
except LookupError as e:
raise RuntimeError(
"AgentInstantiationContext.runtime() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so."
) from e
[文档]
@classmethod
def current_agent_id(cls) -> AgentId:
try:
return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[1]
except LookupError as e:
raise RuntimeError(
"AgentInstantiationContext.agent_id() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so."
) from e
[文档]
@classmethod
def is_in_factory_call(cls) -> bool:
if cls._AGENT_INSTANTIATION_CONTEXT_VAR.get(None) is None:
return False
return True