LangChain
LangChain, a framework for building language model applications, integrates seamlessly with OpenMeter. Tracking and attributing token usage to users is crucial for precise billing, real-time usage dashboards and operational insights in language model operations.
Setup
To integrate OpenMeter with your LangChain application, start by installing the OpenMeter Node.js SDK:
Next, create a file for the OpenMeter handler. This implementation serves as a foundation and can be tailored to meet specific requirements:
Note: Some language models may not provide token usage information in the LLM output. Please verify this with your specific model documentation. Custom token counting can be implemented by using the
js-tiktoken
library.
Usage
Node.js
Next.js and Vercel's AI library
The following example demonstrates how to integrate OpenMeter with a Next.js application using the Vercel's AI library.
How it works
LangChain callbacks
LangChain provides a callbacks system that allows you to hook into the various stages of your LLM application. This is useful for logging, monitoring, streaming, and other tasks.
OpenMeterCallbackHandler
is responsible for capturing the token usage of
language model operations and reporting this data to OpenMeter as events. The
handler captures the start and end of language model operations.
It operates at two key stages:
-
Start of the Language Model Operation (
handleLLMStart
): At this point, the handler captures and stores themetadata
of the current chain execution. -
End of the Language Model Operation (
handleLLMEnd
): This is where the handler extracts information such as the number of prompt tokens, completion tokens from the language model's output (tokenUsage
orestimatedTokenUsage
for streaming requests) and sends two events (input and output) to OpenMeter.
Event Structure
The OpenMeter events will have the following structure:
type
: Indicates the tokens type. Input tokens are tokens used in the prompt, while output tokens are tokens used in the completion.tokens
: Number of tokens.
The subject
field associates the event with a specific customer or operation,
aiding in billing and analysis.