How to Monitor & Track OpenAI and Claude API Costs by Project
A practical engineering guide to monitoring OpenAI billing and Claude token usage by project. Learn how to set up project-scoped keys, account for prompt caching discounts, build runaway loop circuit breakers, and see costs next to revenue in RealMRR.
Engineering teams building with large language models face recurring billing challenges when monthly invoices arrive.
Illustrative example: a startup receives these monthly invoices from its model providers:
- OpenAI API: $11,482.40
- Anthropic Claude API: $9,840.15
The startup operates four distinct product initiatives:
- Core Customer Copilot: The main subscription feature in the web app.
- Document Extraction Pipeline: A background worker processing PDF contracts.
- Internal Developer Slack Bot: A tool for engineering code reviews.
- Experimental Sales Agent: A recent project built by the growth team.
Engineering leaders check the OpenAI Usage Dashboard and the Anthropic Console to identify which project drove the $21,300 expense.
Until work is split into projects and workspaces, these dashboards can only show totals for the whole organization.
The charts report 480 million tokens consumed across several OpenAI and Claude models. They do not show if the core subscription product generated the expense, or if the experimental sales agent entered an infinite tool-calling loop over the weekend.
Monitoring token consumption at the organization level obscures unit economics. Teams must track token consumption, budget limits, and API keys at the individual project level.
This guide outlines the architectural patterns needed to segment OpenAI and Anthropic workloads. It covers project-scoped keys, 2026 prompt caching economics, circuit breakers for autonomous agent loops, and automated cost synchronization with RealMRR.
1. Native Segmentation: OpenAI Projects vs. Anthropic Workspaces
Many engineering teams share a single universal API key across all microservices, local environments, and CI/CD pipelines.
When multiple projects share one key, isolating costs is impossible. Both OpenAI and Anthropic offer organizational tools to isolate resources.
┌────────────────────────────────────────────────────────────────────────┐
│ ORGANIZATIONAL LLM ARCHITECTURE │
│ │
│ ACME CORP PARENT ORGANIZATION │
│ │ │
│ ┌───────────────────────┴───────────────────────┐ │
│ ▼ ▼ │
│ OPENAI ORGANIZATIONAL HUB ANTHROPIC CONSOLE │
│ ├── Project: "prod-customer-app" ├── Workspace: "prod"│
│ │ ├── Key: sk-proj-prod... (Hard Cap: $8k) │ └── Hard: $10k/mo│
│ ├── Project: "internal-slack-bot" ├── Workspace: "dev" │
│ │ ├── Key: sk-proj-slack... (Hard: $200) │ └── Hard: $500/mo│
│ └── Project: "staging-evals" └── Workspace: "eval"│
│ └── Key: sk-proj-stage... (Hard: $500) └── Hard: $1k/mo │
└────────────────────────────────────────────────────────────────────────┘
OpenAI Organizations & Projects
OpenAI provides OpenAI Projects to organize API usage within an organization.
Teams create scoped Service Account Keys assigned to specific projects rather than individual user accounts:
- Open OpenAI Platform Settings -> Projects.
- Create dedicated projects for each initiative (such as
prod-copilot,prod-rag,staging-evals, andinternal-tools). - Generate a Project-Scoped Service Key within each project (prefixed with
sk-proj-).
Specifying Projects in the OpenAI SDK
Pass the explicit project identifier when initializing the client:
// openai-client.ts
import OpenAI from "openai";
// Scoped strictly to the Customer Copilot initiative
export const copilotOpenAI = new OpenAI({
apiKey: process.env.OPENAI_COPILOT_API_KEY, // sk-proj-...
project: process.env.OPENAI_PROJECT_ID, // proj_abc123...
});
When using direct HTTP requests, include the project header:
POST /v1/chat/completions HTTP/1.1
Host: api.openai.com
Authorization: Bearer sk-proj-...
OpenAI-Project: proj_abc123def456
Content-Type: application/json
In the OpenAI Usage Dashboard, select the project filter to review token usage and dollar costs for that specific initiative.
Anthropic Workspaces
Anthropic provides workspace isolation in the Anthropic Console -> Workspaces:
- Create dedicated workspaces for specific teams or environments (such as
Production Backend,Research & Fine-Tuning, andInternal Agents). - Each workspace maintains its own API Keys, Monthly Spend Limits, and Rate Limits (Tokens Per Minute).
API Key Isolation Rule
Never share API keys across production, staging, and local development environments.
Running a local evaluation batch of 500 prompts against your most expensive model using a production key can incur hundreds of dollars in minutes. Isolate non-production keys into dedicated workspaces with a strict $50.00 monthly hard limit.
2. 2026 Model Economics: Token Pricing & Prompt Caching
Tracking costs across multiple projects requires understanding modern model pricing structures.
In 2026, model billing includes input tokens, output tokens, reasoning tokens, and prompt caching rates.
Claude Pricing Reference
| Model Name | Standard Input (per 1M) | Output Tokens (per 1M) | Prompt Cache Write (per 1M) | Prompt Cache Read (per 1M) |
|---|---|---|---|---|
| Claude 3 Opus | $15.00 | $75.00 | $18.75 (+25%) | $1.50 (90% discount) |
| Claude 3.5 Sonnet | $3.00 | $15.00 | $3.75 (+25%) | $0.30 (90% discount) |
| Claude 3.5 Haiku | $0.80 | $4.00 | $1.00 (+25%) | $0.08 (90% discount) |
Claude prices are from Anthropic's pricing page, as of November 2026. Cache writes use the 5-minute rate. For OpenAI models, take current prices from OpenAI's pricing page on the day you build your price table. OpenAI applies prompt caching automatically and bills cached input at a lower rate. |
Prompt Caching Economics
Prompt caching creates significant price differences on Anthropic Claude 3.5 Sonnet:
- Standard Input Token Price: $3.00 per million.
- Cache Read Token Price: $0.30 per million (a 90% discount).
┌────────────────────────────────────────────────────────────────────────┐
│ THE PROMPT CACHING COST PARADOX │
├────────────────────────────────────────────────────────────────────────┤
│ Scenario: You run a Codebase Assistant querying 50,000 tokens of │
│ documentation on every user prompt. │
│ │
│ WITHOUT PROMPT CACHING (100 Requests): │
│ 50,000 input tokens × 100 requests = 5,000,000 tokens │
│ 5M tokens × $3.00/M = $15.00 │
│ │
│ WITH PROMPT CACHING (1 Write + 99 Cache Reads): │
│ • Initial Write: 50,000 tokens × $3.75/M = $0.1875 │
│ • 99 Cache Reads: 4,950,000 × $0.30/M = $1.4850 │
│ ─────────────────────────────────────────────────── │
│ TOTAL COST: $1.67 (89% Net Savings!) │
└────────────────────────────────────────────────────────────────────────┘
When an application uses prompt caching (such as setting cache_control: { type: "ephemeral" } on system prompts in Anthropic), input token expenses decrease by up to 90 percent.
If an internal telemetry script calculates input costs using standard $3.00/M rates, it will overstate expenses. It will report $15.00 in costs when Anthropic billed $1.67.
Accurate cost tracking requires recording both cache_read_input_tokens and cache_creation_input_tokens.
3. Runtime Metadata Tagging: Tracking Features Within Projects
Project keys isolate costs at the macro level between distinct products.
Inside a single project, teams often need granular feature-level tracking:
- Measuring the cost of a "Weekly Report Generator" versus an interactive chat feature.
- Tracking consumption driven by a specific customer account.
Both OpenAI and Anthropic support metadata tags in API requests.
OpenAI: The user Parameter
OpenAI API endpoints accept an optional user string parameter.
Encode metadata into this parameter using a structured format:
// openai-tagged.ts
import OpenAI from "openai";
const openai = new OpenAI();
export async function callOpenAIWithMetadata(params: {
prompt: string;
projectId: string;
featureName: string;
workspaceId: string;
}) {
// Format: proj_{projectId}__feat_{feature}__ws_{workspaceId}
const userTag = `proj_${params.projectId}__feat_${params.featureName}__ws_${params.workspaceId}`;
const response = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL!, // the OpenAI model you use
messages: [{ role: "user", content: params.prompt }],
user: userTag,
});
return response;
}
Anthropic: The metadata.user_id Parameter
Anthropic Messages API requests accept metadata inside metadata: { user_id: string }:
// claude-tagged.ts
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic();
export async function callClaudeWithMetadata(params: {
prompt: string;
featureName: string;
workspaceId: string;
}) {
const metadataTag = `feat_${params.featureName}__ws_${params.workspaceId}`;
const response = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [{ role: "user", content: params.prompt }],
metadata: {
user_id: metadataTag,
},
});
return response;
}
These tags don't add cost breakdowns to the provider dashboards. Anthropic uses metadata.user_id to help detect abuse and asks for an opaque ID, never a name or email. To report cost by feature, log each response's usage with your feature name in your own database.
4. Runaway Loops: Protecting Against Autonomous Agent Disasters
Autonomous agent loops present a major financial risk in AI application development.
In traditional software, an infinite loop consumes CPU cycles until a container restarts.
In agentic systems, an agent with tool-calling access that hits recurring errors can trigger thousands of sequential multi-turn API calls:
┌────────────────────────────────────────────────────────────────────────┐
│ THE RUNAWAY AGENT RECURSION DISASTER │
├────────────────────────────────────────────────────────────────────────┤
│ Step 1: Agent decides to call `search_database()` tool. │
│ Step 2: Database returns an unexpected SQL syntax error. │
│ Step 3: LLM inspects error: "I will retry with modified syntax." │
│ Step 4: Modified query fails with another permission error. │
│ Step 5: LLM retries again... and again... and again... │
│ │
│ In 15 minutes: │
│ • 850 Multi-Turn Completions executed │
│ • Context accumulates to 90,000 tokens per request │
│ • 76,500,000 input tokens on Claude 3.5 Sonnet ($3.00 per million) │
│ • FINANCIAL DAMAGE: $229.50 for a single failed user query! │
└────────────────────────────────────────────────────────────────────────┘
The 4-Tier Runaway Loop Defense System
An agent execution pipeline requires multiple safeguards:
LAYER 1: Hard Max Output Tokens (`max_tokens: 2048`)
LAYER 2: Maximum Execution Turns (`MAX_TURNS = 10`)
LAYER 3: State Hash Detection (Catches repeating loops)
LAYER 4: Real-Time Sliding Budget Windows (Redis atomic spend caps)
Production TypeScript: Resilient Agent Loop Executor
This wrapper includes turn counters, output token ceilings, and state hashing to stop repetitive loops:
// safe-executor.ts
import crypto from "crypto";
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic();
export interface AgentStepResult {
role: "user" | "assistant";
content: any;
}
export async function executeAgentSafely(params: {
systemPrompt: string;
userPrompt: string;
tools: any[];
maxTurns?: number; // Default: 10 turns max
projectId: string;
}) {
const maxTurns = params.maxTurns || 10;
const messages: any[] = [{ role: "user", content: params.userPrompt }];
// Track tool-call signatures to detect identical repeating loops
const executionHistoryHashes = new Set<string>();
let totalInputTokens = 0;
let totalOutputTokens = 0;
for (let turn = 1; turn <= maxTurns; turn++) {
// 1. Enforce strict output token boundary
const response = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 2048,
system: params.systemPrompt,
messages,
tools: params.tools,
});
totalInputTokens += response.usage.input_tokens;
totalOutputTokens += response.usage.output_tokens;
// Check if the agent is finished (no tool calls)
if (response.stop_reason !== "tool_use") {
return {
success: true,
finalMessage: response.content,
turnsUsed: turn,
totalTokens: totalInputTokens + totalOutputTokens,
};
}
// 2. Extract tool-calling payload and generate state hash
const toolUseBlocks = response.content.filter(
(c): c is Anthropic.ToolUseBlock => c.type === "tool_use",
);
// Hash only the tool name and input. Each block's id is unique, so including it would never repeat.
const stateSignature = JSON.stringify(toolUseBlocks.map((b) => ({ name: b.name, input: b.input })));
const stateHash = crypto.createHash("sha256").update(stateSignature).digest("hex");
// 3. CIRCUIT BREAKER: Detect repeating identical tool invocations
if (executionHistoryHashes.has(stateHash)) {
console.error(`[AI Circuit Breaker] Identical repeating tool state detected on turn ${turn}. Aborting!`);
throw new Error(`Runaway loop terminated: Agent repeated identical action twice.`);
}
executionHistoryHashes.add(stateHash);
// Append assistant response to conversational thread
messages.push({ role: "assistant", content: response.content });
// Execute mock tool and return results
const toolResults = await executeMockTools(toolUseBlocks);
messages.push({ role: "user", content: toolResults });
}
throw new Error(`Agent exceeded maximum execution turn limit (${maxTurns}). Aborted to protect budget.`);
}
async function executeMockTools(toolBlocks: any[]): Promise<any[]> {
return toolBlocks.map((block) => ({
type: "tool_result",
tool_use_id: block.id,
content: JSON.stringify({ status: "success", data: "Processed payload" }),
}));
}
5. Programmatic Auditing through the OpenAI Administration API
Rather than inspecting usage dashboards manually, developers can pull consumption metrics through the API.
The OpenAI Administration Usage API (/v1/organization/usage) provides hourly or daily token summaries grouped by project, model, or API key:
GET https://api.openai.com/v1/organization/usage/completions
?start_time=1700000000
&end_time=1700086400
&group_by=project_id
&bucket_width=1d
Production TypeScript: Fetching Daily Token Usage per Project
This endpoint returns token counts. For dollar amounts, call /v1/organization/costs with the same Admin key.
// openai-admin-usage.ts
export interface ProjectDailyUsage {
projectId: string;
model: string;
inputTokens: number;
outputTokens: number;
totalTokens: number;
}
export async function fetchOpenAIProjectUsage(params: {
adminKey: string; // Admin key (sk-admin-...)
startTimeUnix: number;
endTimeUnix: number;
projectId?: string;
}): Promise<ProjectDailyUsage[]> {
const url = new URL("https://api.openai.com/v1/organization/usage/completions");
url.searchParams.append("start_time", params.startTimeUnix.toString());
url.searchParams.append("end_time", params.endTimeUnix.toString());
url.searchParams.append("bucket_width", "1d");
url.searchParams.append("group_by", "project_id");
url.searchParams.append("group_by", "model");
if (params.projectId) {
url.searchParams.append("project_id", params.projectId);
}
const response = await fetch(url.toString(), {
method: "GET",
headers: {
"Authorization": `Bearer ${params.adminKey}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`[OpenAI Admin API] Failed to fetch usage: ${response.statusText}`);
}
const data = await response.json();
const results: ProjectDailyUsage[] = [];
for (const bucket of data.data || []) {
for (const result of bucket.results || []) {
results.push({
projectId: result.project_id || "default",
model: result.model || "unknown",
inputTokens: result.input_tokens || 0,
outputTokens: result.output_tokens || 0,
totalTokens: (result.input_tokens || 0) + (result.output_tokens || 0),
});
}
}
return results;
}
6. Full-Stack FinOps: Syncing Usage into RealMRR
Tracking token consumption answers technical questions about infrastructure volume.
Founders must also answer strategic financial questions:
- Did a product that cost $4,200 in Claude API tokens generate $20,000 in subscription revenue, or did it produce $3,500?
Revenue analytics built on Stripe or Paddle data shows what customers paid. It does not include what you paid for AI models or cloud hosting.
┌─────────────────────────────────────────────────────────────────┐
│ ILLUSTRATIVE EXAMPLE: ONE PRODUCT IN REALMRR │
│ │
│ Revenue (Stripe, Paddle or Lemon Squeezy): $38,500.00 │
│ AI costs (OpenAI project + Anthropic workspace): -$8,420.00 │
│ Hosting (AWS + Cloudflare): -$2,150.00 │
│ ─────────────────────────────────────────────────────────── │
│ Profit: $27,930.00 │
│ Margin: 72.5% │
└─────────────────────────────────────────────────────────────────┘
RealMRR connects incoming revenue with actual infrastructure costs.
Founders connect OpenAI and Anthropic with an organization Admin key in the RealMRR workspace. RealMRR maps OpenAI spend by project and Anthropic spend by workspace to your products. Anything it can't map shows as "Unassigned".
RealMRR reads revenue from Stripe, Paddle or Lemon Squeezy and shows revenue, costs and profit for each product. It syncs every 6 hours on the Free plan and every hour on Plus and Scale.
7. The Engineering FinOps Checklist
Review this checklist before deploying new AI workflows:
1. Organizational & Key Isolation
- Separate OpenAI Projects created for Production, Staging, and Internal Tools.
- Dedicated Anthropic Workspaces configured with independent spend limits.
- Staging and development keys limited to hard monthly spend caps ($50/month).
- No shared root administrative API keys used in application source code.
2. Token Pricing & Prompt Caching
- Telemetry scripts account for prompt caching discounts ($0.30/1M on Claude 3.5 Sonnet).
- High-volume system prompts use
cache_control: { type: "ephemeral" }to optimize cache hit rates.
3. Circuit Breakers & Runaway Protection
- Every LLM API call specifies an explicit
max_tokenslimit. - Multi-turn autonomous agents enforce maximum turn limits (
MAX_TURNS = 10). - State hashing stops repeating tool-call recursion loops.
- Redis sliding spend caps track daily workspace budgets.
4. Macro Financial Verification
- Connect your payment and AI providers to RealMRR to see AI and hosting costs next to revenue for each product.
8. Summary: Establish Project-Level Visibility
Building AI software requires monitoring costs for every API call.
Segment project keys, record prompt caching discounts, add recursion circuit breakers, and monitor net margins to protect product profitability.
Connect your payment and AI infrastructure to RealMRR to maintain clear financial visibility and build a sustainable software business.
Related Reading
- How to Track and Allocate OpenAI & Anthropic API Costs Per User
- A Minimalist Founder's Guide to AWS Cost Explorer
- Why $20k MRR Can Still Leave You Broke: The Broken Unit Economics of AI Wrappers
- RealMRR vs Baremetrics vs ProfitWell: Why Subscription Analytics Fail Modern AI Apps
- How to Reconcile Stripe Payouts with QuickBooks or Xero Without Going Crazy
Know your real profit today.
Connect your payment gateway and cloud bills to get verified profit rankings, automated bookkeeping, and zero guesswork.