Overview
AI agents burn through search credits unpredictably. A single research task might trigger 50 searches while a Q&A task uses 2. Without per-agent cost tracking, teams discover overspend only at billing time. This workflow wraps every search call with cost tracking, per-agent attribution, and threshold alerting.
Trigger
Every search API call from any agent in the system.
Schedule
Event-driven
Workflow Steps
Intercept Search Request
Wrap the search API call with a cost-tracking middleware that records the calling agent, task ID, and query.
Execute Search
Forward the request to Scavio search API. Record success/failure and result count.
Record Cost
Add the credit cost ($0.005/credit) to the running total for this agent and task.
Check Thresholds
Compare cumulative spend against daily and monthly budgets. Alert at 50%, 75%, 90%.
Enforce Limits
Block non-critical searches if the daily or monthly budget is exhausted.
Python Implementation
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}")JavaScript Implementation
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));Platforms Used
Web search with knowledge graph, PAA, and AI overviews
YouTube
Video search with transcripts and metadata
Community, posts & threaded comments from any subreddit
Amazon
Product search with prices, ratings, and reviews