Skip to content

fix(server): hide Llama 3.x python_tag calls, add Responses reasoning - #2496

Merged
adrysn merged 6 commits into
mainfrom
fix/issue-2470-python-tag-stream-harmony-reasoning
Oct 20, 2026
Merged

adrysn merged 6 commits into
mainfrom
fix/issue-2470-python-tag-stream-harmony-reasoning

Conversation

@adrysn

@adrysn adrysn commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Llama 3.x <|python_tag|> calls no longer stream as delta.content. CHAT_DELIMITERS enters tool-call state on <|python_tag|> and exits on <|eom_id|> or end of stream. clean_content_markers drops the same block, so no-tools and unparsed calls match the streamed output (feat(tokenizer): Kimi K3 tiktoken family and native XTML renderer #1743 rule). try_llama3 now also accepts the tag after visible text, which becomes the content, and stops at <|eom_id|>.
  • /v1/responses emits a reasoning item for gpt-oss Harmony. split_reasoning reads the chat route's sources in this order: parse_tool_calls(...).reasoning_content, then the existing <think> extraction, then the StreamFilter split (chat::extract_reasoning_content, which already routes Harmony). No second Harmony parser was added. The streamed arm already routed analysis to reasoning through the filter.
  • output_tokens_details.reasoning_tokens is the reasoning item's text, trimmed and encoded with the model tokenizer. Both arms use the same encoding. The parity suite shows streamed and non-streamed reasoning text are equal, so the counts are equal.

Not held back: the bare-JSON Llama 3.x form ({"name": ..., "parameters": ...} with no tag). It has no marker. The filter would have to hold back every { until end of stream to classify it, which would stall every JSON-shaped answer. It still streams as content and is then parsed into tool_calls.

Behavior note: a <|python_tag|> block that is not JSON (Llama's built-in code interpreter) is now dropped from content, streamed and non-streamed, like other tool markup.

Changes during review

  • Duplicated text with an unclosed primed <think> (27928305). When generation stopped mid-thought, the non-streamed reply sent the same text as the reasoning item and as output_text. split_reasoning now strips unclosed primed thinking from the visible text through the chat route's strip_unclosed_primed_thinking.
  • Quadratic non-stream reasoning replay (82846066). extract_reasoning_content fed the whole reply to one StreamFilter::feed, which rescans its buffer on every delimiter hit. 32k repeated markers took 35 to 80 s. It now feeds 128-byte chunks cut on UTF-8 boundaries (about 0.3 s for the same inputs). A test pins chunked output to per-character output.
  • Reasoning-token count off the async executor (9af71a31). The non-stream arm now counts through spawn_blocking, as the stream arm already did. Tiktoken BPE is quadratic per piece, so a pathological reply could block a tokio worker.
  • Docs (b7327309): docs/responses-api.md, docs/server-features.md and a CHANGELOG entry.

Known gaps, not in this PR: multi-segment Harmony analysis is joined with \n by the parser but with nothing by StreamFilter. Whitespace right before a tool-call marker streams as content, while the non-streamed reply trims it. Both are carried into #2464.

Test plan

  • New parity tests (llama3_python_tag_*, 4 tests) cover chunkings(). They fail when the stream_filter/parser/formats changes are stashed.
  • New responses.rs tests (Harmony split with and without parsed tools, reasoning output item, streamed vs non-streamed reasoning_tokens for <think>, primed close-only and Harmony, zero case). They fail when split_reasoning is reverted to main's logic and the counter returns 0.
  • cargo test --lib for server::tool_calls::, server::routes::responses, server::responses, server::muse_atem, server::reasoning_echo, plus cargo clippy --lib --tests -D warnings. All pass on a CPU-only macOS build (MLXCEL_BUILD_METAL=0).
  • GB10 server scenarios (Llama 3.1 streamed tool call, gpt-oss Responses streamed and non-streamed). Not run: this host has no CUDA or Metal.

Resolves #2470

Llama 3.x `<|python_tag|>` tool calls streamed their raw JSON as `delta.content` and then again as `delta.tool_calls`, because the stream filter had no row for the marker. `CHAT_DELIMITERS` now enters tool-call state on `<|python_tag|>` and leaves it on `<|eom_id|>` or end of stream. The non-streamed cleanup drops the same block, and `try_llama3` accepts the tag after visible text and stops at `<|eom_id|>`, so both shapes agree. The bare-JSON form has no marker and is still not held back.

`/v1/responses` read reasoning only from `<think>` forms and hard-coded `reasoning_tokens: 0`. `split_reasoning` now reads the sources the chat route uses: the parser's `reasoning_content` (Harmony `analysis`), then the `<think>` extraction, then the `StreamFilter` split. Both arms count `reasoning_tokens` by encoding their reasoning item text with the model tokenizer.

New parity tests in stream_parity_tests.rs and unit tests in responses.rs fail without the fix. tool_calls, responses, muse_atem and reasoning_echo lib tests and clippy pass on a CPU-only build.

Refs #2470
@adrysn adrysn added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority labels Oct 20, 2026
The new StreamFilter fallback in split_reasoning returns the whole output as reasoning when a primed thinking block never closes (max_tokens hit mid-thought), but the visible text still carried the same output, so the non-streamed reply surfaced it twice: once as the reasoning item and once as output_text. The streamed reply already sends it as reasoning only.

split_reasoning now applies the chat route's strip_unclosed_primed_thinking to the visible text, so both arms of /v1/responses match the chat route. A regression test covers the primed unclosed case with and without parsed tools.

Refs #2470
@adrysn

adrysn commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Hide Llama 3.x <|python_tag|> calls from streamed content, and surface Harmony reasoning plus non-zero reasoning_tokens on /v1/responses (#2470).

Findings Addressed

  • Non-streamed /v1/responses surfaced an unclosed primed thinking block twice, as the reasoning item and as output_text; the new StreamFilter fallback returned it as reasoning while the visible text kept it. Fixed in 2792830 with the chat route's strip_unclosed_primed_thinking and a regression test (HIGH)

Remaining Items

  • Multi-segment Harmony analysis: the parser joins segments with \n, the StreamFilter concatenates them, so reasoning text and token count can differ by a token between arms. The chat route has the same split (MEDIUM, pre-existing)
  • /v1/responses ignores --reasoning-format, before and after this PR (MEDIUM, pre-existing, out of scope)
  • Non-JSON <|python_tag|> blocks (code interpreter, builtin tools) are dropped from content without a log line (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (CPU narrow targets; GB10 scenarios not run here)

extract_reasoning_content fed the whole generation into one StreamFilter::feed call. The filter rescans its full pending buffer for every delimiter on each hit, so a delimiter-dense reply was O(hits x length): 32k repeated <|python_tag|> took 42 s and 32k <tool_call> took 80 s on the async request path. This PR made both the new Llama 3.x markers and the non-stream /v1/responses path (split_reasoning) reach it.

The replay now feeds 128-byte chunks cut on UTF-8 char boundaries, the same shape as the per-token streaming path, and the same inputs finish in about 0.29 s. Filter internals are unchanged. A new test asserts chunked output equals a per-char feed for delimiter-dense, multibyte and Harmony inputs.

Validated with the tool_calls, routes::chat, routes::responses, responses, chat_request, muse_atem and reasoning_echo suites, clippy -D warnings and cargo fmt --check.

Refs #2470
@adrysn

adrysn commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Fixed:

  • HIGH (8284606): extract_reasoning_content fed the whole reply into one StreamFilter::feed, which is O(delimiter hits x length). 32k <|python_tag|> took 42 s, and 32k <tool_call> took 80 s. This PR adds new markers and the non-stream /v1/responses path to that code. The filter now gets 128-byte chunks cut on char boundaries, and the same inputs finish in about 0.29 s. A parity test was added.

Remaining (not fixed here):

  • MEDIUM: count_reasoning_tokens re-encodes model reasoning. On tiktoken checkpoints (Kimi K3, HunYuan), bpe_encode is quadratic per piece. Its own doc puts a 25k-char punctuation run at about 26 s. It runs once per response, and the non-stream arm runs it on the async executor. Suggested follow-up: in the stream arm, count reasoning positions from the filter, and clamp the count to completion_tokens.
  • MEDIUM, pre-existing: in split_reasoning, extract_reasoning_from_raw matches the first literal </think> anywhere. A Harmony final channel that mentions </think> therefore moves the final text before it, plus the raw <|channel|> markup, into reasoning. The streamed arm does not do this.
  • LOW, pre-existing class: <|eom_id|> (like </tool_call>) exits to content from the Thinking state, so reasoning after it streams as content. Non-stream strips the block.

Cleared: UTF-8 slicing (all cuts come from ASCII find offsets), stream buffering (ToolCall payload is drained every feed and held bytes are bounded), strip_python_tag_blocks (linear, 1.9 ms at 32k openers), and ATEM escape through <|eom_id|> (guarded by atem_depth).

Gates: the tool_calls, routes::chat, routes::responses, responses, chat_request, muse_atem and reasoning_echo suites pass, and clippy -D warnings and fmt --check are clean.

The non-stream `/v1/responses` arm encoded the reasoning item on the tokio executor thread. Tiktoken BPE is quadratic per piece (a 25k-char punctuation run takes about 26 s), so a long reasoning item on a Kimi K3 or HunYuan checkpoint could stall a worker. The handler has no blocking section to fold the count into, so it now runs `count_reasoning_tokens` through `tokio::task::spawn_blocking`. The counting itself is unchanged, and the stream arm already counts inside its own blocking task, so the two arms stay equal. A new async test checks that the blocking-pool count equals the direct count.

Validated with the responses, server::responses and tool_calls lib tests, clippy -D warnings, and cargo fmt --check on a CPU-only build.

Refs #2470
Describe the #2470 behavior changes: Llama 3.x python_tag calls are held back from streamed content and non-JSON python_tag blocks are dropped in both modes (docs/server-features.md), and /v1/responses returns Harmony reasoning as a reasoning output item with a real reasoning_tokens count (docs/responses-api.md). Add the CHANGELOG Fixed entry.

Validation: cargo test --profile test-fast -p mlxcel --lib for server::tool_calls:: (457), server::routes::responses (25) and server::responses (56) pass; clippy --lib --tests -D warnings and cargo fmt --check are clean.

Refs #2470
@adrysn adrysn added status:done Completed and removed status:review Under review labels Oct 20, 2026
@adrysn
adrysn merged commit 1aa80a3 into main Oct 20, 2026
27 checks passed
@adrysn
adrysn deleted the fix/issue-2470-python-tag-stream-harmony-reasoning branch October 20, 2026 12:15
@inureyes

inureyes commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Implementation hardening

Reviewed PR #2496 and the full issue #2470 thread. Follow-up PR #2498, commit 11da2573 fixes one remaining correctness gap: multiple Harmony analysis segments were joined differently by the parser, and multiple think blocks could lose later reasoning in non-streamed Responses. Both modes now accumulate reasoning through the existing streaming filter before legacy fallbacks, preserving text and token-count parity. Regression cases cover both formats with and without tools; documentation is updated.

  • Security: reviewed suppression of tagged tool syntax, declared-tool parsing and error paths; no new authorization or input-boundary gap found.
  • Performance/reliability: retained bounded UTF-8 reasoning replay and off-executor token counting; the new canonical path remains linear in output size. Delimiter-dense regression passed.
  • Validation: cargo test --profile test-fast --features cuda --lib -- server::tool_calls:: server::routes::responses server::responses server::muse_atem server::reasoning_echo --test-threads=1: 580 passed. The chunked-reasoning regression also passed separately. cargo clippy -j 4 -p mlxcel --lib --tests -- -D warnings passed in an isolated CPU target directory. Formatting and diff checks passed.
  • Real NVIDIA GB10 HTTP verification: Llama 3.1 8B 4-bit emitted exactly one tool call and no raw python-tag/JSON content in streaming or non-streaming; GPT-OSS 20B MXFP4 produced equal nonempty reasoning and equal nonzero reasoning-token counts through both Responses modes. Both servers were shut down after testing.
  • Residual scope: unmarked bare-JSON calls and chat-route whitespace normalization remain as disclosed in the original PR. The previously disclosed multi-segment Responses reasoning mismatch is fixed here.

inureyes added a commit that referenced this pull request Oct 20, 2026
## Summary

Follow-up hardening for merged [PR #2496](#2496), reviewed against [issue #2470](#2470). Non-streamed Responses could insert parser-only newlines between Harmony analysis segments or omit later think blocks, making reasoning text and token counts differ from streaming. Both modes now use the existing bounded streaming filter before legacy fallbacks. Regression tests cover both formats with and without tools, and the Responses documentation describes the common accumulation rule.

Security review found no additional authorization or input-boundary gaps. Tagged tool-call suppression remains intact. Performance review confirms bounded UTF-8 replay and token counting off the async executor are preserved; no separate Harmony parser was introduced.

## Validation

- CUDA tool-call, Responses and reasoning regressions: 580 passed; delimiter-dense reasoning replay: 1 passed.
- `cargo clippy -j 4 -p mlxcel --lib --tests -- -D warnings`, formatting and diff checks passed; clippy used an independent target directory to exclude stale worktree artifacts.
- Real GB10 HTTP tests passed: Llama 3.1 8B 4-bit produced one tool call without raw call content; GPT-OSS 20B MXFP4 returned identical reasoning and 44 reasoning tokens in both Responses modes.
- The multi-segment Responses mismatch disclosed in the original PR is fixed. Its unmarked bare-JSON tool-call and chat whitespace caveats remain outside this correction.

Refs #2470

Refs #2496
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(server): stream Llama 3.x python_tag tool calls cleanly and surface harmony reasoning in Responses

2 participants