liveBook · Manning

Token tracking system

As explained in Build AI-Enhanced Web Apps

Token usage tracking is the collection of token-consumption measurements from language-model calls.

A token tracking system collects token-consumption measurements from language-model calls so applications can manage costs across multi-call workflows. It is especially useful when documents exceed a model’s context window and require several requests. section 7.1.4

A practical implementation combines a TokenTracker instance with an LLM callback. When a call completes, handleLLMEnd reads usage metadata from the returned message, updates the tracker, and exposes current usage and token differences. The tracker can later export metrics to an analytics service. section 7.1.4

Tracking Gemini usage

Create a TokenTracker, attach handleLLMEnd to a ChatGoogleGenerativeAI model, pass message.usage_metadata to updateTokens, and log getCurrentUsage() and getTokenDiff().

Message metadata provides broader provider coverage than output.llmOutput?.tokenUsage, which may be model-limited; js-tiktoken currently supports OpenAI models but not Google Gemini models. section 7.1.4

How Build AI-Enhanced Web Apps covers it

How deep it goes
Explains callback wiring, message metadata, tracker updates, and provider limitations without detailing tracker internals.
Examples
Uses a JavaScript TokenTracker with ChatGoogleGenerativeAI, Gemini 2.0 Flash, handleLLMEnd, and usage logging.
What it assumes
Assumes language-model API calls and callbacks, while demonstrating token tracking from usage metadata.
What you can do after
Operate callback-based usage monitoring and inspect current token totals and per-call differences.
How it connects
Connects token usage tracking with LLM callbacks, context windows, cost management, message metadata, and analytics services.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build AI-Enhanced Web Apps. The section links point to the parts of the book it draws on.