Repository navigation
fix(langchain): count flex/priority cached tokens and 0.3.x provider - #1213
Merged
Abhijeet Prasad (AbhiPrasad) merged 3 commits intoNov 30, 2026
Merged
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Contributor
[Medium impact] The reviewed changes appear safe to merge. SummaryThis PR fixes cached-token counts for OpenAI service tiers and restores provider names for older LangChain versions.
No actionable issues were found. Tests were not run. Reviews (3) · Last reviewed commit: "ref(langchain): simplify cache-token and..." · Reviewed by Greptile |
> 🤖 **This text was AI-generated.**
The `test_langchain(0.3.28)` nox session never ran against
langchain-core 0.3.28. It installed the pin, then installed the
`test-langchain` group, whose langchain-openai/anthropic/langgraph pins
require langchain-core 1.x and silently upgraded it:
```
install langchain-core==0.3.28
install test-langchain (langchain-openai==1.1.14, ...)
-> langchain-core upgraded to 1.8.4 # session tests 1.8.4, not 0.3.28
```
Running the real 0.3.28 stack exposed an SDK bug: LLM spans had no
`metadata.provider`. The callback only read the provider from the
response's `model_provider`, which langchain 1.x added. The serialized
id (`["langchain", "chat_models", "openai", "ChatOpenAI"]`) does not
carry it in a form `_provider_from_serialized` understands, so
langchain 0.3.x users got no provider and lost cost estimation.
- Add a `test-langchain-0-3` dependency group with the newest companions
that still accept langchain-core 0.3.28 (langchain-openai 0.2.14,
langchain-anthropic 0.3.1, langgraph 0.5.4), declare its uv conflicts,
and use it for the `0.3.28` session, following the existing
`test-llamaindex-0-13` pattern. The session now runs `uv pip check`
so a future silent upgrade fails setup.
- Fall back to the `ls_provider` that LangChain puts in callback
metadata on every version:
```python
provider = _provider_from_serialized(serialized)
if not provider:
provider = metadata.get("ls_provider") # "openai", "anthropic", ...
```
The response's `model_provider` still overrides it at span end, so
langchain 1.x output is unchanged.
- langchain-openai only reports the served service tier from 0.3.16, so
tests now expect `served_service_tier` to be omitted on older
versions instead of asserting a value the framework never exposes.
The existing 0.3.28 cassettes were recorded with langchain-openai
1.1.14. Playback does not match request bodies and OpenAI's response
format is the same, so they replay correctly against the old stack.
`integrations/langchain-py/uv.lock` and `integrations/adk-py/uv.lock`
are refreshed because they embed the SDK's dependency-group metadata.
> 🤖 **This text was AI-generated.**
## Problem
When OpenAI serves a call on the `flex` or `priority` service tier,
langchain-openai (>= 1.0.0) renames the cache-hit key in
`usage_metadata.input_token_details`:
```python
# default tier
{"cache_read": 1954}
# flex / priority tier
{"flex_cache_read": 1954, "flex": 3}
{"priority_cache_read": 1951, "priority": 3}
```
`BraintrustCallbackHandler` only read `cache_read`, so these spans had
no `prompt_cached_tokens` metric. Affected calls showed a 0% cache hit
rate even though OpenAI reported a hit. This happened for both Chat
Completions and the Responses API (`use_responses_api=True`).
## Solution
Read `cache_read` first, and otherwise fall back to any
`<tier>_cache_read` key:
```python
cache_read = details.get("cache_read")
if cache_read is None:
cache_read = sum(v for k, v in details.items() if k.endswith("_cache_read"))
```
The fallback matches the suffix rather than hard-coding `flex` and
`priority`, because the service-tier spec treats tiers as open strings
and langchain-openai may add more. The `flex` / `priority` keys
(uncached input at that tier) are not counted as cached tokens.
The new cassette-backed test records real flex and priority calls
against `gpt-5-mini`; `gpt-6-luna` reports priority requests as served
`"fast"`, which langchain-openai does not rename. The test is skipped
on langchain-openai < 1.0, which never renames the key. The ~1500-token
prompt used for caching tests is now a shared module constant.
Limitation: langchain-openai renames reasoning tokens the same way
(`flex_reasoning`), but the LangChain callback does not record
reasoning tokens at all today, so nothing is lost there.
Service tiers spec: https://github.com/braintrustdata/braintrust-spec/blob/main/skills/instrumentation-spec/references/features/service-tiers.md
> 🤖 **This text was AI-generated.**
Behavior-preserving cleanups after review:
- `_cache_read_tokens` returns the first `cache_read` / `*_cache_read`
value instead of summing a filtered list; only one such key is ever
present per response.
```python
return next(
(v for k, v in details.items() if k == "cache_read" or k.endswith("_cache_read")),
None,
)
```
- `_provider_from_start` validates `ls_provider` the same way
`_model_and_provider_from_response` validates `model_provider`.
- Drop the `[test-langchain, test-langchain-0-3]` uv conflict: both
groups are already in the shared openai conflict set, so it was
redundant (re-locking only removes that entry; resolutions are
unchanged).
- Drop the extra `_check_installed_deps` call in `test_langchain`;
`_run_tests` already runs `uv pip check` for every session.
- Tests: fold `REPORTS_SERVED_TIER` into `_served()` and collapse the
caching prompt setup into one expression.
Abhijeet Prasad (AbhiPrasad)
force-pushed
the
abhi/langchain-cache-tokens-50c4f860
branch
from
November 30, 2026 16:19
b7c806e to
7d597e2
Compare
Abhijeet Prasad (AbhiPrasad)
deleted the
abhi/langchain-cache-tokens-50c4f860
branch
November 30, 2026 16:30
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR fixes two bugs in the LangChain callback handler (
BraintrustCallbackHandler). It also fixes thetest_langchain(0.3.28)nox session, which never actually tested langchain-core 0.3.28.1. Cached input tokens dropped on flex and priority tiers
Problem
When OpenAI serves a call on the
flexorpriorityservice tier, langchain-openai (>= 1.0.0) renames the cache-hit key inusage_metadata.input_token_details:The callback only read
cache_read, so these spans had noprompt_cached_tokensmetric. Affected calls showed a 0% cache hit rate even when OpenAI reported a hit. Both Chat Completions and the Responses API (use_responses_api=True) were affected. The service-tier metadata (requested_service_tier/served_service_tier) was already correct; only the cached token count was lost.Solution
Read
cache_readfirst, and otherwise fall back to any<tier>_cache_readkey:The fallback matches the suffix instead of hard-coding
flexandpriority, because the service-tier spec treats tiers as open strings and langchain-openai may add more. The bareflex/prioritykeys (uncached input at that tier) are not counted as cached.The new cassette-backed test,
test_service_tier_prompt_cached_tokens, records real flex and priority calls (Chat Completions and Responses API) againstgpt-5-mini. It usesgpt-5-minibecausegpt-6-lunareports priority requests as served"fast", and langchain-openai does not rename the key forfast. The test is skipped on langchain-openai < 1.0, which never renames it.2.
test_langchain(0.3.28)ran langchain-core 1.8.4, hiding a missingproviderProblem
The session installed the 0.3.28 pin, then installed the
test-langchaingroup. That group's pins require langchain-core 1.x, so it silently upgraded the pin:Running the real 0.3.28 stack exposed an SDK bug: LLM spans had no
metadata.provider. The callback only got the provider from the response'smodel_provider, which langchain 1.x added. The serialized id (["langchain", "chat_models", "openai", "ChatOpenAI"]) doesn't carry it in a form_provider_from_serializedunderstands. So langchain 0.3.x users got no provider on LLM spans, which cost estimation relies on.Solution
Add a
test-langchain-0-3dependency group with the newest companions that still accept langchain-core 0.3.28 (langchain-openai 0.2.14, langchain-anthropic 0.3.1, langgraph 0.5.4). Declare its uv conflicts and use it for the0.3.28session, following the existingtest-llamaindex-0-13pattern.Fall back to the
ls_providerthat LangChain puts in callback metadata on every version:The response's
model_providerstill overrides it when the span ends, so langchain 1.x output is unchanged.langchain-openai only reports the served tier from 0.3.16. On older versions the tests now expect
served_service_tierto be omitted, rather than asserting a value the framework never exposes.Notes for reviewers
py/uv.lockdiff is generated: uv adds a separate resolution for the new conflicting group. Existing groups keep their versions.integrations/langchain-py/uv.lockandintegrations/adk-py/uv.lockonly gain the new group's metadata, which they copy from the SDK.cassettes/0.3.28/recordings were made with langchain-openai 1.1.14. Playback doesn't match on request bodies and OpenAI's response format is the same, so they replay correctly against the old stack.flex_reasoning). The LangChain callback doesn't record reasoning tokens at all today, so nothing is lost there, but that's a gap of its own.uv pip checkpasses whenever the environment is consistent, so it can't catch this class of bug.test_strandsandtest_agentscopealso install a locked group after their matrix dependency, so they could silently upgrade it the same way.gpt-6-lunaare now recorded withserved_service_tier: "fast". The backend picks pricing by served tier, so it's worth checking its price table has an entry forfast.