Conversation
The Conversation class provides natural multi-turn conversations with automatic history management, cost tracking, and persistence.
Basic Usage
from yosrai import Agent, Conversation
agent = Agent.from_preset("assistant")
# Start a conversation
with agent.conversation() as chat:
response1 = chat.send_message("Hello!")
response2 = chat.send_message("What's my name?")
print(f"Total cost: ${chat.total_usage.cost:.4f}")
Constructor
Conversation(
agent: Agent,
session_id: Optional[str] = None,
max_history: int = 50,
system_prompt: Optional[str] = None,
initial_context: Optional[Dict[str, Any]] = None
)
Parameters:
- agent: The agent to converse with
- session_id: Unique conversation identifier (auto-generated if None)
- max_history: Maximum messages to keep in history (auto-trims)
- system_prompt: Override agent's default instructions
- initial_context: Initial context variables
Context Manager
Conversations must be used as context managers to ensure proper state management:
# ✅ Correct usage
with agent.conversation() as chat:
chat.send_message("Hello")
# ❌ Incorrect - will raise RuntimeError
chat = agent.conversation()
chat.send_message("Hello") # Error!
Methods
send_message(message: str, **context_updates) -> str
Send a message and receive a response.
with agent.conversation() as chat:
response = chat.send_message("Explain recursion")
# Update context variables
response = chat.send_message("Give an example", language="python")
Parameters:
- message: User's message
- **context_updates: Context variables to update
Returns: Agent's response string
clear() -> None
Clear conversation history while preserving session.
with agent.conversation() as chat:
chat.send_message("Remember this")
print(len(chat.messages)) # 2
chat.clear()
print(len(chat.messages)) # 0
get_history(limit: Optional[int] = None) -> List[ConversationMessage]
Get conversation message history.
with agent.conversation() as chat:
chat.send_message("Hello")
chat.send_message("How are you?")
# Get all messages
all_messages = chat.get_history()
# Get recent messages
recent = chat.get_history(limit=3)
get_summary() -> Dict[str, Any]
Get conversation statistics and metadata.
summary = chat.get_summary()
# {
# "session_id": "abc123",
# "agent_name": "Assistant",
# "total_messages": 4,
# "user_messages": 2,
# "assistant_messages": 2,
# "total_tokens": 150,
# "total_cost": 0.0045,
# "created_at": "2024-01-01T10:00:00",
# "last_activity": "2024-01-01T10:05:00"
# }
Persistence
save_to_file(file_path: str) -> None
Save conversation to JSON file.
with agent.conversation(session_id="tutorial") as chat:
chat.send_message("Explain quantum computing")
chat.send_message("Give a practical example")
chat.save_to_file("quantum_tutorial.json")
load_from_file(file_path: str, agent: Agent) -> Conversation
Load conversation from JSON file.
# Resume previous conversation
loaded = Conversation.load_from_file("quantum_tutorial.json", agent)
with loaded:
response = loaded.send_message("Now explain it simply")
Advanced Features
Custom System Prompts
Override the agent's default instructions:
with agent.conversation(
system_prompt="You are a pirate. Speak like one! Arrr!"
) as chat:
response = chat.send_message("How are you?")
# "Arrr, I'm doin' fine, matey!"
Initial Context
Provide context variables that persist throughout the conversation:
with agent.conversation(
user_name="Dr. Smith",
expertise="physics",
style="academic"
) as chat:
chat.send_message("Hello!")
# Agent knows user is Dr. Smith, expert in physics, prefers academic style
History Management
Control memory usage with automatic trimming:
# Limit to 20 messages (10 turns)
with agent.conversation(max_history=20) as chat:
# Long conversation automatically trimmed
pass
Message Format
Each message in the conversation is a ConversationMessage:
@dataclass
class ConversationMessage:
role: str # "user", "assistant", "system"
content: str
timestamp: datetime
metadata: Dict[str, Any] # Custom metadata
Cost Tracking
Conversations automatically track cumulative costs:
with agent.conversation() as chat:
chat.send_message("Long message...") # $0.002
chat.send_message("Another message...") # $0.001
print(f"Total cost: ${chat.total_usage.cost:.4f}") # $0.003
Error Handling
Conversations handle errors gracefully:
with agent.conversation() as chat:
try:
response = chat.send_message("Valid message")
except Exception as e:
# Error messages are still added to history
print(f"Error occurred: {e}")
# Conversation can continue
response = chat.send_message("Try again")
CLI Integration
Conversations work seamlessly with the CLI:
# Interactive conversation
yosrai chat --preset assistant --save-session chat.json
# Resume via CLI
yosrai chat --load-session chat.json
# Commands within chat:
/status # Show conversation stats
/clear # Reset conversation
/save # Save current session
Best Practices
✅ Do's
- Always use context managers:
with agent.conversation() as chat: - Save important conversations:
chat.save_to_file("important.json") - Monitor costs:
print(chat.total_usage.cost) - Set appropriate history limits:
max_history=50 - Use session IDs for organization:
session_id="project_xyz"
❌ Don'ts
- Don't use conversations outside context managers
- Don't manually manage message history (let Conversation handle it)
- Don't share conversations across different agent instances
- Don't rely on conversation state persisting without saving
Examples
Research Session
researcher = Agent.from_preset("researcher")
with researcher.conversation(session_id="quantum_research") as chat:
chat.send_message("What is quantum entanglement?")
chat.send_message("How is it used in computing?")
chat.send_message("What are current practical applications?")
# Save for later reference
chat.save_to_file("quantum_research_session.json")
print(f"Research cost: ${chat.total_usage.cost:.4f}")
Code Review Session
coder = Agent.from_preset("coder")
with coder.conversation(
system_prompt="You are a senior software engineer doing code review.",
max_history=30
) as chat:
chat.send_message("Review this Python function for security issues", code=code_snippet)
chat.send_message("Suggest improvements for performance")
chat.send_message("How would you test this?")
chat.save_to_file("code_review_session.json")
Educational Tutorial
teacher = Agent.from_preset("assistant")
with teacher.conversation(
topic="machine learning",
student_level="beginner",
session_id="ml_tutorial_001"
) as chat:
responses = []
responses.append(chat.send_message("What is machine learning?"))
responses.append(chat.send_message("Give a simple example"))
responses.append(chat.send_message("What are the main types?"))
# Save complete tutorial
chat.save_to_file("ml_tutorial_complete.json")
print(f"Tutorial completed in {len(chat.messages)//2} exchanges")