Examples
Practical patterns for using the AI Mode API in production.
1. Robust Client (Python)
A Python class that handles connection checks and timeouts gracefully.
import requests
import time
from typing import Optional, Dict, Any
class AIModeClient:
def __init__(self, websocket_id: str):
self.base_url = f"https://app.aimodeapi.com/api/{websocket_id}"
self.session = requests.Session()
def ask(self, query: str, retries: int = 2) -> Optional[Dict[str, Any]]:
"""
Send a query with retry logic.
"""
payload = {"query": query}
for attempt in range(retries + 1):
try:
print(f"Angle '{query}' (Attempt {attempt + 1})...")
response = self.session.post(
self.base_url,
json=payload,
timeout=90 # Generous timeout
)
# Check for 400 (Connection Not Found) specifically
if response.status_code == 400:
print("Error: Extension not connected. Please check your browser.")
return None
response.raise_for_status()
return response.json()
except requests.Timeout:
print("Request timed out. Google AI took too long.")
except requests.RequestException as e:
print(f"Request failed: {e}")
if attempt < retries:
time.sleep(2) # Wait before retry
return None
# Usage
client = AIModeClient("YOUR_WEBSOCKET_ID")
result = client.ask("Explain the theory of relativity")
if result:
resp = result.get('response', {})
if resp.get('success'):
print(resp['data']['response_body'])
else:
print("AI processing failed")
2. Batch Processing (JavaScript)
Process a list of questions sequentially.
Sequential Processing
We recommend sequential processing (one by one) per extension instance to avoid overwhelming the single browser tab.
const WEBSOCKET_ID = "YOUR_WEBSOCKET_ID";
const API_URL = `https://app.aimodeapi.com/api/${WEBSOCKET_ID}`;
const questions = [
"What is photosynthesis?",
"How do magnets work?",
"Why is the sky blue?"
];
async function processQueue() {
for (const [index, question] of questions.entries()) {
console.log(`\n[${index + 1}/${questions.length}] Asking: "${question}"`);
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: question })
});
if (!response.ok) {
const err = await response.text();
console.error(`Failed: ${response.status} - ${err}`);
continue;
}
const json = await response.json();
if (!json.response.success) {
console.error("Automation error");
continue;
}
const answer = json.response.data.response_body;
console.log("Answer:", answer.substring(0, 100) + "...");
// Optional: Wait a bit between requests to be polite to Google
await new Promise(r => setTimeout(r, 2000));
} catch (error) {
console.error("Error processing question:", error);
}
}
console.log("\nBatch complete!");
}
processQueue();