Quick Reference
Handle errors gracefully. Retry transient failures, respect rate limits, and always set timeouts.Retry Logic
Retry on timeouts and server errors (5xx).- JavaScript
- Python
- HTTPie
Copy
import { AGIClient } from 'agi';
const client = new AGIClient({ apiKey: 'your_api_key' });
async function runTaskWithRetry(task, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const session = await client.createSession('agi-0');
try {
const result = await session.runTask(task);
return result;
} finally {
await session.delete();
}
} catch (error) {
if (error.status === 429) { // Rate limit
await new Promise(resolve => setTimeout(resolve, 60000));
continue;
} else if (error.status >= 500) { // Server error
if (attempt < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, 5000 * (attempt + 1)));
continue;
}
}
throw error;
}
}
}
Copy
from pyagi import AGIClient
import time
client = AGIClient(api_key="your_api_key")
def run_task_with_retry(task, max_retries=3):
"""Run task with automatic retry"""
for attempt in range(max_retries):
try:
with client.session("agi-0") as session:
return session.run_task(task)
except Exception as e:
if hasattr(e, 'status_code'):
if e.status_code == 429: # Rate limit
time.sleep(60)
continue
elif e.status_code >= 500: # Server error
if attempt < max_retries - 1:
time.sleep(5 * (attempt + 1)) # Exponential backoff
continue
raise
Copy
# Retry logic with bash
MAX_RETRIES=3
ATTEMPT=0
while [ $ATTEMPT -lt $MAX_RETRIES ]; do
RESPONSE=$(http POST https://api.agi.tech/v1/sessions/$SESSION/message \
Authorization:"Bearer $AGI_API_KEY" \
message="$TASK" 2>&1)
STATUS_CODE=$(echo "$RESPONSE" | grep -oP 'HTTP/\d\.\d \K\d+')
if [ "$STATUS_CODE" = "429" ]; then
sleep 60
ATTEMPT=$((ATTEMPT + 1))
continue
elif [ "$STATUS_CODE" -ge 500 ]; then
if [ $ATTEMPT -lt $((MAX_RETRIES - 1)) ]; then
sleep $((5 * (ATTEMPT + 1)))
ATTEMPT=$((ATTEMPT + 1))
continue
fi
fi
break
done
Timeout Handling
Always set timeouts to prevent hanging.- JavaScript
- Python
- HTTPie
Copy
async function runTaskWithTimeout(session, message, timeout = 300000) {
const startTime = Date.now();
const resultPromise = session.runTask(message);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error(`Task exceeded ${timeout}ms timeout`)), timeout);
});
return Promise.race([resultPromise, timeoutPromise]);
}
Copy
from pyagi import AGIClient
import time
client = AGIClient(api_key="your_api_key")
def run_task_with_timeout(session, message, timeout=300):
"""Send task with timeout"""
start_time = time.time()
# The package handles timeouts automatically, but you can add custom logic
try:
result = session.run_task(message)
if time.time() - start_time > timeout:
raise TimeoutError(f"Task exceeded {timeout}s timeout")
return result
except Exception as e:
if time.time() - start_time > timeout:
raise TimeoutError(f"Task exceeded {timeout}s timeout")
raise
Copy
TIMEOUT=300
START_TIME=$(date +%s)
http POST https://api.agi.tech/v1/sessions/$SESSION/message \
Authorization:"Bearer $AGI_API_KEY" \
message="$MESSAGE" \
timeout=$TIMEOUT
while true; do
ELAPSED=$(($(date +%s) - START_TIME))
if [ $ELAPSED -gt $TIMEOUT ]; then
echo "Task exceeded ${TIMEOUT}s timeout"
exit 1
fi
STATUS=$(http GET https://api.agi.tech/v1/sessions/$SESSION/status \
Authorization:"Bearer $AGI_API_KEY" | jq -r '.status')
if [ "$STATUS" = "finished" ]; then
break
elif [ "$STATUS" = "error" ]; then
echo "Task failed"
exit 1
fi
sleep 2
done
Key Principles
Retry Transient Errors
Retry on timeouts and server errors (5xx)
Handle Rate Limits
Wait 60s and retry on 429 errors
Set Timeouts
Always set request timeouts (30s recommended)
Clean Up Sessions
Always delete sessions in finally blocks