Quick Start¶
This guide will help you get started with nagents in minutes.
Basic Usage¶
1. Create a Provider¶
First, create a provider with your API credentials:
2. Create a Session Manager¶
Required Component
The session_manager parameter is required when creating an Agent. It handles conversation persistence.
from pathlib import Path
from nagents import SessionManager
session_manager = SessionManager(Path("sessions.db"))
3. Create an Agent¶
from nagents import Agent
agent = Agent(
provider=provider,
session_manager=session_manager,
system_prompt="You are a helpful assistant.", # (1)!
)
- The system prompt is optional but recommended to define the agent's behavior.
4. Run a Conversation¶
import asyncio
async def main():
async for event in agent.run("What is the capital of France?"):
if hasattr(event, 'chunk'):
print(event.chunk, end="", flush=True)
print() # newline at end
await agent.close()
asyncio.run(main())
Complete Example¶
Here's a complete, runnable example:
With Tools¶
Define Python functions as tools that the agent can call:
agent_with_tools.py
from nagents import Agent, Provider, ProviderType, SessionManager
from pathlib import Path
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"The weather in {city} is sunny, 22°C"
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression."""
return str(eval(expression))
async def main():
provider = Provider(...)
session_manager = SessionManager(Path("sessions.db"))
agent = Agent(
provider=provider,
session_manager=session_manager,
tools=[get_weather, calculate], # (1)!
)
async for event in agent.run("What's the weather in Paris?"):
...
- Pass functions directly - nagents automatically generates the tool schema from type hints and docstrings.
Tool Documentation
Always include docstrings in your tool functions! The LLM uses them to understand when and how to call each tool.
With Session Persistence¶
Sessions allow the agent to remember previous conversations:
persistent_sessions.py
from pathlib import Path
from nagents import Agent, SessionManager, Provider, ProviderType
async def main():
provider = Provider(...)
session_manager = SessionManager(Path("sessions.db"))
agent = Agent(provider=provider, session_manager=session_manager)
# First conversation - use a specific session ID
async for event in agent.run(
"Remember my name is Alice",
session_id="user-123", # (1)!
):
...
# Later, continue the same session
async for event in agent.run(
"What's my name?",
session_id="user-123", # (2)!
):
# Agent will remember: "Your name is Alice"
...
- Use a consistent session ID to maintain conversation history.
- Same session ID = same conversation context.
Handling Events¶
nagents emits various event types during generation:
event_handling.py
from nagents import (
TextChunkEvent,
TextDoneEvent,
ToolCallEvent,
ToolResultEvent,
ErrorEvent,
DoneEvent,
)
async for event in agent.run("Hello"):
match event:
case TextChunkEvent(chunk=chunk):
print(chunk, end="")
case ToolCallEvent(name=name, arguments=args):
print(f"\n:material-tools: Calling tool: {name}")
case ToolResultEvent(result=result):
print(f":material-check: Tool result: {result}")
case ErrorEvent(message=msg):
print(f":material-alert: Error: {msg}")
case DoneEvent(final_text=text, usage=usage):
print(f"\n---")
print(f"Total tokens: {usage.total_tokens}")
if usage.session:
print(f"Session tokens: {usage.session.total_tokens}")
Event Types Reference
| Event | Description |
|---|---|
TextChunkEvent |
Streaming text chunk |
TextDoneEvent |
Complete text (non-streaming) |
ToolCallEvent |
Model is calling a tool |
ToolResultEvent |
Tool execution completed |
ErrorEvent |
Error occurred |
DoneEvent |
Generation complete |
Next Steps¶
-
Configuration
Learn about generation parameters and HTTP logging.
-
Tools Guide
Create powerful tools for your agent.
-
Sessions Guide
Manage conversation persistence.