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

# Getting started

> First steps with OpenRouter middleware for tracking AI costs.

## Installation

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

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

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

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

<Steps>
  <Step title="Initialize the OpenRouter provider">
    First, set up the OpenRouter provider using your API key.

    ```typescript theme={null}
    import { createOpenRouter } from '@openrouter/ai-sdk-provider';

    const openrouter = createOpenRouter({
      apiKey: process.env.OPENROUTER_API_KEY,
    });
    ```
  </Step>

  <Step title="Create the billing middleware">
    Initialize the OpenRouter billing middleware. You need to provide a destination (such as `consoleDestination`) where billing events will be sent.

    ```typescript theme={null}
    import { createOpenRouterV3Middleware } from '@ai-billing/openrouter';
    import { consoleDestination } from '@ai-billing/core';

    const billingMiddleware = createOpenRouterV3Middleware({
      destinations: [consoleDestination()],
    });
    ```
  </Step>

  <Step title="Wrap the model">
    Use `wrapLanguageModel` from the `ai` package to apply the billing middleware to your OpenRouter model.

    ```typescript theme={null}
    import { wrapLanguageModel } from 'ai';

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

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

    ```typescript theme={null}
    import { generateText } from 'ai';

    const result = await generateText({
      model: wrappedModel,
      prompt: 'What is the capital of Sweden?',
    });
    ```
  </Step>
</Steps>
