Skip to main content

Quick Reference

Handle errors gracefully. Retry transient failures, respect rate limits, and always set timeouts.

Retry Logic

Retry on timeouts and server errors (5xx).
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;
        }
    }
}

Timeout Handling

Always set timeouts to prevent hanging.
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]);
}

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

Next Steps