Creating an Agent
There are two ways to create an agent:Using as_agent() (Recommended)
The simplest way to create an agent is using the as_agent() method on any chat client:
Using the Agent Class
For more control, you can instantiate the Agent class directly:
Running an Agent
Non-Streaming Response
Get the complete response at once:Streaming Response
Stream the response as it’s generated:Agent Configuration
Instructions
Instructions define the agent’s behavior and personality:Tools
Tools can be added at the agent level or per-run:Middleware
Middleware allows you to intercept and modify agent behavior:Sessions and Context
Using Sessions
Sessions manage conversation history and state:Custom History Providers
Store conversation history in a database:Response Models and Structured Output
Structured Output with Pydantic
Generate structured data with type safety:Advanced Configuration
Chat Options
Override model settings per-run:Background Responses
Start an agent run without blocking:Auto-Retry
Automatically retry failed requests:Best Practices
Use descriptive instructions
Use descriptive instructions
Provide clear, specific instructions that define the agent’s role, constraints, and response format. Include examples when helpful.
Prefer `as_agent()` for simplicity
Prefer `as_agent()` for simplicity
Use the
as_agent() shorthand method for creating agents unless you need fine-grained control over the Agent class initialization.Enable tool approval in production
Enable tool approval in production
Always use
approval_mode="always_require" for tools in production. Only use "never_require" for samples and testing.Use sessions for multi-turn conversations
Use sessions for multi-turn conversations
Pass an
AgentSession to maintain context across multiple interactions with the same user.Implement proper error handling
Implement proper error handling
Wrap agent runs in try-except blocks to handle failures gracefully:
API Reference
Agent Class
run() Method
Examples
Multi-Agent Interaction
Agent with Multiple Tools
Related
- Tools - Add custom functionality to agents
- Middleware - Intercept and modify agent behavior
- Workflows - Orchestrate multi-agent systems
- Providers - Connect to different AI services