feat(langchain): Support cache/reasoning token metrics based on Langchain UsageMetadata - #6840
Conversation
alexander-alderman-webb
left a comment
There was a problem hiding this comment.
Re-generating the test matrix has pulled in some test failures.
Could you revert changes to tox.ini, scripts/populate_tox/releases.jsonl, and scripts/populate_tox/package_dependencies.jsonl?
62ab173 to
88ef6da
Compare
88ef6da to
12997a4
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 12997a4. Configure here.
| ): | ||
| token_usage = _get_token_usage(response) | ||
| if token_usage: | ||
| tokens = _extract_tokens(token_usage) |
There was a problem hiding this comment.
Token counts inflated for multiple choices
Medium Severity
_record_token_usage now always prefers summing usage from response.generations before considering response-level llm_output usage. Providers typically attach the same request-level usage_metadata to every choice, so calls with n > 1 can report multiplied input, output, total, cache, and reasoning tokens. Previously, present llm_output token usage was used once and avoided that inflation.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 12997a4. Configure here.
|
Going to review this now. |
|
Just an update that I found a bug handling multi-candidate responses. We'll want to fix that first. |


Summary
Cache read/Cache write tokens and output reasoning tokens weren't being picked up by the Langchain integration.
scripts/generate-test-files.shto update Langchain version as the olderlatestversion wasn't returningcache_writemetric.Description
As described by my initial approach here, this PR adds a few new token usage metrics
cache_read/cache_creation/reasoning/audioand populates the following additional span tags.gen_ai.usage.input_tokens.cachedgen_ai.usage.input_tokens.cache_writegen_ai.usage.output_tokens.reasoningTesting
Add new asserts in Langchain v1+ only tests (
test_langchain_create_agent,test_tool_execution_span) as suggested by @alexander-alderman-webbRan unit tests with
TESTPATH=tests/integrations/langchain/test_langchain.py uv run tox -e <ENV>for following envs:py3.14-langchain-base-v0.1.20py3.14-langchain-base-latestIssues
Fixes #6799
Fixes PY-2606
Related
OTel's Langchain Integration's set_chat_response_usage impl
Test Evidence
py3.14-langchain-base-v0.1.20py3.14-langchain-base-latest