Skip to content

fix(langchain): count flex/priority cached tokens and 0.3.x provider - #1213

Merged
Abhijeet Prasad (AbhiPrasad) merged 3 commits into
mainfrom
abhi/langchain-cache-tokens-50c4f860
Nov 30, 2026
Merged

Abhijeet Prasad (AbhiPrasad) merged 3 commits into
mainfrom
abhi/langchain-cache-tokens-50c4f860

Conversation

@AbhiPrasad

@AbhiPrasad Abhijeet Prasad (AbhiPrasad) commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

🤖 This text was AI-generated.

This PR fixes two bugs in the LangChain callback handler (BraintrustCallbackHandler). It also fixes the test_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 flex or priority service tier, langchain-openai (>= 1.0.0) renames the cache-hit key in usage_metadata.input_token_details:

# default tier
{"cache_read": 1954}

# flex / priority tier
{"flex_cache_read": 1954, "flex": 3}
{"priority_cache_read": 1951, "priority": 3}

The callback only read cache_read, so these spans had no prompt_cached_tokens metric. 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_read first, and otherwise fall back to any <tier>_cache_read key:

return next(
    (v for k, v in details.items() if k == "cache_read" or k.endswith("_cache_read")),
    None,
)

The fallback matches the suffix instead of hard-coding flex and priority, because the service-tier spec treats tiers as open strings and langchain-openai may add more. The bare flex / priority keys (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) against gpt-5-mini. It uses gpt-5-mini because gpt-6-luna reports priority requests as served "fast", and langchain-openai does not rename the key for fast. 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 missing provider

Problem

The session installed the 0.3.28 pin, then installed the test-langchain group. That group's pins require langchain-core 1.x, so it silently upgraded the pin:

install langchain-core==0.3.28
install test-langchain (langchain-openai==1.1.14, ...)
  -> langchain-core upgraded to 1.8.4   # session tested 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 got the provider from the response's model_provider, which langchain 1.x added. The serialized id (["langchain", "chat_models", "openai", "ChatOpenAI"]) doesn't carry it in a form _provider_from_serialized understands. So langchain 0.3.x users got no provider on LLM spans, which cost estimation relies on.

Solution

  • 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.

  • Fall back to the ls_provider that LangChain puts in callback metadata on every version:

    provider = _provider_from_serialized(serialized)
    if not provider:
        provider = metadata.get("ls_provider")  # "openai", "anthropic", ...

    The response's model_provider still 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_tier to be omitted, rather than asserting a value the framework never exposes.

Notes for reviewers

  • The large py/uv.lock diff is generated: uv adds a separate resolution for the new conflicting group. Existing groups keep their versions. integrations/langchain-py/uv.lock and integrations/adk-py/uv.lock only gain the new group's metadata, which they copy from the SDK.
  • The existing 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.
  • langchain-openai renames reasoning tokens the same way (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.
  • Follow-up: nothing in nox checks that the installed version matches the matrix pin. uv pip check passes whenever the environment is consistent, so it can't catch this class of bug. test_strands and test_agentscope also install a locked group after their matrix dependency, so they could silently upgrade it the same way.
  • Open question, outside this repo: priority calls on gpt-6-luna are now recorded with served_service_tier: "fast". The backend picks pricing by served tier, so it's worth checking its price table has an entry for fast.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T16:21:24.764123Z 7d597e2 New commits
ℹ️ About Codex in GitHub

Your 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.

@greptile-apps

greptile-apps Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed changes appear safe to merge.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge.

Summary

This PR fixes cached-token counts for OpenAI service tiers and restores provider names for older LangChain versions.

  • LangChain spans include cached input counts for OpenAI service tiers.
  • LangChain 0.3 spans include provider names, and its test session keeps the pinned version.

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.
@AbhiPrasad
Abhijeet Prasad (AbhiPrasad) force-pushed the abhi/langchain-cache-tokens-50c4f860 branch from b7c806e to 7d597e2 Compare November 30, 2026 16:19
@AbhiPrasad
Abhijeet Prasad (AbhiPrasad) merged commit 0bbd0b2 into main Nov 30, 2026
192 of 194 checks passed
@AbhiPrasad
Abhijeet Prasad (AbhiPrasad) deleted the abhi/langchain-cache-tokens-50c4f860 branch November 30, 2026 16:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant