Aperçu
Les agents IA consomment les crédits de recherche de manière imprévisible. Une seule tâche de recherche peut déclencher 50 recherches tandis qu'une tâche de questions-réponses en utilise 2. Sans suivi des coûts par agent, les équipes ne découvrent les dépassements qu'à la facturation. Ce workflow encapsule chaque appel de recherche avec un suivi des coûts, une attribution par agent et des alertes de seuil.
Déclencheur
Chaque appel API de recherche provenant de tout agent du système.
Planification
Piloté par les événements
Étapes du workflow
Intercepter la requête de recherche
Envelopper l'appel API de recherche avec un middleware de suivi des coûts qui enregistre l'agent appelant, l'ID de tâche et la requête.
Exécuter la recherche
Transmettre la requête à l'API de recherche Scavio. Enregistrer le succès/échec et le nombre de résultats.
Enregistrer le coût
Ajouter le coût en crédits (0,005 $/crédit) au total cumulé pour cet agent et cette tâche.
Vérifier les seuils
Comparer les dépenses cumulées aux budgets quotidien et mensuel. Alerter à 50 %, 75 %, 90 %.
Appliquer les limites
Bloquer les recherches non critiques si le budget quotidien ou mensuel est épuisé.
Implémentation Python
import requests, os, json, time
from pathlib import Path
from datetime import datetime
API_KEY = os.environ["SCAVIO_API_KEY"]
H = {"x-api-key": API_KEY, "Content-Type": "application/json"}
COST_PER_CREDIT = 0.005
DAILY_BUDGET = 100 # credits
COSTS_FILE = Path("agent_costs.json")
def load_costs() -> dict:
today = datetime.now().strftime("%Y-%m-%d")
if COSTS_FILE.exists():
data = json.loads(COSTS_FILE.read_text())
if data.get("date") == today:
return data
return {"date": today, "agents": {}, "total": 0}
def save_costs(costs: dict):
COSTS_FILE.write_text(json.dumps(costs, indent=2))
def tracked_search(query: str, agent_id: str, critical: bool = False) -> dict:
costs = load_costs()
# Check budget
if costs["total"] >= DAILY_BUDGET and not critical:
return {"blocked": True, "reason": "Daily budget exhausted", "used": costs["total"]}
resp = requests.post(
"https://api.scavio.dev/api/v1/search",
headers=H,
json={"query": query, "country_code": "us"},
timeout=10,
)
# Track cost
costs["total"] += 1
if agent_id not in costs["agents"]:
costs["agents"][agent_id] = 0
costs["agents"][agent_id] += 1
# Check thresholds
pct = costs["total"] / DAILY_BUDGET * 100
for t in [50, 75, 90]:
if pct >= t:
print(f"BUDGET ALERT: {pct:.0f}% used ({costs['total']}/{DAILY_BUDGET} credits)")
save_costs(costs)
return resp.json()
result = tracked_search("kubernetes pod scheduling 2026", "research-agent-01")
print(f"Results: {len(result.get('organic_results', []))}")
costs = load_costs()
print(f"Daily total: {costs['total']} credits, ${costs['total'] * COST_PER_CREDIT:.2f}")Implémentation JavaScript
const H = {'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json'};
const fs = await import('fs');
const DAILY_BUDGET = 100;
function loadCosts() {
const today = new Date().toISOString().slice(0,10);
try { const d = JSON.parse(fs.readFileSync('agent_costs.json','utf8')); return d.date===today?d:{date:today,agents:{},total:0}; }
catch { return {date:today,agents:{},total:0}; }
}
function saveCosts(c) { fs.writeFileSync('agent_costs.json', JSON.stringify(c,null,2)); }
async function trackedSearch(query, agentId, critical=false) {
const costs = loadCosts();
if (costs.total >= DAILY_BUDGET && !critical) return {blocked:true, reason:'Daily budget exhausted'};
const r = await fetch('https://api.scavio.dev/api/v1/search', {method:'POST', headers:H, body:JSON.stringify({query, country_code:'us'})});
costs.total++;
costs.agents[agentId] = (costs.agents[agentId]||0) + 1;
const pct = costs.total/DAILY_BUDGET*100;
for (const t of [50,75,90]) { if (pct>=t) console.log('BUDGET ALERT: '+pct.toFixed(0)+'% used'); }
saveCosts(costs);
return r.json();
}
const r = await trackedSearch('kubernetes pod scheduling 2026', 'research-agent-01');
console.log('Results: '+(r.organic_results||[]).length);
const costs = loadCosts();
console.log('Daily total: '+costs.total+' credits, $'+(costs.total*0.005).toFixed(2));Plateformes utilisées
Recherche web avec graphe de connaissances, PAA et aperçus IA
YouTube
Recherche de vidéos avec transcriptions et métadonnées
Communauté, publications et commentaires imbriqués de n'importe quel subreddit
Amazon
Recherche de produits avec prix, notes et avis