Overview
This workflow generates a weekly report of search API costs across all agents in a deployment. It reads usage logs, calculates per-agent and per-task costs at $0.005/query, identifies cost trends, and flags agents whose usage spiked above normal. The report helps teams optimize agent search patterns, identify runaway loops, and forecast monthly API spend.
Trigger
Cron schedule (every Friday at 5:00 PM UTC)
Schedule
Runs every Friday at 5:00 PM UTC
Workflow Steps
Collect usage logs
Read search API usage logs for the current week from the logging system.
Calculate per-agent costs
Group queries by agent ID, calculate total queries and costs per agent at $0.005/query.
Detect usage anomalies
Compare each agent's weekly usage against its 4-week rolling average to detect spikes.
Generate cost report
Compile a structured report with per-agent breakdown, trends, and anomaly flags.
Python Implementation
import json
from datetime import datetime
from pathlib import Path
from collections import defaultdict
COST_PER_QUERY = 0.005
def generate_cost_report(usage_log: list[dict]) -> dict:
"""Generate weekly cost report from usage logs."""
agent_usage = defaultdict(lambda: {"queries": 0, "platforms": defaultdict(int)})
for entry in usage_log:
agent_id = entry.get("agent_id", "unknown")
platform = entry.get("platform", "google")
agent_usage[agent_id]["queries"] += 1
agent_usage[agent_id]["platforms"][platform] += 1
report = {
"week_ending": datetime.utcnow().strftime("%Y-%m-%d"),
"total_queries": sum(a["queries"] for a in agent_usage.values()),
"total_cost": round(sum(a["queries"] for a in agent_usage.values()) * COST_PER_QUERY, 2),
"agents": [],
}
for agent_id, usage in sorted(agent_usage.items(), key=lambda x: x[1]["queries"], reverse=True):
cost = round(usage["queries"] * COST_PER_QUERY, 2)
report["agents"].append({
"agent_id": agent_id,
"queries": usage["queries"],
"cost": cost,
"platforms": dict(usage["platforms"]),
})
return report
def run():
# Example usage log
sample_log = [
{"agent_id": "research_agent", "platform": "google", "query": "test", "timestamp": "2026-05-20T10:00:00"},
{"agent_id": "research_agent", "platform": "reddit", "query": "test", "timestamp": "2026-05-20T10:01:00"},
{"agent_id": "price_agent", "platform": "amazon", "query": "test", "timestamp": "2026-05-20T11:00:00"},
{"agent_id": "price_agent", "platform": "walmart", "query": "test", "timestamp": "2026-05-20T11:01:00"},
{"agent_id": "price_agent", "platform": "amazon", "query": "test", "timestamp": "2026-05-20T12:00:00"},
]
report = generate_cost_report(sample_log)
print(f"Weekly cost report ({report['week_ending']}):")
print(f" Total: {report['total_queries']} queries, ${report['total_cost']}")
for agent in report["agents"]:
print(f" {agent['agent_id']}: {agent['queries']} queries (${agent['cost']})")
Path(f"cost_report_{report['week_ending']}.json").write_text(json.dumps(report, indent=2))
if __name__ == "__main__":
run()JavaScript Implementation
const COST_PER_QUERY = 0.005;
function generateCostReport(logs) {
const agents = {};
for (const entry of logs) {
const id = entry.agent_id ?? "unknown";
if (!agents[id]) agents[id] = { queries: 0, platforms: {} };
agents[id].queries++;
agents[id].platforms[entry.platform ?? "google"] = (agents[id].platforms[entry.platform ?? "google"] ?? 0) + 1;
}
const total = Object.values(agents).reduce((s, a) => s + a.queries, 0);
return { totalQueries: total, totalCost: (total * COST_PER_QUERY).toFixed(2), agents };
}
const logs = [
{ agent_id: "research", platform: "google" },
{ agent_id: "research", platform: "reddit" },
{ agent_id: "price", platform: "amazon" },
{ agent_id: "price", platform: "amazon" },
];
const report = generateCostReport(logs);
console.log(`Total: ${report.totalQueries} queries, $${report.totalCost}`);
for (const [id, data] of Object.entries(report.agents)) console.log(` ${id}: ${data.queries} queries`);Platforms Used
Web search with knowledge graph, PAA, and AI overviews
Amazon
Product search with prices, ratings, and reviews
Community, posts & threaded comments from any subreddit