Lesson 2 of 6 · AutoGen
Conversable Agents
Build AutoGen agents: AssistantAgent with a model, system message and Python tools, reflect_on_tool_use, saved state, UserProxyAgent and the events a run makes.
- 7 min read
- Intermediate
- Reviewed
- Create an AssistantAgent with a system message and tools
- Explain reflect_on_tool_use and the events a run produces
- Use an agent's memory across runs, and save its state
- Bring a person into the conversation with UserProxyAgent
Agents that converse
The original AutoGen 0.2 had a single ConversableAgent class configured into different roles; the redesign split it into focused agents with the same idea. You'll still see the term “conversable agents” throughout AutoGen's documentation and papers.
An assistant with a tool
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.anthropic import AnthropicChatCompletionClient
def get_weather(city: str) -> str:
"""Get today's weather for a city."""
return {"porto": "17°C, light rain until 2pm", "lisbon": "24°C, sunny"}.get(city.lower(), "no data")
async def main():
model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
assistant = AssistantAgent(
"cycling_assistant",
model_client=model_client,
tools=[get_weather], # plain functions become tools
reflect_on_tool_use=True, # after the tool runs, the model writes the final answer
system_message="You help people plan bike rides. Check the weather before advising.",
)
result = await assistant.run(task="Is this morning good for a ride in Porto?")
for m in result.messages:
print(f"{type(m).__name__:<22} {m.source}: {m.content}")
# The agent keeps its conversation, so a follow-up works
result = await assistant.run(task="And in the afternoon?")
print(result.messages[-1].content)
await model_client.close()
asyncio.run(main())TextMessage user: Is this morning good for a ride in Porto?
ToolCallRequestEvent cycling_assistant: [FunctionCall(id='call_1', arguments='{"city": "Porto"}', name='get_weather')]
ToolCallExecutionEvent cycling_assistant: [FunctionExecutionResult(content='17°C, light rain until 2pm', name='get_weather', call_id='call_1', is_error=False)]
TextMessage cycling_assistant: Not ideal: Porto has light rain until 2pm. If you can, wait until the afternoon.
Yes, the afternoon looks good: the rain should stop at 2pm, and it's 17°C.What to notice:
- Tools are plain functions. AutoGen reads the name, docstring and type hints to build the tool schema, as LangChain and CrewAI do.
- A run produces messages and events.
TextMessages are what agents say;ToolCallRequestEventandToolCallExecutionEventrecord the tool call and its result. Printing them all is the quickest way to see what an agent did. reflect_on_tool_use=Truemakes the agent call the model again after the tool runs, to write a natural answer. WithFalse, the agent's final message is just the tool's output, which is cheaper and fine when the output is already readable.- The agent remembers. The follow-up “And in the afternoon?” works because the agent keeps its conversation between
runcalls.await agent.save_state()captures that history so you can store it and restore it later withload_state.
Here's the reflection difference, and the memory, in plain Python:
# A conversable agent in plain Python: it keeps its own message history between runs,
# can call a tool, and either returns the raw tool result or "reflects" on it with the model.
class Agent:
def __init__(self, name, model, tools, reflect_on_tool_use):
self.name, self.model, self.tools, self.reflect = name, model, tools, reflect_on_tool_use
self.history = [] # kept across runs, like AutoGen's model context
def run(self, task):
self.history.append(("user", task))
reply = self.model(self.history)
if isinstance(reply, dict): # the model asked for a tool
result = self.tools[reply["tool"]](**reply["args"])
self.history.append(("tool", result))
reply = self.model(self.history) if self.reflect else result
self.history.append((self.name, reply))
return reply
def fake_model(history): # stands in for an LLM
last_role, last = history[-1]
if last_role == "tool":
return f"Light rain until 2pm ({last}), so ride in the afternoon."
if "weather" in last or "ride" in last:
return {"tool": "get_weather", "args": {"city": "Porto"}}
return f"I remember {sum(1 for r, _ in history if r == 'user')} questions from you."
weather = {"get_weather": lambda city: "17°C, light rain until 2pm"}
raw = Agent("raw", fake_model, weather, reflect_on_tool_use=False)
reflective = Agent("reflective", fake_model, weather, reflect_on_tool_use=True)
print("No reflection: ", raw.run("Good morning for a ride in Porto?"))
print("With reflection:", reflective.run("Good morning for a ride in Porto?"))
print("Memory: ", reflective.run("How many questions have I asked?"))A person in the conversation
UserProxyAgent stands in for a human. When it's its turn, it asks a real person for input, by default with Python's input() in the terminal, or with your own input_func in a web app:
import asyncio
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.messages import TextMessage
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.anthropic import AnthropicChatCompletionClient
async def main():
model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
planner = AssistantAgent(
"ride_planner", model_client=model_client,
system_message="Propose one bike route at a time. When the user approves, confirm it briefly.",
)
person = UserProxyAgent("person", input_func=input) # asks the real person at the keyboard
team = RoundRobinGroupChat(
[planner, person], # they take turns
termination_condition=TextMentionTermination("APPROVE", sources=["person"]) | MaxMessageTermination(8),
)
result = await team.run(task="Plan a flat 20 km ride from Porto for Saturday.")
for m in result.messages:
if isinstance(m, TextMessage): # skip events such as "input requested"
print(f"{m.source}: {m.content}")
print("Stopped because:", result.stop_reason)
await model_client.close()
asyncio.run(main())user: Plan a flat 20 km ride from Porto for Saturday. ride_planner: Route 1: Porto riverside to Foz and back along the coast, 24 km, flat. person: Something shorter, please: my legs are tired. ride_planner: Route 2: riverside path to Foz and back, 16 km, flat, with a café stop at Foz. person: APPROVE Stopped because: Text 'APPROVE' mentioned
The planner and the person take turns. The termination condition only listens for “APPROVE” from the person (sources=["person"]), so the planner can't end the conversation by accident, and MaxMessageTermination(8) stops it if nobody approves.
Common mistakes
Write the speaker rule of a round-robin team: participants take turns in a fixed order.
participants = ["coder", "executor", "reviewer"]
def next_speaker(last_speaker):
# Round robin: return the participant after last_speaker, wrapping round to the first.
# If last_speaker is "user" (the task was just given), return the first participant.
pass
for last in ["user", "coder", "executor", "reviewer"]:
print(last, "->", next_speaker(last))
What does reflect_on_tool_use=True change in an AssistantAgent?
Summary
- Conversable agents take part in a conversation; AutoGen's main ones are AssistantAgent, UserProxyAgent and CodeExecutorAgent.
- AssistantAgent uses a model, a system message and plain functions as tools.
- reflect_on_tool_use decides whether the model rewrites tool results; max_tool_iterations allows more tool rounds.
- Agents remember across runs; save_state and load_state persist that memory.
- UserProxyAgent brings a person into the conversation; limit termination to the right sources.
Next: group chats.
Finished reading? Tick it off to track your progress.