Installation
Overview
The@ai-billing/openmeter package provides a destination for sending calculated AI costs and token usage to OpenMeter.
Unlike other destinations, OpenMeter ingests usage as CloudEvents. The destination automatically formats the AI SDK usage into CloudEvents, using the event type to identify the meter and the subject to identify the customer. Cost data is sent in nano-dollars (or your base currency) in the data payload, which is merged with other billing metadata.
Usage
To use the OpenMeter destination, initialize it with your API key, then pass it to any billing middleware.Initialize the OpenMeter destination
Set up the destination using your OpenMeter API key. You can optionally customize the
eventType (defaults to llm_usage), apiUrl, and define a type for your billing tags for type safety.Set up price resolution
In order for the OpenMeter destination to send costs, the
cost property on the generated events must be populated.If you are using a provider that returns pricing natively (like OpenRouter or Anthropic), the cost is automatically calculated and you can skip this step.However, if you are using a provider that doesn’t return pricing natively (such as Groq or local models), you must supply a price resolver like Narev or a local object resolver. Without this, the cost will be undefined and the destination cannot send the meter event to OpenMeter.Create the billing middleware
Initialize the billing middleware for your preferred provider and include the
openMeterDestination in the destinations array.Wrap the model
Use
wrapLanguageModel from the ai package to apply the billing middleware to your model.Pass tags during generation
Finally, use the wrapped model with AI SDK functions like
generateText or streamText.Understanding Billing Tags
Theai-billing-tags object has specific requirements for OpenMeter:- Customer Identity (Subject): By default, the destination looks for
userIdoropenMeterCustomerIdin your tags to populate the CloudEventssubject. If omitted, the event is skipped to avoid ingesting anonymous data. You can override this by providingcustomerIdKeyin the destination options. - Data Payload: Metadata (like
model_id,input_tokens, and your custom tags such asorg_name) are merged along withcost_nanosandcurrencyinto thedatafield of the CloudEvent.