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 usingwrapLanguageModel from the ai package and pass the createOpenAIMiddleware.
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 (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.
inputCacheReadTokens), and even webSearch usage.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.Wrap the model
Use
wrapLanguageModel from the ai package to apply the billing middleware to your OpenAI model.Advanced Usage
Web Search Models
When using models with web search capabilities likegpt-4o-search-preview, you can track the search costs by adding webSearch to your custom pricing map.