Skip to main content

Installation

npm install @ai-billing/openrouter @ai-billing/core @openrouter/ai-sdk-provider ai

Overview

The @ai-billing/openrouter package provides middleware for tracking token usage and calculating costs when using OpenRouter models with the Vercel AI SDK.

Usage

To use the middleware, wrap your OpenRouter model using wrapLanguageModel from the ai package and pass the createOpenRouterV3Middleware.
1

Initialize the OpenRouter provider

First, set up the OpenRouter provider using your API key.
import { createOpenRouter } from '@openrouter/ai-sdk-provider';

const openrouter = createOpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});
2

Create the billing middleware

Initialize the OpenRouter billing middleware. You need to provide a destination (such as consoleDestination) where billing events will be sent.
import { createOpenRouterV3Middleware } from '@ai-billing/openrouter';
import { consoleDestination } from '@ai-billing/core';

const billingMiddleware = createOpenRouterV3Middleware({
  destinations: [consoleDestination()],
});
3

Wrap the model

Use wrapLanguageModel from the ai package to apply the billing middleware to your OpenRouter model.
import { wrapLanguageModel } from 'ai';

const wrappedModel = wrapLanguageModel({
  model: openrouter('google/gemini-2.0-flash-001'),
  middleware: billingMiddleware,
});
4

Use the wrapped model

Finally, use the wrapped model with AI SDK functions like generateText or streamText. The billing middleware will automatically track tokens and handle metrics.
import { generateText } from 'ai';

const result = await generateText({
  model: wrappedModel,
  prompt: 'What is the capital of Sweden?',
});