Documentation Index Fetch the complete documentation index at: https://mintlify.com/microsoft/autogen/llms.txt
Use this file to discover all available pages before exploring further.
The autogen_core package provides the foundational components for building distributed, event-driven multi-agent systems.
Agent Classes
Base class for implementing agents with message handling capabilities. from autogen_core import BaseAgent, AgentId, AgentRuntime, MessageContext
class MyAgent ( BaseAgent ):
def __init__ ( self , agent_id : AgentId, runtime : AgentRuntime):
super (). __init__ (agent_id, runtime)
Unique identifier for the agent instance
Runtime environment for message passing and agent coordination
Returns the agent’s unique identifier
Decorator-based agent with automatic message routing. from autogen_core import RoutedAgent, message_handler, rpc
from dataclasses import dataclass
@dataclass
class TaskMessage :
task: str
class WorkerAgent ( RoutedAgent ):
@message_handler
async def handle_task ( self , message : TaskMessage, ctx : MessageContext) -> str :
return f "Completed: { message.task } "
@rpc
async def get_status ( self ) -> dict :
return { "status" : "ready" }
Optional description of the agent’s capabilities
Decorators Marks a method as a handler for published messages of the parameter type
Marks a method as an RPC endpoint for direct invocation
Marks a method as an event handler
Agent implementation using closure functions for simple message handling. from autogen_core import ClosureAgent, ClosureContext
async def my_handler ( ctx : ClosureContext, message : str ) -> str :
await ctx.send_message( "processed" , recipient_id)
return "Done"
agent = ClosureAgent( "my_agent" , my_handler, runtime)
Async function to handle incoming messages
Runtime & Messaging
Protocol defining the runtime environment for agent execution and communication. from autogen_core import AgentRuntime, AgentId, TopicId
async def example ( runtime : AgentRuntime):
# Send direct message
response = await runtime.send_message(
message = "Hello" ,
recipient = AgentId( "worker" , "default" )
)
# Publish to topic
await runtime.publish_message(
message = { "event" : "started" },
topic_id = TopicId( "events" , "default" )
)
Methods Send a message to a specific agent and await response The message payload to send
Sender agent identifier (None for external)
Token to cancel the operation
Unique message identifier
Publish a message to all subscribers of a topic Register an agent factory for dynamic agent creation Unique agent type identifier
Factory function that creates agent instances
Expected agent class for type checking
SingleThreadedAgentRuntime
In-process runtime for single-threaded agent execution. from autogen_core import SingleThreadedAgentRuntime, TypeSubscription
runtime = SingleThreadedAgentRuntime()
# Register agent type
await runtime.register_factory(
type = "worker" ,
agent_factory = lambda : WorkerAgent(),
expected_class = WorkerAgent
)
# Add subscription
await runtime.add_subscription(
TypeSubscription( topic_type = "tasks" , agent_type = "worker" )
)
# Start runtime
runtime.start()
Start the runtime message processing loop
Gracefully stop the runtime
Context information for message handling. from autogen_core import MessageContext
@message_handler
async def handle ( self , message : str , ctx : MessageContext) -> None :
print ( f "From: { ctx.sender } " )
print ( f "Topic: { ctx.topic_id } " )
print ( f "Message ID: { ctx.message_id } " )
Identifier of the message sender
Topic the message was published to
Unique message identifier
Token for cancelling operations
Identity & Types
Unique identifier for an agent instance. from autogen_core import AgentId
# Create agent ID
agent_id = AgentId( type = "worker" , key = "instance_1" )
# Access components
print (agent_id.type) # "worker"
print (agent_id.key) # "instance_1"
Agent type name (alphanumeric and underscores)
Instance key (ASCII 32-126 characters)
Agent type definition for factory registration. from autogen_core import AgentType
worker_type = AgentType( "worker" )
Topic identifier for pub/sub messaging. from autogen_core import TopicId
topic = TopicId( type = "events" , source = "system" )
Proxy for remote agent communication. from autogen_core import AgentProxy
proxy = AgentProxy(agent_id, runtime)
result = await proxy.send( "Hello" )
Subscriptions
Subscribe to messages by exact type match. from autogen_core import TypeSubscription
subscription = TypeSubscription(
topic_type = "tasks" ,
agent_type = "worker"
)
await runtime.add_subscription(subscription)
Topic type to subscribe to
Agent type that will receive messages
Subscribe to messages matching a type prefix. from autogen_core import TypePrefixSubscription
subscription = TypePrefixSubscription(
topic_type_prefix = "task." ,
agent_type = "worker"
)
Topic type prefix to match
Agent type to receive matching messages
Subscribe to all messages in a namespace. from autogen_core import DefaultSubscription
subscription = DefaultSubscription(
agent_type = "logger"
)
Serialization & Components
Protocol for custom message serialization. from autogen_core import MessageSerializer
class MySerializer ( MessageSerializer ):
def serialize ( self , message : Any) -> bytes :
return json.dumps(message).encode()
def deserialize ( self , data : bytes , type_name : str ) -> Any:
return json.loads(data.decode())
Declarative component configuration. from autogen_core import Component, ComponentModel
@Component
class MyComponent :
def __init__ ( self , config : dict ):
self .value = config[ "value" ]
def to_config ( self ) -> ComponentModel:
return ComponentModel(
component_type = self . __class__ . __name__ ,
config = { "value" : self .value}
)
Marks a class as a configurable component
Serializable component configuration Component type identifier
Component configuration data
Image data container for multimodal messages. from autogen_core import Image
# From bytes
image = Image.from_bytes(image_bytes, format = "png" )
# From file
image = Image.from_file( "photo.jpg" )
# From URL
image = Image.from_url( "https://example.com/image.png" )
Create image from byte data
Create image from file path
State Management
Protocol for agent state persistence. from autogen_core import CacheStore
class CustomStore ( CacheStore ):
async def get ( self , key : str ) -> Any:
# Retrieve value
pass
async def set ( self , key : str , value : Any) -> None :
# Store value
pass
In-memory cache store implementation. from autogen_core import InMemoryStore
store = InMemoryStore()
await store.set( "key" , "value" )
result = await store.get( "key" )
Intervention & Control
Protocol for intercepting and modifying messages. from autogen_core import InterventionHandler, MessageContext
class ApprovalHandler ( InterventionHandler ):
async def on_send ( self , message : Any, ctx : MessageContext) -> Any:
# Review and modify message before sending
if needs_approval(message):
approved = await get_approval(message)
if not approved:
from autogen_core import DropMessage
raise DropMessage( "Not approved" )
return message
Exception to prevent message delivery. from autogen_core import DropMessage
raise DropMessage( "Message rejected by policy" )
Token for cancelling long-running operations. from autogen_core import CancellationToken
token = CancellationToken()
# Cancel after timeout
token.cancel_after( 10.0 )
# Check if cancelled
if token.is_cancelled:
return
Telemetry
OpenTelemetry integration for distributed tracing. from autogen_core import (
trace_create_agent_span,
trace_invoke_agent_span,
trace_tool_span
)
# Trace agent creation
with trace_create_agent_span( agent_type = "worker" ):
agent = WorkerAgent()
# Trace agent invocation
with trace_invoke_agent_span(agent_id, message_type = "Task" ):
result = await agent.handle(task)
# Trace tool execution
with trace_tool_span( tool_name = "calculator" ):
result = calculator.add( 1 , 2 )
Structured logging configuration. from autogen_core import ROOT_LOGGER_NAME , EVENT_LOGGER_NAME , TRACE_LOGGER_NAME
import logging
# Configure root logger
logging.getLogger( ROOT_LOGGER_NAME ).setLevel(logging. INFO )
# Configure event logger for structured events
event_logger = logging.getLogger( EVENT_LOGGER_NAME )
# Configure trace logger for development debugging
trace_logger = logging.getLogger( TRACE_LOGGER_NAME )
Name of the root logger: "autogen_core"
Name for structured event logging
Name for development trace logging
Types & Protocols
Represents a tool or function call. from autogen_core import FunctionCall
call = FunctionCall(
id = "call_123" ,
name = "calculator" ,
arguments = { "a" : 1 , "b" : 2 }
)
Represents a message with unknown type. from autogen_core import UnknownPayload
# Raised when deserializer encounters unknown type
Constants
JSON_DATA_CONTENT_TYPE = "application/json"
PROTOBUF_DATA_CONTENT_TYPE = "application/protobuf"
See Also