Agents are the central primitive in AG2 Beta. They maintain state, interact with models, execute tools, and handle user interactions through a clean, conversation-focused API.
fromautogen.betaimportAgentfromautogen.beta.configimportOpenAIConfigagent=Agent("assistant",prompt="You are a helpful assistant.",config=OpenAIConfig("gpt-4o-mini"),)# Start a new conversationreply=awaitagent.ask("Give me one sentence about AG2 beta.")print(reply.content)# Continue the exact same conversation contextnext_turn=awaitreply.ask("Now make it shorter.")print(next_turn.content)...
Agents can seamlessly use Python functions as tools. When you provide a list of @tool-decorated functions to an agent, it automatically manages the entire execution lifecycle (model requests to execution and returning results).
fromautogen.betaimportAgent,Context,toolfromautogen.beta.configimportOpenAIConfig@toolasyncdefecho(text:str)->str:"""Useful for repeating exactly what was given."""returnf"echo: {text}"agent=Agent("assistant",prompt="Use tools when helpful.",config=OpenAIConfig("gpt-4o-mini"),tools=[echo],)reply=awaitagent.ask("Call the echo tool with 'hello'.")print(reply.content)
Sometimes an agent needs human guidance. You can configure an agent to handle HumanInputRequest events. This is especially effective inside tools where you can get confirmation before taking a sensitive action.
fromautogen.betaimportAgent,Context,toolfromautogen.beta.configimportOpenAIConfigfromautogen.beta.eventsimportHumanInputRequest,HumanMessage@toolasyncdefask_human(context:Context)->str:# Pauses agent execution to await human inputanswer=awaitcontext.input("Please provide confirmation:")returnf"Human said: {answer}"# Define how your application handles the input requestdefhitl_hook(event:HumanInputRequest)->HumanMessage:# Here you could block and wait for UI/CLI input.# We return a static response for demonstration.returnHumanMessage(content="confirmed")agent=Agent("assistant",prompt="Use ask_human when needed.",config=OpenAIConfig("gpt-4o-mini"),tools=[ask_human],hitl_hook=hitl_hook,)reply=awaitagent.ask("Request confirmation through the tool.")print(reply.content)
Need to know exactly what the agent is doing? Pass a MemoryStream when calling ask(). You can attach event subscribers to log actions, save history to a database, or update a user interface in real time.
fromautogen.betaimportAgent,Context,MemoryStreamfromautogen.beta.eventsimportBaseEvent,ModelResponse,ToolCallfromautogen.beta.configimportOpenAIConfigstream=MemoryStream()# Listen to everything@stream.subscribe()asyncdefon_any_event(event:BaseEvent)->None:print(f"Event occurred: {event}")# Only listen to specific events@stream.where(ToolCall).subscribe()asyncdefon_tool_call(event:ToolCall)->None:print("Agent requested tool:",event.name)agent=Agent("assistant",prompt="You are a helpful assistant.",config=OpenAIConfig("gpt-4o-mini"),)# Stream captures all events during the askreply=awaitagent.ask("Give me one sentence about AG2 beta.",stream=stream)