Error Handling
Error Handling
Because even AI makes mistakes—let's handle them with grace (and a bit of humor).
API Errors
try {
await agent.send('What is the meaning of life?');
} catch (e) {
if (e.toString().contains('429')) {
print('Whoa there, speedster! Rate limited. Time for coffee ☕');
} else if (e.toString().contains('401')) {
print('Nice try, but that API key is faker than a $3 bill');
}
}
Missing API Keys
try {
final agent = Agent('openai');
await agent.send('Hello, HAL');
} catch (e) {
if (e.toString().contains('OPENAI_API_KEY')) {
print('I'm afraid I can't do that, Dave. Set your OPENAI_API_KEY first.');
}
}
Tool Errors
final flakeyTool = Tool(
name: 'weather_api',
description: 'Get weather (when it feels like working)',
onCall: (args) async {
// Murphy's Law strikes again
throw Exception('Weather service is having a Monday');
},
);
// The AI gracefully handles tool failures
final agent = Agent('openai', tools: [flakeyTool]);
await agent.send('What's the weather?');
// AI: "I tried to check the weather, but the service seems to be down..."
Retry Strategy
Future<ChatResult> sendWithRetry(
Agent agent,
String prompt, {
int maxRetries = 3,
}) async {
for (var i = 0; i < maxRetries; i++) {
try {
return await agent.send(prompt);
} catch (e) {
if (i == maxRetries - 1) rethrow;
await Future.delayed(Duration(seconds: 1 << i));
}
}
throw Exception('Max retries exceeded');
}
Provider Fallback
Future<ChatResult> sendWithFallback(String prompt) async {
final providers = ['openai', 'anthropic', 'google'];
for (final provider in providers) {
try {
final agent = Agent(provider);
return await agent.send(prompt);
} catch (e) {
print('$provider failed: $e');
if (provider == providers.last) rethrow;
}
}
throw Exception('All providers failed');
}
Rate Limiting
Dartantic includes automatic retry for rate limits:
// Automatic retry with exponential backoff
final agent = Agent('openai');
await agent.send('Hello'); // Retries on 429
Best Practices
- Check environment variables at startup
- Log errors for debugging
- Provide user-friendly messages
- Implement fallbacks for critical paths
- Handle tool errors gracefully
Next Steps
- Automatic Retry - Built-in retry logic
- Logging - Debug and monitor errors