Skip to main content

Installation

Overview

The @ai-billing/openai package provides middleware for tracking token usage and calculating costs when using OpenAI models with the Vercel AI SDK. It captures OpenAI-specific metrics, such as inputCacheReadTokens (for Prompt Caching) and webSearch (for search-enabled models), ensuring that all costs are accurately reflected.

Usage

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

Initialize the OpenAI provider

First, set up the OpenAI provider using your API key.
2

Define model pricing

Set up a price resolver to define the costs for the models you’ll be using. For OpenAI, you can specify costs for standard prompt/completion tokens, cached tokens (inputCacheReadTokens), and even webSearch usage.
Using a Remote Pricing Provider (Narev):Instead of hardcoding prices, you can use a remote pricing provider like Narev to automatically fetch up-to-date pricing.
3

Create the billing middleware

Initialize the OpenAI billing middleware. You need to provide a destination (such as consoleDestination) where billing events will be sent, along with your priceResolver.
4

Wrap the model

Use wrapLanguageModel from the ai package to apply the billing middleware to your OpenAI model.
5

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 calculate costs.

Advanced Usage

Web Search Models

When using models with web search capabilities like gpt-4o-search-preview, you can track the search costs by adding webSearch to your custom pricing map.