> ## 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.

# Introduction

> Middleware for the Vercel AI SDK that sends usage events directly to billing platforms like Stripe, Polar, OpenMeter, and Lago.

# AI Billing

Middleware for the [Vercel AI SDK](https://sdk.vercel.ai/docs) 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.

<CardGroup cols={2}>
  <Card title="Provider-aware metrics" icon="microchip">
    Understands provider-specific metrics like reasoning tokens, prompt caching, and web search costs so you don't miss a cent.
  </Card>

  <Card title="Flexible cost calculation" icon="calculator">
    Use native provider pricing (like OpenRouter), hardcoded price maps, or real-time cost resolution via Narev.
  </Card>

  <Card title="Multiple destinations" icon="arrows-split-up-and-left">
    Format and forward usage seamlessly to Stripe, Polar, OpenMeter, Lago, or your own endpoint — all at once.
  </Card>

  <Card title="Drop-in middleware" icon="plug">
    Works with `wrapLanguageModel` — no changes to your existing `streamText` / `generateText` calls.
  </Card>
</CardGroup>

## Install

<CodeGroup>
  ```bash npm theme={null}
  npm install @ai-billing/core
  ```

  ```bash pnpm theme={null}
  pnpm add @ai-billing/core
  ```

  ```bash yarn theme={null}
  yarn add @ai-billing/core
  ```
</CodeGroup>

Then, install the package for your specific AI provider (e.g., `@ai-billing/openai`) and your billing destination (e.g., `@ai-billing/stripe`). See [Provider middleware](#provider-middleware) 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.

```typescript theme={null}
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.

```typescript theme={null}
import { createOpenAIMiddleware } from '@ai-billing/openai';
import { createNarevPriceResolver } from '@ai-billing/narev';

// 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`.

```typescript theme={null}
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.

```typescript theme={null}
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:

<Steps>
  <Step title="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`.
  </Step>

  <Step title="Price resolvers">
    Functions that turn token metrics into precise financial costs. Use `createNarevPriceResolver` from `@ai-billing/narev` for live Narev rates, `createObjectPriceResolver` from `@ai-billing/core` for custom mappings, or skip this entirely if your provider (like OpenRouter or Vercel AI Gateway) reports costs natively.
  </Step>

  <Step title="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.
  </Step>
</Steps>

## Packages

Every published `@ai-billing` package has generated TypeDoc reference docs under `/sdk/ai-billing/reference/<package>/typedoc/index`.

### Core and integrations

| Package | Role |
| :- | :- |
| [`@ai-billing/core`](/docs/sdk/ai-billing/reference/core/typedoc/index) | V3/V4 billing middleware, destinations, price resolvers, and shared types |
| [`@ai-billing/narev`](/docs/sdk/ai-billing/reference/narev/typedoc/index) | Narev pricing API client and `createNarevPriceResolver` |
| [`@ai-billing/nextjs`](/docs/sdk/ai-billing/reference/nextjs/typedoc/index) | Next.js chat UI, Polar/Stripe credit components, and `create*WithBilling` server factories |

### Provider middleware

Text model support is the current priority. Each package ships V3 and V4 middleware.

| Provider | Package | Features |
| :- | :- | :- |
| [Alibaba](https://ai-sdk.dev/providers/community-providers/alibaba) | [`@ai-billing/alibaba`](/docs/sdk/ai-billing/reference/alibaba/typedoc/index) | Caching, Reasoning |
| [Amazon Bedrock](https://ai-sdk.dev/providers/ai-sdk-providers/amazon-bedrock) | [`@ai-billing/amazon-bedrock`](/docs/sdk/ai-billing/reference/amazon-bedrock/typedoc/index) | Caching |
| [Anthropic](https://ai-sdk.dev/providers/ai-sdk-providers/anthropic) | [`@ai-billing/anthropic`](/docs/sdk/ai-billing/reference/anthropic/typedoc/index) | Caching |
| [Azure](https://ai-sdk.dev/providers/ai-sdk-providers/azure) | [`@ai-billing/azure`](/docs/sdk/ai-billing/reference/azure/typedoc/index) | Caching, Reasoning |
| [Baseten](https://www.baseten.co/) | [`@ai-billing/baseten`](/docs/sdk/ai-billing/reference/baseten/typedoc/index) | |
| [Cerebras](https://ai-sdk.dev/providers/ai-sdk-providers/cerebras) | [`@ai-billing/cerebras`](/docs/sdk/ai-billing/reference/cerebras/typedoc/index) | Caching, Reasoning |
| [Chutes](https://chutes.ai) | [`@ai-billing/chutes`](/docs/sdk/ai-billing/reference/chutes/typedoc/index) | Caching |
| [Cohere](https://ai-sdk.dev/providers/ai-sdk-providers/cohere) | [`@ai-billing/cohere`](/docs/sdk/ai-billing/reference/cohere/typedoc/index) | |
| [DeepInfra](https://ai-sdk.dev/providers/community-providers/deepinfra) | [`@ai-billing/deepinfra`](/docs/sdk/ai-billing/reference/deepinfra/typedoc/index) | Caching |
| [DeepSeek](https://ai-sdk.dev/providers/community-providers/deepseek) | [`@ai-billing/deepseek`](/docs/sdk/ai-billing/reference/deepseek/typedoc/index) | Caching, Reasoning |
| [Fireworks](https://ai-sdk.dev/providers/ai-sdk-providers/fireworks) | [`@ai-billing/fireworks`](/docs/sdk/ai-billing/reference/fireworks/typedoc/index) | Caching, Reasoning |
| [Vercel AI Gateway](https://ai-sdk.dev/providers/ai-sdk-providers/ai-gateway) | [`@ai-billing/gateway`](/docs/sdk/ai-billing/reference/gateway/typedoc/index) | Native pricing |
| [GMI Cloud](https://gmicloud.ai/) | [`@ai-billing/gmicloud`](/docs/sdk/ai-billing/reference/gmicloud/typedoc/index) | Caching, Reasoning |
| [Google](https://ai-sdk.dev/providers/ai-sdk-providers/google) | [`@ai-billing/google`](/docs/sdk/ai-billing/reference/google/typedoc/index) | Caching, Reasoning |
| [Google Vertex AI](https://ai-sdk.dev/providers/ai-sdk-providers/google-vertex) | [`@ai-billing/google-vertex`](/docs/sdk/ai-billing/reference/google-vertex/typedoc/index) | Caching, Reasoning |
| [Groq](https://ai-sdk.dev/providers/ai-sdk-providers/groq) | [`@ai-billing/groq`](/docs/sdk/ai-billing/reference/groq/typedoc/index) | Caching |
| [Hugging Face](https://ai-sdk.dev/providers/ai-sdk-providers/huggingface) | [`@ai-billing/huggingface`](/docs/sdk/ai-billing/reference/huggingface/typedoc/index) | Caching, Reasoning |
| [Minimax](https://ai-sdk.dev/providers/community-providers/minimax) | [`@ai-billing/minimax`](/docs/sdk/ai-billing/reference/minimax/typedoc/index) | Reasoning |
| [Mistral](https://ai-sdk.dev/providers/ai-sdk-providers/mistral) | [`@ai-billing/mistral`](/docs/sdk/ai-billing/reference/mistral/typedoc/index) | Caching |
| [Moonshot AI](https://ai-sdk.dev/providers/community-providers/moonshotai) | [`@ai-billing/moonshotai`](/docs/sdk/ai-billing/reference/moonshotai/typedoc/index) | Caching, Reasoning |
| [OpenAI](https://ai-sdk.dev/providers/ai-sdk-providers/openai) | [`@ai-billing/openai`](/docs/sdk/ai-billing/reference/openai/typedoc/index) | Caching, Search |
| [OpenAI Compatible](https://ai-sdk.dev/providers/openai-compatible-providers) | [`@ai-billing/openai-compatible`](/docs/sdk/ai-billing/reference/openai-compatible/typedoc/index) | Caching, Reasoning |
| [OpenRouter](https://ai-sdk.dev/providers/community-providers/openrouter) | [`@ai-billing/openrouter`](/docs/sdk/ai-billing/reference/openrouter/typedoc/index) | Native pricing |
| [Perplexity](https://ai-sdk.dev/providers/ai-sdk-providers/perplexity) | [`@ai-billing/perplexity`](/docs/sdk/ai-billing/reference/perplexity/typedoc/index) | Reasoning, Search fee |
| [Together AI](https://ai-sdk.dev/providers/ai-sdk-providers/togetherai) | [`@ai-billing/togetherai`](/docs/sdk/ai-billing/reference/togetherai/typedoc/index) | Reasoning |
| [xAI](https://ai-sdk.dev/providers/ai-sdk-providers/xai) | [`@ai-billing/xai`](/docs/sdk/ai-billing/reference/xai/typedoc/index) | Caching, Reasoning |
| [Z.ai](https://z.ai/) | [`@ai-billing/zai`](/docs/sdk/ai-billing/reference/zai/typedoc/index) | Caching, Reasoning |

### Billing destinations

| Destination | Package | Format |
| :- | :- | :- |
| Stripe | [`@ai-billing/stripe`](/docs/sdk/ai-billing/reference/stripe/typedoc/index) | Meter events, nano-dollars |
| Polar.sh | [`@ai-billing/polar`](/docs/sdk/ai-billing/reference/polar/typedoc/index) | Polar events, nano-dollars |
| OpenMeter | [`@ai-billing/openmeter`](/docs/sdk/ai-billing/reference/openmeter/typedoc/index) | CloudEvents |
| Lago | [`@ai-billing/lago`](/docs/sdk/ai-billing/reference/lago/typedoc/index) | Lago events, nano-dollars |
| Console | [`@ai-billing/core`](/docs/sdk/ai-billing/reference/core/typedoc/index) | `consoleDestination` debug logging |

### Roadmap

> **Note:** We are prioritizing support for **text models**.

**Active development**

* [Requesty](https://ai-sdk.dev/providers/community-providers/requesty)
* [Cloudflare AI Gateway](https://ai-sdk.dev/providers/community-providers/cloudflare-ai-gateway)

To prioritize a provider that is not listed above, [open a GitHub issue](https://github.com/narevai/ai-billing/issues).

## Reference

<CardGroup cols={2}>
  <Card title="Core primitives" icon="boxes-stacked" href="/docs/sdk/ai-billing/reference/core/typedoc/index">
    Middleware, destinations, price resolvers, and shared types in `@ai-billing/core`.
  </Card>

  <Card title="Narev pricing client" icon="coins" href="/docs/sdk/ai-billing/reference/narev/typedoc/index">
    `createNarevClient`, `createNarevPriceResolver`, and trace cost helpers in `@ai-billing/narev`.
  </Card>

  <Card title="Next.js components" icon="react" href="/docs/sdk/ai-billing/reference/nextjs/typedoc/index">
    Chat UI, credit usage widgets, and server factories in `@ai-billing/nextjs`.
  </Card>

  <Card title="Full API reference" icon="book-open" href="/docs/sdk/ai-billing/reference/openai/typedoc/index">
    Browse the sidebar for every provider, destination, and integration package.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.