costhq/middleware module lets you add cost tracking to existing code without swapping out client instances. Instead of replacing new OpenAI() with new TrackedOpenAI(), you wrap individual functions or entire client objects at the point where tracking makes sense for your architecture.
Import
withTracking
withTracking wraps any async function and records its token usage to the active CostHQ session. The wrapped function has an identical call signature to the original — no call sites change.
BatchTracker
BatchTracker tracks multiple calls that all share the same provider and model. Construct it once, then call .track() for each API call in your loop or batch.
.track() is the same tokenExtractor as in withTracking. If you omit it, BatchTracker falls back to the same dual-format default (OpenAI and Anthropic usage shapes).
createTrackedClient
createTrackedClient wraps an existing client object so that every method call on the returned object is automatically tracked — no function-by-function wrapping needed.