Overview
Optimize your AGI Agent integration for maximum performance through concurrent execution and caching.Parallel Execution
Process multiple independent tasks simultaneously.- JavaScript
- Python
- HTTPie
Copy
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);
Copy
from concurrent.futures import ThreadPoolExecutor, as_completed
from pyagi import AGIClient
import time
client = AGIClient(api_key="your_api_key")
def check_price(product):
with client.session("agi-0-fast") as session:
result = session.run_task(f"Find {product} price on Amazon")
return result
def check_multiple_prices(products):
with ThreadPoolExecutor(max_workers=5) as executor:
futures = {
executor.submit(check_price, product): product
for product in products
}
results = {}
for future in as_completed(futures):
product = futures[future]
try:
results[product] = future.result()
except Exception as e:
print(f"Failed for {product}: {e}")
results[product] = None
return results
# Usage
products = ["iPhone 15", "Samsung S24", "Pixel 8"]
prices = check_multiple_prices(products)
Copy
# Create multiple sessions in parallel (using background jobs)
for product in "iPhone 15" "Samsung S24" "Pixel 8"; do
(
SESSION=$(http POST https://api.agi.tech/v1/sessions \
Authorization:"Bearer $AGI_API_KEY" \
agent_name=agi-0-fast | jq -r '.session_id')
http POST https://api.agi.tech/v1/sessions/$SESSION/message \
Authorization:"Bearer $AGI_API_KEY" \
message="Find $product price on Amazon"
# Poll for completion...
http DELETE https://api.agi.tech/v1/sessions/$SESSION \
Authorization:"Bearer $AGI_API_KEY"
) &
done
wait
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.- JavaScript
- Python
- HTTPie
Copy
// 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;
}
Copy
# After logging in, save snapshot
requests.delete(
f"{BASE_URL}/sessions/{session_id}",
headers=HEADERS,
params={
"save_snapshot_mode": "filesystem",
"save_as_default": "true"
}
)
# Future sessions restore authentication automatically
def create_authenticated_session():
response = requests.post(
f"{BASE_URL}/sessions",
headers=HEADERS,
json={
"agent_name": "agi-0",
"restore_default_environment_from_user_id": user_id
}
)
return response.json()["session_id"]
Copy
# After logging in, save snapshot
http DELETE "https://api.agi.tech/v1/sessions/$SESSION_ID?save_snapshot_mode=filesystem&save_as_default=true" \
Authorization:"Bearer $AGI_API_KEY"
# Future sessions restore authentication automatically
NEW_SESSION=$(http POST https://api.agi.tech/v1/sessions \
Authorization:"Bearer $AGI_API_KEY" \
agent_name=agi-0 \
restore_default_environment_from_user_id=$USER_ID | jq -r '.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.- JavaScript
- Python
- HTTPie
Copy
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;
}
Copy
import time
cache = {}
CACHE_TTL = 3600 # 1 hour
def get_cached_price(product):
cache_key = f"price:{product}"
# Check cache
if cache_key in cache:
data, timestamp = cache[cache_key]
if time.time() - timestamp < CACHE_TTL:
return data
# Fetch new data
result = check_price(product)
# Store in cache
cache[cache_key] = (result, time.time())
return result
Copy
# Use external caching (Redis, file-based, etc.)
CACHE_FILE="/tmp/price_cache.json"
# Check cache
if [ -f "$CACHE_FILE" ]; then
CACHE_TIME=$(jq -r '.timestamp' "$CACHE_FILE")
NOW=$(date +%s)
if [ $((NOW - CACHE_TIME)) -lt 3600 ]; then
jq -r ".$PRODUCT" "$CACHE_FILE"
exit 0
fi
fi
# Fetch and cache
RESULT=$(http POST https://api.agi.tech/v1/sessions/$SESSION_ID/message \
Authorization:"Bearer $AGI_API_KEY" \
message="Find $PRODUCT price")
echo "{\"$PRODUCT\": \"$RESULT\", \"timestamp\": $(date +%s)}" > "$CACHE_FILE"
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