Skip to content

feat: populate Anthropic streaming input_tokens, add /v1/models context_window and model retrieve endpoint - #7234

Merged
MatejKosec merged 2 commits into
mainfrom
user/mkosec/fix-anthropic-streaming-tokens
Apr 13, 2026
Merged

MatejKosec merged 2 commits into
mainfrom
user/mkosec/fix-anthropic-streaming-tokens

Conversation

@MatejKosec

@MatejKosec MatejKosec commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Three fixes for Anthropic Messages API compatibility + OpenAI model endpoint improvements that enable Claude Code to work directly against Dynamo without cc-proxy.

1. Populate input_tokens in streaming message_start event

The real Anthropic API sends input_tokens in the message_start SSE event. Dynamo was sending 0 because the inference engine only reports prompt token counts on the final chunk (message_delta). Clients like Claude Code read input_tokens from message_start and don't fall back to message_delta, causing token counts to jump between real values and 0 on alternating turns.

Fix: Compute a len/3 character estimate from the original request before streaming begins. The estimate is set once at construction and stays consistent between message_start and message_delta — the engine's real output token count still populates message_delta.

2. Add context_window and max_output_tokens to /v1/models

Claude Code reads context_window from the model API response to determine how much context a model supports. Without it, Claude Code falls back to a conservative 200k default and may not utilize the model's full context window.

Fix: Pull context_length from the ModelDeploymentCard (populated by the engine during discovery) and expose it as context_window in model responses. Optional env var overrides (DYN_CONTEXT_WINDOW, DYN_MAX_OUTPUT_TOKENS) are supported for all models.

3. Add GET /v1/models/{model} retrieve endpoint

The OpenAI API specification defines a GET /v1/models/{model} endpoint that returns a single model object. This is also used by Anthropic-format clients.

Fix: Add the retrieve endpoint with wildcard path to support model IDs containing slashes (e.g. Qwen/Qwen3.5-35B-A3B-FP8). Both OpenAI and Anthropic response formats are supported.

Architecture: Content negotiation moved to anthropic.rs

When --enable-anthropic-api is active, model listing and retrieval use a content-negotiating router in anthropic.rs. Requests with the anthropic-version header get Anthropic format; all others get standard OpenAI format. This keeps openai.rs free of Anthropic-specific logic.

When --enable-anthropic-api is NOT active, the plain OpenAI model router is used (with the new context_window and retrieve endpoint still available).

API References

  • OpenAI List Models: GET /v1/models — returns {object: "list", data: [{id, object, created, owned_by}]}
  • OpenAI Retrieve Model: GET /v1/models/{model} — returns {id, object, created, owned_by}
  • Anthropic List Models: GET /v1/models — returns {data: [{id, display_name, type, created_at, context_window}], has_more, first_id, last_id}
  • Anthropic Retrieve Model: GET /v1/models/{model_id} — returns {id, display_name, type, created_at, context_window}

Files Changed

File Change
lib/llm/src/protocols/anthropic/types.rs Shared estimate_message_tokens() helper, estimate_input_tokens() on AnthropicCreateMessageRequest
lib/llm/src/protocols/anthropic/stream_converter.rs Accept estimated tokens in constructor, use in message_start, keep stable across stream
lib/llm/src/http/service/anthropic.rs Token estimation in streaming path, anthropic_models_router with content-negotiating handlers
lib/llm/src/http/service/openai.rs context_window/max_output_tokens on ModelListing, GET /v1/models/{model} retrieve endpoint
lib/llm/src/http/service/service_v2.rs Route to anthropic models router when DYN_ENABLE_ANTHROPIC_API is set

Test plan

  • CI passes (Rust checks, clippy, tests)
  • GET /v1/models returns context_window from MDC
  • GET /v1/models with anthropic-version header returns Anthropic format
  • GET /v1/models/{model} returns single model (both formats)
  • Streaming message_start contains non-zero input_tokens
  • Token counts don't jump between message_start and message_delta
  • Claude Code connects via ANTHROPIC_BASE_URL and sees correct context window

@MatejKosec
MatejKosec requested a review from a team March 11, 2026 19:10
@github-actions github-actions Bot added fix frontend `python -m dynamo.frontend` and `dynamo-run in=http|text|grpc` labels Mar 11, 2026
@coderabbitai

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes implement token estimation for Anthropic models and enhance OpenAI model configuration. Anthropic's token estimation methods are added to type definitions, passed through the streaming converter, and used by the HTTP service. OpenAI models now expose context window and max output token fields with environment-based override support.

Changes

Cohort / File(s) Summary
Anthropic Token Estimation
lib/llm/src/protocols/anthropic/types.rs, lib/llm/src/protocols/anthropic/stream_converter.rs, lib/llm/src/http/service/anthropic.rs
Added estimate_input_tokens() and estimate_tokens() methods using len/3 heuristic for token approximation. Updated AnthropicStreamConverter constructor to accept and initialize with estimated token count instead of hardcoded 0. Modified HTTP service to compute token estimate before stream conversion.
OpenAI Model Configuration
lib/llm/src/http/service/openai.rs
Extended ModelListing struct with optional context_window and max_output_tokens fields. Introduced environment variable overrides DYN_CONTEXT_WINDOW and DYN_MAX_OUTPUT_TOKENS for dynamic per-model configuration in listings.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Token counts hop and play,
Anthropic learns to estimate today,
OpenAI's windows expand so wide,
With env vars as guide,
API responses bloom and sway! 🌱

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title accurately describes the main changes: populating input_tokens in Anthropic streaming and adding context_window/max_output_tokens to the /v1/models endpoint.
Description check ✅ Passed The description is comprehensive with clear sections for overview, detailed explanations of three fixes, architecture notes, API references, files changed, and a test plan.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can scan for known vulnerabilities in your dependencies using OSV Scanner.

OSV Scanner will automatically detect and report security vulnerabilities in your project's dependencies. No additional configuration is required.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/llm/src/protocols/anthropic/stream_converter.rs (1)

56-67: ⚠️ Potential issue | 🔴 Critical

Update the remaining AnthropicStreamConverter::new call sites.

This signature change leaves test_thinking_text_then_tool_call (Line 904) and test_thinking_only_closed_in_end_events (Line 968) still calling the old one-argument constructor, so this file no longer compiles.

🛠 Proposed fix
-        let mut conv = AnthropicStreamConverter::new("test-model".into());
+        let mut conv = AnthropicStreamConverter::new("test-model".into(), 0);
...
-        let mut conv = AnthropicStreamConverter::new("test-model".into());
+        let mut conv = AnthropicStreamConverter::new("test-model".into(), 0);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/llm/src/protocols/anthropic/stream_converter.rs` around lines 56 - 67,
The tests fail to compile because AnthropicStreamConverter::new now requires a
second parameter (estimated_input_tokens); update the remaining call sites in
the file that call AnthropicStreamConverter::new (notably in the tests
test_thinking_text_then_tool_call and test_thinking_only_closed_in_end_events)
to pass an appropriate u32 estimated_input_tokens value (e.g. 0 or a realistic
estimate) as the second argument so the constructor signature matches the
updated impl.
🧹 Nitpick comments (4)
lib/llm/src/http/service/anthropic.rs (1)

196-201: Only estimate input tokens on the streaming path.

This walk is only used when building the streaming converter at Line 279, but it now runs for every non-streaming /v1/messages request too. Gating it behind streaming avoids the extra traversal and schema serialization on the non-streaming path.

♻️ Proposed change
-    let estimated_input_tokens = orig_request.estimate_input_tokens();
+    let estimated_input_tokens = if streaming {
+        orig_request.estimate_input_tokens()
+    } else {
+        0
+    };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/llm/src/http/service/anthropic.rs` around lines 196 - 201, The file
currently calls orig_request.estimate_input_tokens() for every /v1/messages
call; change it so estimated_input_tokens is only computed when handling the
streaming path: guard the call behind the existing streaming flag (the
variable/parameter named streaming) so that orig_request.estimate_input_tokens()
is invoked only inside the streaming branch where the streaming converter is
built (the place referencing estimated_input_tokens when constructing the
converter), and ensure estimated_input_tokens is declared/used only within that
branch to avoid extra traversal and schema work on non-streaming requests.
lib/llm/src/http/service/openai.rs (1)

1618-1647: Please add a focused /v1/models test for the new fields.

I don't see coverage in the provided context for the three cases that matter here: card-derived context_window, env override precedence, and omission when neither source exists. A small handler/unit test would lock the backward-compatibility behavior down.

Also applies to: 1664-1673

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/llm/src/http/service/openai.rs` around lines 1618 - 1647, Add a focused
unit/handler test exercising the /v1/models response for ModelListing to cover
three cases: (1) when a model has a card-provided context_length, assert the
returned context_window equals that card value (use
state.manager().get_model_cards() / ModelListing in the test setup), (2) when
DYN_CONTEXT_WINDOW is set, assert it overrides the card value (set the env var
DYN_CONTEXT_WINDOW and verify context_window matches it), and (3) when neither
card nor env var exist, assert context_window is omitted/None. Use the same
request path that hits the code building ModelListing (model_display_names(),
context_window_override, DYN_CONTEXT_WINDOW) so the test verifies
backward-compatibility and env precedence.
lib/llm/src/protocols/anthropic/types.rs (1)

184-232: Share the token-estimation walk with /v1/messages/count_tokens.

estimate_input_tokens() is now effectively a second copy of AnthropicCountTokensRequest::estimate_tokens() in this file. If block/tool accounting changes in one path and not the other, message_start.usage.input_tokens and /v1/messages/count_tokens will diverge for the same request shape. Please extract the common {system, messages, tools} traversal into a shared helper and have both callers reuse it.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/llm/src/protocols/anthropic/types.rs` around lines 184 - 232, The
traversal that computes total_len in
AnthropicCreateMessageRequest::estimate_input_tokens duplicates the logic in
AnthropicCountTokensRequest::estimate_tokens; extract a shared helper function
(e.g., fn compute_message_tool_len(...) -> usize or a method on a new helper
type) that takes the common inputs (system, messages, tools) and returns the
aggregated length, then call that helper from both
AnthropicCreateMessageRequest::estimate_input_tokens and
AnthropicCountTokensRequest::estimate_tokens and keep the existing tokenization
heuristic (len/3 and minimum 1) in each caller so
message_start.usage.input_tokens and /v1/messages/count_tokens remain consistent
for identical request shapes.
lib/llm/src/protocols/anthropic/stream_converter.rs (1)

76-95: Add a regression test for the new start/end usage handoff.

This is the client-visible behavior Claude Code cares about, but the current tests only cover block ordering. A focused test should assert that emit_start_events() reports the estimated input_tokens here and that a later chunk with backend usage overwrites message_delta.usage.input_tokens with the real prompt token count.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/llm/src/protocols/anthropic/stream_converter.rs` around lines 76 - 95,
Write a focused regression test that verifies the start/end usage handoff: call
emit_start_events() on the Anthropic stream converter and assert the produced
message_start event contains an AnthropicMessageResponse whose
usage.input_tokens equals the converter's estimated input token count (e.g., the
converter's input_token_count), then simulate receiving a later chunk that
contains backend usage (the event that updates message_delta.usage) and assert
that after processing that chunk the message's usage.input_tokens has been
overwritten with the real prompt token count. Locate and use
emit_start_events(), AnthropicMessageResponse, make_sse_event and the code path
that merges backend usage into message_delta.usage.input_tokens to implement the
setup, simulate the chunk, and perform the two assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@lib/llm/src/protocols/anthropic/stream_converter.rs`:
- Around line 56-67: The tests fail to compile because
AnthropicStreamConverter::new now requires a second parameter
(estimated_input_tokens); update the remaining call sites in the file that call
AnthropicStreamConverter::new (notably in the tests
test_thinking_text_then_tool_call and test_thinking_only_closed_in_end_events)
to pass an appropriate u32 estimated_input_tokens value (e.g. 0 or a realistic
estimate) as the second argument so the constructor signature matches the
updated impl.

---

Nitpick comments:
In `@lib/llm/src/http/service/anthropic.rs`:
- Around line 196-201: The file currently calls
orig_request.estimate_input_tokens() for every /v1/messages call; change it so
estimated_input_tokens is only computed when handling the streaming path: guard
the call behind the existing streaming flag (the variable/parameter named
streaming) so that orig_request.estimate_input_tokens() is invoked only inside
the streaming branch where the streaming converter is built (the place
referencing estimated_input_tokens when constructing the converter), and ensure
estimated_input_tokens is declared/used only within that branch to avoid extra
traversal and schema work on non-streaming requests.

In `@lib/llm/src/http/service/openai.rs`:
- Around line 1618-1647: Add a focused unit/handler test exercising the
/v1/models response for ModelListing to cover three cases: (1) when a model has
a card-provided context_length, assert the returned context_window equals that
card value (use state.manager().get_model_cards() / ModelListing in the test
setup), (2) when DYN_CONTEXT_WINDOW is set, assert it overrides the card value
(set the env var DYN_CONTEXT_WINDOW and verify context_window matches it), and
(3) when neither card nor env var exist, assert context_window is omitted/None.
Use the same request path that hits the code building ModelListing
(model_display_names(), context_window_override, DYN_CONTEXT_WINDOW) so the test
verifies backward-compatibility and env precedence.

In `@lib/llm/src/protocols/anthropic/stream_converter.rs`:
- Around line 76-95: Write a focused regression test that verifies the start/end
usage handoff: call emit_start_events() on the Anthropic stream converter and
assert the produced message_start event contains an AnthropicMessageResponse
whose usage.input_tokens equals the converter's estimated input token count
(e.g., the converter's input_token_count), then simulate receiving a later chunk
that contains backend usage (the event that updates message_delta.usage) and
assert that after processing that chunk the message's usage.input_tokens has
been overwritten with the real prompt token count. Locate and use
emit_start_events(), AnthropicMessageResponse, make_sse_event and the code path
that merges backend usage into message_delta.usage.input_tokens to implement the
setup, simulate the chunk, and perform the two assertions.

In `@lib/llm/src/protocols/anthropic/types.rs`:
- Around line 184-232: The traversal that computes total_len in
AnthropicCreateMessageRequest::estimate_input_tokens duplicates the logic in
AnthropicCountTokensRequest::estimate_tokens; extract a shared helper function
(e.g., fn compute_message_tool_len(...) -> usize or a method on a new helper
type) that takes the common inputs (system, messages, tools) and returns the
aggregated length, then call that helper from both
AnthropicCreateMessageRequest::estimate_input_tokens and
AnthropicCountTokensRequest::estimate_tokens and keep the existing tokenization
heuristic (len/3 and minimum 1) in each caller so
message_start.usage.input_tokens and /v1/messages/count_tokens remain consistent
for identical request shapes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8c11d2b5-890c-4d04-9535-95e29beb726d

📥 Commits

Reviewing files that changed from the base of the PR and between 96a5592 and 32d3a9c.

📒 Files selected for processing (4)
  • lib/llm/src/http/service/anthropic.rs
  • lib/llm/src/http/service/openai.rs
  • lib/llm/src/protocols/anthropic/stream_converter.rs
  • lib/llm/src/protocols/anthropic/types.rs

@pull-request-size pull-request-size Bot added size/L and removed size/M labels Mar 11, 2026
@MatejKosec
MatejKosec force-pushed the user/mkosec/fix-anthropic-streaming-tokens branch from c2f3c0a to 1857cb5 Compare March 11, 2026 22:53
@MatejKosec
MatejKosec force-pushed the user/mkosec/fix-anthropic-streaming-tokens branch from 3fa8b7f to 64a2869 Compare March 12, 2026 17:39
@MatejKosec MatejKosec changed the title fix: populate input_tokens in Anthropic streaming message_start fix: populate input_tokens in Anthropic streaming + add model retrieval endpoint Mar 13, 2026
@MatejKosec
MatejKosec force-pushed the user/mkosec/fix-anthropic-streaming-tokens branch from 23e1970 to 040b0c0 Compare April 1, 2026 18:44
…ndow and retrieve endpoint

Three fixes for the Anthropic Messages API compatibility layer:

1. **input_tokens in streaming message_start**: The engine only reports
   prompt token counts on the final chunk, but clients like Claude Code
   read input_tokens from the initial message_start event. Add a len/3
   character heuristic to estimate input tokens before streaming begins.
   Extract the estimation logic into a shared `estimate_message_tokens()`
   helper reused by both `AnthropicCreateMessageRequest` and
   `AnthropicCountTokensRequest`.

2. **context_window in /v1/models**: Claude Code reads context_window from
   the model listing API to manage its context budget. Expose
   `context_length` from `ModelDeploymentCard` in both OpenAI and Anthropic
   model list/retrieve responses. Support `DYN_CONTEXT_WINDOW` and
   `DYN_MAX_OUTPUT_TOKENS` env var overrides.

3. **GET /v1/models/{model} retrieve endpoint**: Standard API endpoint
   needed by clients. Added to both OpenAI and Anthropic routers. Uses
   wildcard path to support model IDs with slashes (e.g.
   `Qwen/Qwen3.5-35B-A3B-FP8`).

When `DYN_ENABLE_ANTHROPIC_API=1`, the /v1/models router is replaced with
a content-negotiating version: requests with `anthropic-version` header get
Anthropic format (with display_name, created_at, context_window), others
get standard OpenAI format. This addresses reviewer feedback to keep
Anthropic-specific logic out of openai.rs.

Signed-off-by: Marko Kosec <mkosec@nvidia.com>
…model responses

The Anthropic SDK's ModelInfo type uses `max_input_tokens` and `max_tokens`,
not `context_window` and `max_output_tokens`. Rename these fields in the
Anthropic-format branches of list_models() and get_model() so the SDK
can properly deserialize them.

Also add tracing::warn\! when DYN_CONTEXT_WINDOW or DYN_MAX_OUTPUT_TOKENS
env vars are set but fail to parse, instead of silently ignoring.

Signed-off-by: Marko Kosec <mkosec@nvidia.com>

This branch was previously deployed

1 inactive deployment
GITLAB — 858bea5c Deployed Apr 9, 2026 by copy-pr-bot[bot] via Trigger CI Pipeline #23211
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend::sglang Relates to the sglang backend feat frontend `python -m dynamo.frontend` and `dynamo-run in=http|text|grpc` size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants