The problem nobody talks about
You have 30 agents running in production. Marketing, support, procurement, data pipelines — all calling GPT-4o or Claude 3.5 Sonnet. The bill comes in at $47k for the month. Finance asks: which agents are worth it?
You go to OpenAI's dashboard. It shows you total spend by model. Not by agent. Not by team. Not by outcome. Just a big number that grows every month with no attributable cause.
user or metadata field — if you're even passing that. Without instrumentation at the application layer, you have no idea which agent caused which charge.
And it gets worse. A single agent with a logic bug — a loop, a missing exit condition, a context window that keeps growing — can generate $4k–$12k in a single weekend. No alert fires. The billing cycle doesn't tell you until the bill arrives. You're not running AI agents at scale; you're running a blind spot at scale.
This guide walks through how to build proper instrumentation. Not a hack, not a dashboard you have to check manually — a system that attributes every token to an agent, tracks cost per invocation, and can alert you or hard-cap spend before it becomes a line item on the CFO's report.
Step 1: Instrument the OpenAI SDK wrapper
The first thing you need is a wrapper around the OpenAI (or Anthropic) SDK that intercepts every request and logs the cost. Don't patch every call site — wrap the client once.
/** * OpenAI cost tracker — wraps the official SDK to capture * token usage and cost per call, attributing it to an agent ID. * Pass agentId in the request options under `user`. */ const { OpenAI } = require('openai'); const pool = require('./db/pool'); // your pg Pool // Pricing per 1M tokens (USD) — update quarterly const PRICING = { 'gpt-4o': { input: 2.50, output: 10.00 }, 'gpt-4o-mini': { input: 0.15, output: 0.60 }, 'gpt-4-turbo': { input: 10.00, output: 30.00 }, 'gpt-3.5-turbo': { input: 0.50, output: 1.50 }, }; function buildClient(apiKey) { return new OpenAI({ apiKey }); } /** * Log a cost event to the fleet_events table. * Insert is fire-and-forget — don't block the LLM response on it. */ async function logCostEvent(agentId, model, usage, extraMetadata = {}) { const p = PRICING[model] || { input: 0, output: 0 }; const inputCost = (usage.prompt_tokens / 1_000_000) * p.input; const outputCost = (usage.completion_tokens / 1_000_000) * p.output; const totalCost = inputCost + outputCost; // Fire-and-forget — don't hold up the LLM response pool.query( `INSERT INTO fleet_events (agent_id, event_type, amount, metadata, occurred_at) VALUES ($1, $2, $3, $4, NOW())`, [ agentId, 'llm_call', totalCost, JSON.stringify({ model, prompt_tokens: usage.prompt_tokens, completion_tokens: usage.completion_tokens, ...extraMetadata, }) ] ).catch(err => console.error('fleet_events insert failed:', err.message)); } /** * Tracked chat completion — logs cost then returns the response. * Usage: trackedChat(client, { agentId: 'support-001', model: 'gpt-4o', messages: [...] }) */ async function trackedChat(client, options) { const { agentId, model, messages, temperature, max_tokens, ...rest } = options; const response = await client.chat.completions.create({ model, messages, temperature: temperature ?? 0.7, max_tokens: max_tokens ?? 2048, user: agentId, // ← the attribution signal ...rest, }); const usage = response.usage; if (usage) { // Non-blocking — don't slow down your agent response logCostEvent(agentId, model, usage, { response_id: response.id, finish_reason: response.choices[0].finish_reason, }); } return response; } module.exports = { buildClient, trackedChat, PRICING };
Key design decisions:
- Pass
agentIdvia theuserfield. OpenAI surfaces this in their usage logs and API responses — it becomes the primary attribution key you can join on. - Log asynchronously.
logCostEventfires withoutawait— you do not want a database write to add latency to every LLM call. - Update pricing quarterly. Model prices change. Hardcode the current prices and build a reminder to update them when OpenAI sends their price-change notice (they do, usually 30 days ahead).
Step 2: Set up the events table
The fleet_events table is simple — insert-only, no joins in the hot path. Keep it lean.
CREATE TABLE IF NOT EXISTS fleet_events (
id SERIAL PRIMARY KEY,
agent_id VARCHAR(64) NOT NULL,
event_type VARCHAR(64) NOT NULL, -- 'llm_call', 'budget_hit', 'cap_exceeded'
amount NUMERIC(12,4) NOT NULL, -- cost in USD
metadata JSONB DEFAULT '{}',
occurred_at TIMESTAMPTZ DEFAULT NOW()
);
-- Query by agent + time window — your most common read pattern
CREATE INDEX idx_fleet_events_agent_time
ON fleet_events (agent_id, occurred_at DESC);
-- Aggregate rollups for dashboards (run as a periodic job)
CREATE TABLE IF NOT EXISTS fleet_events_rollup (
agent_id VARCHAR(64) NOT NULL,
period VARCHAR(16) NOT NULL, -- 'day', 'week', 'month'
total_cost NUMERIC(12,2) NOT NULL DEFAULT 0,
total_calls INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ DEFAULT NOW(),
PRIMARY KEY (agent_id, period)
);
The rollup table is updated by a cron job — don't compute daily totals on every dashboard request. Every 5 minutes is fine; daily is fine for most use cases. Keeps the dashboard fast.
Step 3: Query spend by agent, department, and time window
With the events table in place, you can answer the questions that matter.
/** * db/agent-spend.js * Query helpers for agent cost attribution. * All queries go through this file — never inline pool.query outside db/. */ // Spend by agent for a given time window async function getAgentSpend(pool, { agentId, since, until }) { const { rows } = await pool.query( `SELECT agent_id, SUM(amount) AS total_cost, COUNT(*) AS call_count, JSONB_OBJECT_AGG(event_type, COUNT(*)) AS events_by_type FROM fleet_events WHERE agent_id = $1 AND occurred_at BETWEEN $2 AND $3 GROUP BY agent_id`, [agentId, since, until] ); return rows[0] || { total_cost: 0, call_count: 0 }; } // Fleet-wide breakdown — used by the dashboard overview async function getFleetSpend(pool, { since, until }) { const { rows } = await pool.query( `SELECT agent_id, SUM(amount) AS total_cost, COUNT(*) AS call_count, ROUND(SUM(amount)::numeric, 2) AS total_cost_rounded, AVG(amount) AS avg_call_cost FROM fleet_events WHERE occurred_at BETWEEN $1 AND $2 GROUP BY agent_id ORDER BY total_cost DESC`, [since, until] ); return rows; } // Department-level rollup — assumes a department mapping you maintain async function getDepartmentSpend(pool, deptAgents, since, until) { const { rows } = await pool.query( `SELECT SUM(amount) AS dept_cost, COUNT(*) AS dept_calls FROM fleet_events WHERE agent_id = ANY($1) AND occurred_at BETWEEN $2 AND $3`, [deptAgents, since, until] ); return rows[0]; } // Budget utilization — what % of the monthly cap has each agent consumed? async function getBudgetUtilization(pool, budgets) { // budgets: [{ agentId: 'support-001', monthlyCap: 5000 }, ...] const startOfMonth = dateTrunc('month', new Date()); const agentIds = budgets.map(b => b.agentId); const { rows } = await pool.query( `SELECT agent_id, SUM(amount) AS mtd_cost FROM fleet_events WHERE agent_id = ANY($1) AND occurred_at >= $2 GROUP BY agent_id`, [agentIds, startOfMonth] ); // Join with budgets, compute utilization % return budgets.map(b => { const row = rows.find(r => r.agent_id === b.agentId); const spent = parseFloat(row?.mtd_cost || 0); return { agentId: b.agentId, spent, cap: b.monthlyCap, utilization: Math.round((spent / b.monthlyCap) * 100 * 10) / 10, }; }); } module.exports = { getAgentSpend, getFleetSpend, getDepartmentSpend, getBudgetUtilization };
Step 4: The dashboard — metrics that actually matter
With data flowing in, you can build the dashboard. Here's what to track:
| Metric | Why it matters | Alert threshold |
|---|---|---|
| Cost per agent / day | Catches runaway loops early — a 4x spike in 24h is a bug, not organic growth | >2× 7-day avg |
| Token count per call | Sudden jumps in avg tokens/call = context explosion, loop, or prompt injection | >3× baseline |
| Budget utilization % | Finance cares about this. At 80% by day 20, you're on track to overspend. | 80% warn, 100% hard cap |
| Calls per hour | Volume spike without cost spike = using a cheaper model. Cost spike without volume = runaway output. | Configurable per agent |
Here's what a minimal dashboard looks like in practice:
fleets table as agent metadata. When utilization hits 100%, your wrapper checks the cap before making the next call. This is how you get "hard caps that actually stop spend" — not just alerts.
Step 5: Hard caps — stop spend before it surprises you
Alerts are nice. Hard caps are what finance wants. Here's how to implement them at the call site:
// At the top of trackedChat, before the API call: async function getMonthlyBudget(pool, agentId) { const { rows } = await pool.query( `SELECT cap FROM agent_budgets WHERE agent_id = $1`, [agentId] ); return rows[0]?.cap || null; } async function getMTDSpent(pool, agentId) { const startOfMonth = dateTrunc('month', new Date()); const { rows } = await pool.query( `SELECT COALESCE(SUM(amount), 0) AS mtd_spent FROM fleet_events WHERE agent_id = $1 AND occurred_at >= $2`, [agentId, startOfMonth] ); return parseFloat(rows[0].mtd_spent); } async function trackedChat(client, options) { const { agentId, ...llmOptions } = options; // --- HARD CAP CHECK --- const cap = await getMonthlyBudget(pool, agentId); if (cap !== null) { const spent = await getMTDSpent(pool, agentId); if (spent >= cap) { pool.query( `INSERT INTO fleet_events (agent_id, event_type, amount, metadata, occurred_at) VALUES ($1, 'cap_exceeded', 0, '{}', NOW())`, [agentId] ); throw new Error(`Agent ${agentId} hit monthly cap of $${cap}`); } } // Proceed with the LLM call const response = await client.chat.completions.create(llmOptions); // ... log cost as before }
Yes, this adds two database queries per agent call. For a system that matters this much, that's fine — and you can cache the monthly spend in memory with a 60-second TTL to reduce DB load to near-zero. The cap check only matters when you're close to the limit anyway.
Map<agentId, { spent, cachedAt }>. Refresh it after the TTL. Your DB will thank you.
What Sentoria gives you out of the box
Everything in this post is the pattern we built Sentoria around. The wrapper, the rollup schema, the budget enforcement, the dashboard — it's all in the product. You don't need to wire this up yourself if you'd rather focus on the agents themselves.
If you're still building this manually:
- Start with the wrapper — everything else follows from getting
agent_idonto every call. - Don't skip the hard cap. "Alert at 90%" is not a cap — it's a warning that you're about to not have a cap.
- Update model pricing quarterly. A stale price table means your costs are wrong.
- Keep the rollup table updated. Computing aggregates on a 10M-row table on every dashboard load will wake you up at 3am.
Get the Fleet Monitor
Sentoria handles all of this automatically — per-agent visibility, hard caps, and CFO-ready spend reports.
Join the waitlist and get early access.