Basic Agent¶
This example demonstrates how to create a simple conversational agent using nagents.
Overview¶
flowchart LR
A[User Input] --> B[Agent]
B --> C[Provider]
C --> D[LLM API]
D --> C
C --> B
B --> E[Response]
Simple Chat Agent¶
The most basic agent requires just a provider and a session manager:
- The
SessionManageris required - it handles conversation persistence - Use environment variables in production:
os.environ.get("OPENAI_API_KEY") - The system prompt defines the agent's personality and behavior
Interactive Chat Loop¶
For a more interactive experience, create a chat loop:
- Creating a session allows conversation history to persist across messages
- Pass the
session_idto maintain context between turns
Handling Different Event Types¶
The agent emits various events during execution. Here's how to handle them:
async for event in agent.run("What is Python?"):
match event.type:
case "text_delta":
print(event.content, end="", flush=True)
case "thinking_delta":
print(f"[Thinking: {event.content}]")
case "usage":
print(f"\n📊 Usage: {event.input_tokens}→{event.output_tokens} tokens")
case "message_complete":
print(f"✅ Complete: {event.stop_reason}")
case "error":
print(f"❌ Error: {event.error}")
Configuration Options¶
Agent Parameters¶
| Parameter | Type | Required | Description |
|---|---|---|---|
provider |
Provider |
Yes | The LLM provider to use |
session_manager |
SessionManager |
Yes | Manages conversation sessions |
system_prompt |
str |
No | Instructions for the agent |
tools |
list[Tool] |
No | Tools the agent can use |
max_tokens |
int |
No | Maximum response tokens |
temperature |
float |
No | Sampling temperature (0-2) |
Example with All Options¶
configured_agent.py
agent = Agent(
provider=provider,
session_manager=session_manager,
system_prompt="""You are a Python expert.
- Always provide code examples
- Explain concepts clearly
- Suggest best practices""",
max_tokens=2048,
temperature=0.7,
)
Best Practices¶
Environment Variables
Never hardcode API keys. Use environment variables:
Error Handling
Always handle potential errors gracefully:
Session Management
For production applications, implement proper session lifecycle management:
Next Steps¶
- Learn about Multi-Provider setups for fallback and load balancing
- Explore Tool Usage to give your agent capabilities
- Check out the Sessions Guide for advanced session management