Installation
Overview
The@ai-billing/lago package provides a destination for sending calculated AI costs and token usage directly to Lago.
It leverages Lago’s events API to track usage and automatically syncs it with your Lago customers based on the tags provided during generation. The destination ensures usage data conforms to Lago’s requirements, specifically formatting the cost into nano-dollars (cost_nanos) and setting the currency alongside the billable metric code (defaults to llm_usage).
Usage
To use the Lago destination, create it with your Lago API key, and then pass it to any billing middleware.Initialize the Lago destination
First, set up the Lago destination using your Lago API key and optionally the base API URL and meter code. You can optionally define a type for your billing tags to ensure type safety.
Set up price resolution
In order for the Lago 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 event to Lago (this will result in an error).Create the billing middleware
Initialize the billing middleware for your preferred provider and include the
lagoDestination 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 is critical when using the Lago destination:- Identity (
external_customer_id): The destination extracts identity from the tags to map the usage event to anexternal_customer_idin Lago. By default, it checks foruserIdorexternalCustomerId. You can also configure a custom key using theexternalCustomerIdKeyoption when creating the destination. If no identity is found, the event is skipped to avoid ingesting anonymous data. - Properties Payload: By default, metadata such as token dimensions and any custom tags are built into the
propertiespayload sent to Lago.cost_nanosandcurrencyare automatically injected into thepropertiespayload based on the resolved cost of the request. You can override the metadata mapping by providing a custommapMetadatafunction.