What this thread does
Attach one usage callback to the feature entry point, identify its expensive model calls, then apply a token stop and a separate call-count limit.
Do first: attach the following callback to one complete feature invocation, including its nested chains or agent, and inspect the corresponding trace: which provider/model accounts for the tokens, and which chain or agent repeats that call?
from langchain_core.callbacks import UsageMetadataCallbackHandler
usage = UsageMetadataCallbackHandler()
result = feature.invoke(inputs, config={
"callbacks": [usage],
"run_name": "answer-feature",
"tags": ["answer-feature"],
})
print(usage.usage_metadata)
feature and inputs are your existing runnable and input. The callback aggregates by model; it does not identify individual chains or calculate dollars. Use child runs for that distinction. Usage callback guide; trace configuration.
Choose the branch from that diagnosis
1. You have totals but cannot locate the expensive chain or agent. Use Python langchain 1.4.9 with langchain-core 1.7.6 as this recipe's baseline. The November 4–5 release entries establish those versions; 1.4.9 package metadata requires core >=1.7.5. In an existing LangSmith account, set LANGSMITH_TRACING=true with credentials in your secret manager. Select the registered agent/environment with LANGSMITH_AGENT_ID and LANGSMITH_AGENT_ENVIRONMENT; project-based accounts use LANGSMITH_PROJECT. Follow the LangChain tracing path, then open the cost breakdown in the trace tree. Compare child LLM runs by model, input/output tokens and call count. Check: one feature request has the expected parent and child calls; the largest child costs explain its total. Parent totals aggregate children, so adding both double-counts spend. For thread-level totals, include session_id or thread_id on every child run.
2. You need application counters, or only some providers report usage. On langchain-core 1.7.6, follow the usage callback guide and keep a separate UsageMetadataCallbackHandler per feature invocation. Compare its model-keyed totals with each final AIMessage.usage_metadata. Retain input/output and cache details rather than pricing every token identically. In LangSmith, inspect the model pricing and token categories if token counts exist but cost is absent. Hover over a cost section to inspect its token subtypes. Check: every billable model child has a model identifier and nonmissing usage, and the totals agree for a completed request. Missing metadata is unknown usage, not zero spend. A shared callback across simultaneous requests loses request attribution.
3. Streaming makes usage disappear or inflate. For langchain-openai 1.7.4, follow streaming usage metadata: construct ChatOpenAI(model=your_model_id, stream_usage=True) and retain usage-only chunks even when they contain no displayable text. Use the completed-call callback as the accounting point; do not also add the UI's running totals. The 1.7.4 implementation scopes this wrapper to official OpenAI formats; a compatible endpoint needs its own usage check. Check: compare a completed streamed request's callback count with the provider's reported usage for that request, including the final event. An interrupted stream may never deliver final usage.
4. The expensive unit is an agent with too many turns. On langchain 1.4.9, use model call limit middleware: add ModelCallLimitMiddleware(run_limit=4, exit_behavior="error") to create_agent(..., middleware=[...]). Import it from langchain.agents.middleware. This limits agent model turns; it is not a token or dollar cap. The counter advances after model turns; retries inside a turn are not separate turns. For a between-call token stop, adapt the official before-model middleware path with the same request-local callback:
from langchain.agents.middleware import before_model
@before_model
def stop_at_budget(state, runtime):
used = sum(v["total_tokens"] for v in usage.usage_metadata.values())
if used >= 20_000:
raise RuntimeError("Feature token budget reached")
Register stop_at_budget alongside the model limiter and pass usage through invocation callbacks. 20_000 and four calls are example policies. Create the callback and its guard together for each invocation; do not reuse their closure for concurrent requests. Check: with a small budget and a harmless tool fixture, the next model call is blocked once recorded usage crosses the threshold; separately force repeated tool use and confirm no fifth agent model turn starts. Surface the budget exception as an incomplete result. If any model omits usage or its model identifier, block further work at the application boundary instead of trusting the token guard.
5. One call dominates because its output is long. On langchain-openai 1.7.4, set an explicit output allowance with ChatOpenAI(model=your_model_id, max_tokens=512). The integration parameter guide documents conversion to max_completion_tokens. Check: the provider-reported output usage respects the allowance and a truncation is surfaced as incomplete, rather than accepted as a successful feature result. This does not limit the input prompt or total feature cost; a large input still needs an application admission check before sending it.
Evidence and limits
André Pankraz's March 22, 2025 report #30429 documents inflated streaming totals; it is historical evidence of an accounting failure, not proof of a current universal bug. Juyotal's July 2026 budget proposal and July 13 reply by dariel.datoon distinguish call limits from token limits and describe a before-model guard. The TokenBudgetMiddleware snippet there is proposed code; use the documented hooks for this recipe.
For a sequential single-agent loop, the guard reacts after a completed call and can overshoot by that call's usage. Nested agents need their own guards or central admission control; otherwise they can make multiple calls between parent checks. It cannot cancel provider work already underway, cover uninstrumented calls, or reserve a shared tenant budget. For a monetary ceiling, design application admission control around input, output allowances, retries and concurrency, then reconcile provider charges. These snippets alone do not provide that guarantee. For customer billing attribution, see llm-api-bill-cost-per-customer-feature-tagging.
Not for: Vercel AI SDK in TypeScript; see vercel-ai-sdk-track-feature-token-cost-production.
Started from a post by @LangChain maintainers, packaged by the editor. Original post