Connection Timeouts
Problem: Requests timeout before completing Solution: Implement retry logic with exponential backoff- JavaScript
- Python
- HTTPie
Copy
// 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' })
}
);
Copy
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def create_session_with_retries():
"""Create requests session with retries"""
session = requests.Session()
# Configure retries
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "POST", "DELETE"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
# Usage
http_session = create_session_with_retries()
response = http_session.post(
f"{BASE_URL}/sessions",
headers=HEADERS,
json={"agent_name": "agi-0"},
timeout=30 # Increase timeout
)
Copy
# HTTPie has built-in timeout handling
http --timeout=30 POST https://api.agi.tech/v1/sessions \
Authorization:"Bearer $AGI_API_KEY" \
agent_name=agi-0
# For retries, use a loop
for i in {1..3}; do
http POST https://api.agi.tech/v1/sessions \
Authorization:"Bearer $AGI_API_KEY" \
agent_name=agi-0 && break || sleep $((2 ** i))
done
Rate Limiting (429 Errors)
Problem: Too many requests causing rate limit errors Solution: Implement rate limiting and backoff- JavaScript
- Python
- HTTPie
Copy
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);
}
Copy
from time import time, sleep
class RateLimiter:
def __init__(self, calls_per_minute=30):
self.calls_per_minute = calls_per_minute
self.calls = []
def wait_if_needed(self):
"""Wait if rate limit would be exceeded"""
now = time()
# Remove old calls
self.calls = [t for t in self.calls if now - t < 60]
# Check limit
if len(self.calls) >= self.calls_per_minute:
sleep_time = 60 - (now - self.calls[0])
print(f"Rate limit: sleeping {sleep_time:.1f}s")
sleep(sleep_time)
self.calls.append(now)
# Usage
limiter = RateLimiter(calls_per_minute=20)
for task in tasks:
limiter.wait_if_needed()
run_agent_task(task)
Copy
# Simple rate limiting with sleep
for task in "${tasks[@]}"; do
http POST https://api.agi.tech/v1/sessions/$SESSION_ID/message \
Authorization:"Bearer $AGI_API_KEY" \
message="$task"
# Wait 2 seconds between requests
sleep 2
done
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- JavaScript
- Python
- HTTPie
Copy
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)}`);
}
}
Copy
def check_message_flow(session_id):
# Send test message
send_message(session_id, "Reply with 'OK'")
# Wait and check
time.sleep(5)
messages = get_messages(session_id)
print(f"Total messages: {len(messages['messages'])}")
print(f"Agent connected: {messages['has_agent']}")
print(f"Status: {messages['status']}")
# Print recent messages
for msg in messages["messages"][-5:]:
print(f"[{msg['type']}] {msg['content'][:100]}")
Copy
# Send test message
http POST https://api.agi.tech/v1/sessions/$SESSION_ID/message \
Authorization:"Bearer $AGI_API_KEY" \
message="Reply with 'OK'"
# Wait and check
sleep 5
# Get messages
http GET https://api.agi.tech/v1/sessions/$SESSION_ID/messages \
Authorization:"Bearer $AGI_API_KEY" | jq '{
total: (.messages | length),
agent_connected: .has_agent,
status: .status,
recent: .messages[-5:]
}'
Parsing SSE Streams
Problem: Difficulty parsing Server-Sent Events Solution: Use proper SSE client or manual parsing- JavaScript
- Python
- HTTPie
Copy
// 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);
}
}
}
}
Copy
# Option 1: Use sseclient library
from sseclient import SSEClient
def stream_events_simple(session_id):
url = f"{BASE_URL}/sessions/{session_id}/events"
headers = {"Authorization": f"Bearer {API_KEY}"}
messages = SSEClient(url, headers=headers)
for msg in messages:
if msg.event and msg.data:
data = json.loads(msg.data)
print(f"[{msg.event}] {data}")
# Option 2: Manual parsing
def stream_events_manual(session_id):
url = f"{BASE_URL}/sessions/{session_id}/events"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Accept": "text/event-stream"
}
response = requests.get(url, headers=headers, stream=True)
event_type = None
for line in response.iter_lines(decode_unicode=True):
if not line:
continue
if line.startswith("event:"):
event_type = line[7:].strip()
elif line.startswith("data:"):
data = json.loads(line[6:])
print(f"[{event_type}] {data}")
Copy
# Stream events with HTTPie
http --stream GET https://api.agi.tech/v1/sessions/$SESSION_ID/events \
Authorization:"Bearer $AGI_API_KEY" \
Accept:text/event-stream
# Alternative: Use http --stream for SSE
http --stream GET https://api.agi.tech/v1/sessions/$SESSION_ID/events \
Authorization:"Bearer $AGI_API_KEY" \
Accept:text/event-stream