How do you calculate accurate per-request USD cost tracking across multiple LLM providers in middleware? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you calculate accurate per-request USD cost tracking across multiple LLM providers in middleware?

message-square
0

How Per-Request Cost Tracking Works Across Providers

Accurate per-request cost tracking in middleware requires reading each provider’s actual post-response usage report rather than relying solely on local token counts. Tokenizers estimate strings, while provider usage fields capture server-side accounting for cached prefixes, reasoning/thinking tokens, and context tiers.

  • Split input into distinct buckets: Separate uncached input tokens from cache reads and cache writes so you do not double-charge cached tokens at the full input rate.
  • Watch how reasoning tokens are reported: Reasoning/thinking tokens are billed at output token rates. Check whether a provider’s output count already includes reasoning tokens so you do not add them twice.
  • Apply context-length and tier multipliers: Some models charge higher rates above a context threshold (such as >200K tokens) or apply multipliers for Batch, Flex, or Priority tiers.
  • Use high-precision decimals: Individual calls often cost fractions of a cent (e.g., $0.00042). Store exact numeric USD floats or scaled micro-dollars in telemetry, and format to 6+ decimal places in logs.

Provider Usage Mapping & Cost Formula

Provider Uncached Input Cached Read Cache Write Billable Output (incl. Reasoning)
OpenAI input_tokens - cached_tokens (or prompt_tokens - cached) input_tokens_details.cached_tokens cache_write_tokens (when applicable) output_tokens (already includes output_tokens_details.reasoning_tokens)
Anthropic input_tokens cache_read_input_tokens cache_creation_input_tokens output_tokens
Gemini promptTokenCount - cachedContentTokenCount cachedContentTokenCount Separate storage rate ($/1M/hr) if explicit cache used candidatesTokenCount + thoughtsTokenCount

For any normalized token breakdown, cost per 1M tokens is:

$$\text{Cost}{\text{USD}} = \frac{u{\text{in}} \cdot r_{\text{in}} + u_{\text{cached}} \cdot r_{\text{cached}} + u_{\text{write}} \cdot r_{\text{write}} + u_{\text{out}} \cdot r_{\text{out}}}{1{,}000{,}000}$$

Steps to Build Middleware Cost Tracking

  1. Normalize usage into a single internal structure: Map OpenAI, Anthropic, and Gemini responses into { uncachedInput, cacheRead, cacheWrite, output }.
  2. Maintain a versioned pricing table by model and tier: Store rates per 1M tokens (plus any long-context threshold or tier multiplier) in config rather than hardcoding scattered math.
  3. Compute cost right after each response (or final stream chunk): Attach provider, model, usage, and costUsd to your request context/telemetry record.
  4. Track non-token charges separately: Built-in tools (such as web search/grounding) or cache storage hours are billed differently than per-token inference.

TypeScript Middleware Example

export type ProviderName = "openai" | "anthropic" | "gemini";

export interface NormalizedUsage {
  uncachedInput: number;
  cacheRead: number;
  cacheWrite: number;
  output: number;
}

export interface ModelRateCard {
  inputPer1M: number;
  cachedReadPer1M: number;
  cacheWritePer1M: number;
  outputPer1M: number;
  longContextThresholdTokens?: number;
  longContextMultiplier?: number;
}

export interface CostRecord {
  requestId: string;
  provider: ProviderName;
  model: string;
  usage: NormalizedUsage;
  costUsd: number;
}

// Example per-1M USD rate table (keep synced with current provider pricing)
const RATE_CARDS: Record<string, ModelRateCard> = {
  "gpt-4o-mini": {
    inputPer1M: 0.15,
    cachedReadPer1M: 0.075,
    cacheWritePer1M: 0.15,
    outputPer1M: 0.6,
  },
  "claude-sonnet-4-6": {
    inputPer1M: 3.0,
    cachedReadPer1M: 0.3,
    cacheWritePer1M: 3.75,
    outputPer1M: 15.0,
  },
  "gemini-2.5-flash": {
    inputPer1M: 0.3,
    cachedReadPer1M: 0.03,
    cacheWritePer1M: 0,
    outputPer1M: 2.5,
  },
};

export function normalizeUsage(
  provider: ProviderName,
  rawUsage: Record<string, any> = {}
): NormalizedUsage {
  if (provider === "openai") {
    const totalInput = rawUsage.input_tokens ?? rawUsage.prompt_tokens ?? 0;
    const cacheRead =
      rawUsage.input_tokens_details?.cached_tokens ??
      rawUsage.prompt_tokens_details?.cached_tokens ??
      0;
    const cacheWrite = rawUsage.cache_write_tokens ?? 0;
    const output = rawUsage.output_tokens ?? rawUsage.completion_tokens ?? 0;

    return {
      uncachedInput: Math.max(0, totalInput - cacheRead - cacheWrite),
      cacheRead,
      cacheWrite,
      output,
    };
  }

  if (provider === "anthropic") {
    return {
      uncachedInput: rawUsage.input_tokens ?? 0,
      cacheRead: rawUsage.cache_read_input_tokens ?? 0,
      cacheWrite: rawUsage.cache_creation_input_tokens ?? 0,
      output: rawUsage.output_tokens ?? 0,
    };
  }

  // Gemini usageMetadata
  const promptTokens = rawUsage.promptTokenCount ?? 0;
  const cacheRead = rawUsage.cachedContentTokenCount ?? 0;
  const candidates = rawUsage.candidatesTokenCount ?? 0;
  const thoughts = rawUsage.thoughtsTokenCount ?? 0;

  return {
    uncachedInput: Math.max(0, promptTokens - cacheRead),
    cacheRead,
    cacheWrite: 0,
    output: candidates + thoughts,
  };
}

export function calculateCostUsd(
  model: string,
  usage: NormalizedUsage,
  tierMultiplier = 1
): number {
  const rate = RATE_CARDS[model];
  if (!rate) return 0;

  const totalInputTokens =
    usage.uncachedInput + usage.cacheRead + usage.cacheWrite;
  const contextMult =
    rate.longContextThresholdTokens &&
    totalInputTokens > rate.longContextThresholdTokens
      ? (rate.longContextMultiplier ?? 1)
      : 1;

  const inputCost =
    (usage.uncachedInput / 1_000_000) * rate.inputPer1M * contextMult;
  const cacheReadCost =
    (usage.cacheRead / 1_000_000) * rate.cachedReadPer1M * contextMult;
  const cacheWriteCost =
    (usage.cacheWrite / 1_000_000) * rate.cacheWritePer1M * contextMult;
  const outputCost = (usage.output / 1_000_000) * rate.outputPer1M;

  return (inputCost + cacheReadCost + cacheWriteCost + outputCost) * tierMultiplier;
}

export async function withCostTracking<T extends { usage?: Record<string, any> }>(
  requestId: string,
  provider: ProviderName,
  model: string,
  runCall: () => Promise<T>,
  onRecord: (record: CostRecord) => void | Promise<void>
): Promise<T> {
  const response = await runCall();
  const usage = normalizeUsage(provider, response.usage);
  const costUsd = calculateCostUsd(model, usage);

  await onRecord({
    requestId,
    provider,
    model,
    usage,
    costUsd,
  });

  return response;
}

Helpful Tips for Production Cost Middleware

  • Include stream_options: { include_usage: true } on OpenAI streams: Streaming responses omit usage unless you explicitly request it on the final chunk.
  • Reconcile against provider billing/usage APIs: Periodically compare middleware sums against official invoice/usage endpoints to catch pricing changes, tool surcharges, or unmapped model versions early.
  • Record failed/retried attempts separately: Tag retries and failed calls with attempt and status so you can see how much spend goes toward retries or fallbacks versus successful user answers.