Skip to main content

Overview

Optimize your AGI Agent integration for maximum performance through concurrent execution and caching.

Parallel Execution

Process multiple independent tasks simultaneously.
import { AGIClient } from 'agi';

const client = new AGIClient({ apiKey: 'your_api_key' });

async function checkPrice(product) {
  const session = await client.createSession('agi-0-fast');
  try {
    const result = await session.runTask(`Find ${product} price on Amazon`);
    return result;
  } finally {
    await session.delete();
  }
}

async function checkMultiplePrices(products) {
  const promises = products.map(product => checkPrice(product));
  const results = await Promise.allSettled(promises);
  
  const prices = {};
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      prices[products[index]] = result.value;
    } else {
      console.log(`Failed for ${products[index]}: ${result.reason}`);
      prices[products[index]] = null;
    }
  });
  
  return prices;
}

// Usage
const products = ["iPhone 15", "Samsung S24", "Pixel 8"];
const prices = await checkMultiplePrices(products);
Respect rate limits! Don’t create too many concurrent sessions. Monitor your usage to avoid hitting API limits.

Reuse Authenticated Sessions

Use snapshots to avoid re-authenticating for each session.
// After logging in, save snapshot
await client.deleteSession(sessionId, {
  save_snapshot_mode: 'filesystem',
  save_as_default: true
});

// Future sessions restore authentication automatically
async function createAuthenticatedSession() {
  const session = await client.createSession('agi-0', {
    restore_default_environment_from_user_id: userId
  });
  return session.session_id;
}
Using snapshots can reduce session creation time by 5-7x when authentication is required.

Simple Caching

Cache results to avoid redundant API calls.
const cache = {};
const CACHE_TTL = 3600 * 1000; // 1 hour in milliseconds

async function getCachedPrice(product) {
  const cacheKey = `price:${product}`;
  
  // Check cache
  if (cache[cacheKey]) {
    const [data, timestamp] = cache[cacheKey];
    if (Date.now() - timestamp < CACHE_TTL) {
      return data;
    }
  }
  
  // Fetch new data
  const result = await checkPrice(product);
  
  // Store in cache
  cache[cacheKey] = [result, Date.now()];
  
  return result;
}

Best Practices

Use Parallel Execution

Process independent tasks concurrently

Reuse Sessions

Use snapshots to avoid re-authenticating

Cache Results

Cache frequently accessed data

Choose Right Model

Use agi-0-fast for simple tasks