Requests and responses: what happens in a run
A run is a conversation between the agent and the model, kept as a list of messages. Printing that list shows exactly what the model was sent and what it said.
for message in result.all_messages():
print(message.kind)
for part in message.parts:
print(" ", part.part_kind)all_messages() returns every message of the run, in order. There are two kinds. A request goes from the agent to the model; a response comes back. Each message holds parts: here the request has one user-prompt part, your ticket, and the response one text part, the answer.
A run with a tool
A tool is a Python function the model can ask the agent to call. Lesson 10 covers them properly; one is enough to see the run grow:
@agent.tool_plain
def lookup_order(order_id: str) -> str:
"""Look up an order's status."""
return f"Order {order_id} has shipped."
result = agent.run_sync("Where is my order A-1001?")
for message in result.all_messages():
for part in message.parts:
content = getattr(part, "content", None) or getattr(part, "args", None)
print(f"{message.kind:8} {part.part_kind:12} {content}")
print(result.usage)Four messages now. The model's first response is a tool-call part with arguments. The agent runs lookup_order and sends the result back in a new request, as a tool-return part. Then the model writes its answer. That is two requests to the model, and usage says so, with tool_calls=1.
The test model called the tool with order_id='a': it calls every tool once with made-up arguments that fit the types, then reports what came back. A real model would have read A-1001 out of the ticket.
- Add a second tool,
refund_order(order_id: str) -> str, and print the parts again. - Print
result.new_messages(). How is it different fromall_messages()here? - Print
result.response, the model's last response.
You understood something today that you didn't yesterday.