Resumen
AI agents burn a traves de search credits unpredictably. A single research tarea podria activar 50 searches mientras un Q&A tarea usa 2. Without per-agent cost seguimiento, teams descubrir overspend solo at billing time. Este flujo de trabajo wraps cada search call con cost seguimiento, per-agent attribution, y umbral alerting.
Desencadenador
Every search llamada un API de cualquier agent in el system.
Programación
Event-driven
Pasos del flujo de trabajo
Intercept Search Solicitud
Wrap el search llamada un API con un cost-tracking middleware ese registros el calling agent, tarea ID, y consulta.
Ejecutar Search
Forward el solicitud to Scavio search API. Record success/failure y resultado conteo.
Record Cost
Add el credit cost ($0.005/credit) to el running total for este agent y tarea.
Verificar Thresholds
Comparar cumulative spend contra diario y mensual budgets. Alert at 50%, 75%, 90%.
Enforce Limits
Block non-critical searches if el diario o mensual budget es exhausted.
Implementacion en 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}")Implementacion en 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));Plataformas utilizadas
Búsqueda web con grafo de conocimiento, PAA y resúmenes de IA
YouTube
Búsqueda de videos con transcripciones y metadatos
Comunidad, publicaciones y comentarios en hilos de cualquier subreddit
Amazon
Búsqueda de productos con precios, calificaciones y reseñas