Skip to main content

Documentation Index

Fetch the complete documentation index at: https://narev.ai/docs/llms.txt

Use this file to discover all available pages before exploring further.

AI Billing

Middleware for the Vercel AI SDK that captures LLM usage, calculates exact costs, and sends normalized billing events directly to your billing platforms. Whether you’re using OpenAI, Anthropic, OpenRouter, or local models, @ai-billing ensures that every token—including prompt caching and reasoning tokens—is precisely measured and billed to the correct user.

Provider-aware metrics

Understands provider-specific metrics like reasoning tokens, prompt caching, and web search costs so you don’t miss a cent.

Flexible cost calculation

Use native provider pricing (like OpenRouter), hardcoded price maps, or real-time cost resolution via Narev.

Multiple destinations

Format and forward usage seamlessly to Stripe, Polar, OpenMeter, Lago, or your own endpoint — all at once.

Drop-in middleware

Works with wrapLanguageModel — no changes to your existing streamText / generateText calls.

Install

npm install @ai-billing/core
Then, install the package for your specific AI provider (e.g., @ai-billing/openai) and your billing destination (e.g., @ai-billing/stripe). See Supported providers below.

Quick start

1. Initialize the destination

Set up the destination where your billing events will be sent. The destination knows exactly how to format the data (e.g., converting to nano-dollars) and map your tags to the correct customer identity for that platform.
import { createStripeDestination } from '@ai-billing/stripe';

const stripeDestination = createStripeDestination({
  apiKey: process.env.STRIPE_SECRET_KEY,
  meterName: 'llm_usage',
});

2. Set up the middleware & price resolution

Initialize the provider middleware. If your provider doesn’t supply costs natively in the API response (like OpenAI or Anthropic), attach a PriceResolver to calculate the cost of the tokens.
import { createOpenAIMiddleware } from '@ai-billing/openai';
import { createNarevPriceResolver } from '@ai-billing/core';

// Automatically fetch up-to-date model pricing
const priceResolver = createNarevPriceResolver({
  apiKey: process.env.NAREV_API_KEY,
});

const billingMiddleware = createOpenAIMiddleware({
  destinations: [stripeDestination],
  priceResolver,
});

3. Wrap your model

Apply the middleware to your language model using the Vercel AI SDK’s wrapLanguageModel.
import { wrapLanguageModel } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });

const model = wrapLanguageModel({
  model: openai('gpt-4o'),
  middleware: billingMiddleware,
});

4. Pass tags during generation

Generate text exactly as you normally would. Use providerOptions to pass ai-billing-tags so the destination knows which customer to bill.
import { streamText } from 'ai';

const { textStream } = await streamText({
  model,
  messages: [{ role: 'user', content: 'Quantify the value of metadata.' }],
  providerOptions: {
    'ai-billing-tags': { 
      stripe_customer_id: 'cus_123', // Used by Stripe to identify the user
      org_name: 'Acme Corp',         // Attached as metadata to the meter event
    },
  },
});
Every completed request now automatically calculates the cost (including caches and reasoning) and emits a formatted event directly to Stripe.

Architecture

The library is built on three composable primitives:
1

Provider middlewares

Specialized middleware for each AI SDK provider (e.g., @ai-billing/openai, @ai-billing/anthropic). These understand provider-specific metadata shapes, extracting standard tokens alongside advanced metrics like inputCacheReadTokens, internalReasoningTokens, and webSearch.
2

Price resolvers

Functions that turn token metrics into precise financial costs. Use the NarevPriceResolver for real-time rates, the ObjectPriceResolver for custom mappings, or skip this entirely if your provider (like OpenRouter) calculates costs natively.
3

Destinations

Functions that receive a normalized BillingEvent and handle the API call to an external billing service (e.g., @ai-billing/stripe, @ai-billing/polar). Destinations ensure that identity mapping, metadata constraints, and cost formatting (like cost_nanos) comply perfectly with each platform’s rules.

Supported providers

Text model support is the current priority.

Status and Roadmap

Note: We are prioritizing support for TEXT models.
Active Development The following providers are planned for future implementation. To prioritize a specific provider, please open a GitHub issue.

Supported destinations

DestinationPackageFormat Requirements
Stripe@ai-billing/stripeMeter Events, Nano-dollars
Polar.sh@ai-billing/polarPolar Events, Nano-dollars
OpenMeter@ai-billing/openmeterCloudEvents
Lago@ai-billing/lagoLago Events, Nano-dollars
Console@ai-billing/coreDebug logging