Skip to main content
An Agent is a stateful wrapper around model calls. Use an agent when your app needs identity, message history, tools, persistent state, or server routes.

What An Agent Owns

An agent owns:
  • an ID
  • a model
  • a system prompt
  • tools
  • message history
  • state
  • storage
  • emitted events
Core generation functions are stateless. Agents are stateful.

Minimal Agent

The async with block starts the agent, loads state, and stops background processing when done.

Conversation Memory

The agent stores messages between calls.
The second call includes the first user message and assistant response.

Persistence

Use SQLiteStorage for local durable history.
Storage persists:
  • agent.state
  • agent.messages
  • event logs when enable_event_log = True

Agent State

State is app-owned data attached to the agent.
Use state for durable facts your application controls. Use messages for conversation history.

Typed State

You can define state shape on a subclass.

Tools On Agents

Tools work the same way as core generation, but agent history persists tool calls and tool results.

Three Ways To Run An Agent

chat

Use chat() when you need final text.

run

Use run() when you need a structured result.

turn

Use turn() when you need events, cancellation, or steering.

Events

Agents can emit application events.
Enable durable replay:
Clients can reconnect and replay missed events by event ID.

Serving Agents

Use AgentServer to expose agents over HTTP, SSE, WebSocket, and RPC.
Read Agent Server when you are ready to serve many agent instances.

When To Use Agents

Use agents for:
  • user sessions
  • persistent chatbots
  • coding agents
  • research agents
  • tool-using assistants
  • apps that need event streams or replay
  • multi-agent systems
Do not use agents for simple one-off calls. Use generate_text() or stream_text() instead.