Skip to main content

Connection Timeouts

Problem: Requests timeout before completing Solution: Implement retry logic with exponential backoff
// Use fetch with timeout and retry logic
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 30000); // 30s timeout
      
      const response = await fetch(url, {
        ...options,
        signal: controller.signal
      });
      
      clearTimeout(timeoutId);
      return response;
    } catch (e) {
      if (i === maxRetries - 1) throw e;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
}

// Usage
const response = await fetchWithRetry(
  'https://api.agi.tech/v1/sessions',
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ agent_name: 'agi-0' })
  }
);

Rate Limiting (429 Errors)

Problem: Too many requests causing rate limit errors Solution: Implement rate limiting and backoff
class RateLimiter {
  constructor(callsPerMinute = 30) {
    this.callsPerMinute = callsPerMinute;
    this.calls = [];
  }

  async waitIfNeeded() {
    const now = Date.now();
    
    // Remove old calls
    this.calls = this.calls.filter(t => now - t < 60000);
    
    // Check limit
    if (this.calls.length >= this.callsPerMinute) {
      const sleepTime = 60000 - (now - this.calls[0]);
      console.log(`Rate limit: sleeping ${sleepTime / 1000}s`);
      await new Promise(resolve => setTimeout(resolve, sleepTime));
    }
    
    this.calls.push(now);
  }
}

// Usage
const limiter = new RateLimiter(20);

for (const task of tasks) {
  await limiter.waitIfNeeded();
  await runAgentTask(task);
}
Monitor your API usage and adjust rate limits accordingly. Consider batching requests when possible.

Messages Not Appearing

Problem: Sent messages but not receiving responses Diagnostic: Check message flow and agent connection
async function checkMessageFlow(sessionId) {
  // Send test message
  await client.sendMessage(sessionId, "Reply with 'OK'");

  // Wait and check
  await new Promise(resolve => setTimeout(resolve, 5000));

  const messages = await client.getMessages(sessionId);

  console.log(`Total messages: ${messages.messages.length}`);
  console.log(`Agent connected: ${messages.has_agent}`);
  console.log(`Status: ${messages.status}`);

  // Print recent messages
  for (const msg of messages.messages.slice(-5)) {
    console.log(`[${msg.type}] ${msg.content.substring(0, 100)}`);
  }
}

Parsing SSE Streams

Problem: Difficulty parsing Server-Sent Events Solution: Use proper SSE client or manual parsing
// Option 1: Use EventSource (browser) or eventsource library (Node.js)
const eventSource = new EventSource(
  `https://api.agi.tech/v1/sessions/${sessionId}/events`,
  {
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    }
  }
);

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(`[${event.type}]`, data);
};

// Option 2: Manual parsing with fetch
async function streamEventsManual(sessionId) {
  const response = await fetch(
    `https://api.agi.tech/v1/sessions/${sessionId}/events`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Accept': 'text/event-stream'
      }
    }
  );

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split('\n');
    buffer = lines.pop() || '';

    let eventType = null;
    for (const line of lines) {
      if (line.startsWith('event:')) {
        eventType = line.substring(6).trim();
      } else if (line.startsWith('data:')) {
        const data = JSON.parse(line.substring(5));
        console.log(`[${eventType}]`, data);
      }
    }
  }
}