Installation
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 usingwrapLanguageModel from the ai package and pass the createOpenRouterV3Middleware.
1
Initialize the OpenRouter provider
First, set up the OpenRouter provider using your 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.3
Wrap the model
Use
wrapLanguageModel from the ai package to apply the billing middleware to your OpenRouter model.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.