Repository navigation
feat: populate Anthropic streaming input_tokens, add /v1/models context_window and model retrieve endpoint - #7234
Conversation
WalkthroughThe 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ 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. Comment 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. |
There was a problem hiding this comment.
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 | 🔴 CriticalUpdate the remaining
AnthropicStreamConverter::newcall sites.This signature change leaves
test_thinking_text_then_tool_call(Line 904) andtest_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/messagesrequest too. Gating it behindstreamingavoids 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/modelstest 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 ofAnthropicCountTokensRequest::estimate_tokens()in this file. If block/tool accounting changes in one path and not the other,message_start.usage.input_tokensand/v1/messages/count_tokenswill 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 estimatedinput_tokenshere and that a later chunk with backend usage overwritesmessage_delta.usage.input_tokenswith 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
📒 Files selected for processing (4)
lib/llm/src/http/service/anthropic.rslib/llm/src/http/service/openai.rslib/llm/src/protocols/anthropic/stream_converter.rslib/llm/src/protocols/anthropic/types.rs
c2f3c0a to
1857cb5
Compare
3fa8b7f to
64a2869
Compare
23e1970 to
040b0c0
Compare
…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>
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_tokensin streamingmessage_starteventThe real Anthropic API sends
input_tokensin themessage_startSSE event. Dynamo was sending0because the inference engine only reports prompt token counts on the final chunk (message_delta). Clients like Claude Code readinput_tokensfrommessage_startand don't fall back tomessage_delta, causing token counts to jump between real values and 0 on alternating turns.Fix: Compute a
len/3character estimate from the original request before streaming begins. The estimate is set once at construction and stays consistent betweenmessage_startandmessage_delta— the engine's real output token count still populatesmessage_delta.2. Add
context_windowandmax_output_tokensto/v1/modelsClaude Code reads
context_windowfrom 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_lengthfrom theModelDeploymentCard(populated by the engine during discovery) and expose it ascontext_windowin 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 endpointThe 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.rsWhen
--enable-anthropic-apiis active, model listing and retrieval use a content-negotiating router inanthropic.rs. Requests with theanthropic-versionheader get Anthropic format; all others get standard OpenAI format. This keepsopenai.rsfree of Anthropic-specific logic.When
--enable-anthropic-apiis NOT active, the plain OpenAI model router is used (with the newcontext_windowand retrieve endpoint still available).API References
{object: "list", data: [{id, object, created, owned_by}]}{id, object, created, owned_by}{data: [{id, display_name, type, created_at, context_window}], has_more, first_id, last_id}{id, display_name, type, created_at, context_window}Files Changed
lib/llm/src/protocols/anthropic/types.rsestimate_message_tokens()helper,estimate_input_tokens()onAnthropicCreateMessageRequestlib/llm/src/protocols/anthropic/stream_converter.rsmessage_start, keep stable across streamlib/llm/src/http/service/anthropic.rsanthropic_models_routerwith content-negotiating handlerslib/llm/src/http/service/openai.rscontext_window/max_output_tokensonModelListing,GET /v1/models/{model}retrieve endpointlib/llm/src/http/service/service_v2.rsDYN_ENABLE_ANTHROPIC_APIis setTest plan
GET /v1/modelsreturnscontext_windowfrom MDCGET /v1/modelswithanthropic-versionheader returns Anthropic formatGET /v1/models/{model}returns single model (both formats)message_startcontains non-zeroinput_tokensmessage_startandmessage_deltaANTHROPIC_BASE_URLand sees correct context window