Best Practices
Best practices for building production-ready agents
Agent Best Practices
Follow these best practices to build reliable, efficient, and maintainable agents.
Model Selection
Use Appropriate Models
Don't use expensive models for simple tasks:
# Good: Use cheaper models for classification
classifier = Agent(model="llama-3")
# Good: Use powerful models for complex reasoning
analyst = Agent(model="gpt-4")Implement Fallbacks
Always configure fallback models:
{
"model": {
"primary": "gpt-4",
"fallbacks": ["claude-3-sonnet", "gemini-pro"]
}
}Memory Management
Set Appropriate TTLs
Configure time-to-live based on data importance:
{
"memory": {
"shortTerm": { "ttl": "1h" },
"longTerm": { "ttl": "30d" }
}
}Implement Memory Cleanup
Regularly clean up old memory:
@agent.schedule("0 0 * * *") # Daily
async def cleanup_memory():
await agent.memory.cleanup(older_than="30d")Error Handling
Implement Retry Logic
Handle transient failures:
@agent.on_error
async def handle_error(error):
if error.is_retryable:
return await agent.retry(max_attempts=3)
else:
await agent.log_error(error)
return error.fallback_responseGraceful Degradation
Provide fallback responses:
try:
response = await agent.generate(prompt)
except Exception as e:
response = "I'm having trouble right now. Please try again."Performance
Use Caching
Cache common responses:
@agent.cache(ttl=3600)
async def get_faq_response(question):
return await agent.generate(question)Optimize Prompts
Keep prompts concise:
# Bad: Verbose prompt
prompt = """
You are a helpful AI assistant. Your job is to...
[500 words of instructions]
Question: {question}
"""
# Good: Concise prompt
prompt = "Answer: {question}"Security
Validate Input
Always validate user input:
@agent.on_message
async def handle_message(message):
if not validate_input(message.content):
return "Invalid input"
return await agent.process(message)Sanitize Output
Prevent injection attacks:
response = await agent.generate(prompt)
return sanitize(response)Monitoring
Set Up Alerts
Monitor critical metrics:
swiftclaw alerts create \
--agent my-agent \
--metric error-rate \
--threshold 5% \
--action notifyLog Important Events
Track agent behavior:
@agent.on_message
async def handle_message(message):
agent.log("Received message", {
"user": message.user_id,
"length": len(message.content)
})Testing
Test Locally
Always test before deploying:
swiftclaw dev --testUse Version Control
Tag releases:
git tag v1.0.0
swiftclaw deploy --version v1.0.0Following these best practices will help you build reliable, efficient agents that scale.
How is this guide ?
Last updated on