Skip to content

feat: add chatStream() streaming API for Qwen3.5 models - #28

Merged
Brooooooklyn merged 3 commits into
mainfrom
feat/chat-stream-api
Mar 12, 2026
Merged

Brooooooklyn merged 3 commits into
mainfrom
feat/chat-stream-api

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Add token-by-token streaming for interactive UIs via AsyncGenerator. The Rust decode loop pushes each token through a ThreadsafeFunction callback, and the TypeScript layer wraps it into async *chatStream() directly on the model classes.

  • Rust: chat_stream() on Qwen3_5Model and Qwen3_5MoeModel using ThreadsafeFunction with cancellation via Arc
  • TypeScript: Qwen35Model/Qwen35MoeModel subclasses override chatStream() as AsyncGenerator
  • Cancellation automatic via generator finally block on break/return
  • ModelLoader returns subclasses so loadPretrained() includes streaming

Note

Medium Risk
Adds new token-by-token streaming generation paths in the Rust Qwen3.5 dense/MoE models and bridges them to JS via threadsafe callbacks, which touches core inference loops and concurrency/cancellation behavior.

Overview
Adds a streaming chat capability for Qwen3.5 dense and MoE models: Rust now exposes chat_stream() that emits per-token ChatStreamChunk callbacks and returns a ChatStreamHandle that can cancel() an in-flight generation.

Updates the JS/TS surface to include ChatStreamChunk/ChatStreamHandle types and wraps the native callback API into an AsyncGenerator-based chatStream() via new packages/lm/src/stream.ts, with automatic cancellation in a finally block; ModelLoader/exports are adjusted so loadPretrained() returns these streaming-enabled subclasses. Adds tests validating the callback-to-async-iterator bridge, final-chunk field mapping, cancellation on early break, and error propagation.

Written by Cursor Bugbot for commit 09a0116. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • New Features

    • Streaming chat for Qwen3.5 and Qwen3.5 MoE: real-time token streaming via callback or async iterator, immediate stream handle with cancel(), incremental delta events and a final event including finishReason, toolCalls, thinking, token counts, and raw text; supports cancellation and error propagation.
  • Tests

    • Added tests validating streaming tokens, final-chunk metadata, cancellation behavior, and error propagation.

Add token-by-token streaming for interactive UIs via AsyncGenerator.
The Rust decode loop pushes each token through a ThreadsafeFunction
callback, and the TypeScript layer wraps it into `async *chatStream()`
directly on the model classes.

- Rust: chat_stream() on Qwen3_5Model and Qwen3_5MoeModel using
  ThreadsafeFunction with cancellation via Arc<AtomicBool>
- TypeScript: Qwen35Model/Qwen35MoeModel subclasses override
  chatStream() as AsyncGenerator<ChatStreamEvent>
- Cancellation automatic via generator finally block on break/return
- ModelLoader returns subclasses so loadPretrained() includes streaming

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 39c14408-ecfa-4431-a2ac-e65d3b650d58

📥 Commits

Reviewing files that changed from the base of the PR and between f33e5ba and 09a0116.

📒 Files selected for processing (5)
  • __test__/models/qwen35-stream.test.ts
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • packages/lm/src/index.ts
  • packages/lm/src/stream.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/models/qwen35-stream.test.ts

📝 Walkthrough

Walkthrough

Adds streaming chat support for Qwen3.5 and Qwen3.5MoE across Rust and TypeScript layers: new ChatStreamChunk/ChatStreamHandle types, native chat_stream APIs with cancellation and per-token callbacks, a TypeScript wrapper converting callbacks to AsyncGenerators, type/declaration updates, and tests for streaming behavior.

Changes

Cohort / File(s) Summary
Streaming tests
__test__/models/qwen35-stream.test.ts
New tests exercising chatStream as an async generator: delta token streaming, final chunk fields, early termination/cancellation, and error propagation using mocked native callbacks.
Native Qwen3.5 streaming
crates/mlx-core/src/models/qwen3_5/model.rs
Adds ChatStreamChunk and ChatStreamHandle; implements chat_stream with ThreadsafeFunction callback, per-token streaming, cancellation via AtomicBool, compiled vs Rust decode paths, and final aggregation (tool_calls, thinking, finish_reason).
Native Qwen3.5MoE streaming
crates/mlx-core/src/models/qwen3_5_moe/model.rs
Adds parallel chat_stream API for MoE variant mirroring dense implementation, including process-wide mutex handling for compiled path, token streaming, cancellation, and final chunk emission.
Native binding export
packages/core/index.cjs
Exports ChatStreamHandle from native binding.
Type declarations
packages/core/index.d.cts
Adds ChatStreamHandle class and ChatStreamChunk interface; extends Qwen35Model and Qwen35MoeModel with chatStream(..., callback): Promise<ChatStreamHandle> signatures.
Stream wrapper & models
packages/lm/src/stream.ts
New wrapper converting callback-based native streams to AsyncGenerators: defines ChatStreamDelta, ChatStreamFinal, ChatStreamEvent; implements Qwen35Model and Qwen35MoeModel classes with chatStream async generators and internal _createChatStream bridge handling queueing, cancellation, and error propagation.
Public exports / re-exports
packages/lm/src/index.ts
Re-exports Qwen35Model/Qwen35MoeModel from ./stream; exposes ChatStreamDelta, ChatStreamFinal, ChatStreamEvent, ChatStreamChunk, ChatStreamHandle, and internal _createChatStream.
Model loader imports
packages/lm/src/models/model-loader.ts
Updates imports/aliases to source Qwen35Model/Qwen35MoeModel from local ../stream module instead of @mlx-node/core.

Sequence Diagram

sequenceDiagram
    participant JS as JavaScript Client
    participant Wrapper as Stream Wrapper<br/>Qwen35Model
    participant Native as Native chat_stream<br/>(Rust)
    participant Callback as ThreadsafeFunction<br/>Callback

    JS->>Wrapper: for await (ev of model.chatStream(...))
    Wrapper->>Native: call native chat_stream(messages, config, callback)
    Native-->>Wrapper: returns ChatStreamHandle
    Native->>Callback: emit ChatStreamChunk (delta)
    Callback->>Wrapper: enqueue/yield delta event
    Wrapper-->>JS: deliver ChatStreamDelta
    loop tokens
        Native->>Callback: emit next delta
        Callback->>Wrapper: enqueue/yield
        Wrapper-->>JS: deliver
    end
    Native->>Callback: emit final ChatStreamChunk (done=true)
    Callback->>Wrapper: enqueue/yield final event
    Wrapper-->>JS: deliver ChatStreamFinal
    alt cancellation
        JS->>ChatStreamHandle: cancel()
        ChatStreamHandle->>Native: set cancel flag
        Native->>Callback: stop emission
        Wrapper-->>JS: generator closes
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Poem

🐰 I nibble bytes and hop on streams,
Tokens trickle like carrot dreams,
Delta hops then final cheer,
Cancel a hop — the end is near,
Streaming joy, a rabbit beams. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding a streaming API for Qwen3.5 models' chat functionality.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/chat-stream-api

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.

- Remove unnecessary pass-through constructors on TS subclasses
- Remove unused Qwen35Config/Qwen35MoeConfig type imports
- Don't stream a delta token on cancellation — just break immediately
- Rewrite tests to exercise the real _createChatStream bridge
  (queue/notify/cancellation) instead of mocking the generator

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (3)
packages/lm/src/stream.ts (3)

31-32: Rename these module-level constants to UPPER_SNAKE_CASE.

_nativeDenseChatStream and _nativeMoeChatStream stand out from the package's constant naming convention. NATIVE_DENSE_CHAT_STREAM / NATIVE_MOE_CHAT_STREAM would match the repo style better.

Based on learnings, "In TypeScript files across mlx-node/mlx-node, adopt camelCase for variables, functions, and methods, while using UPPER_SNAKE_CASE for module-level constants (for example: const TEXT_LABELS = ...; const DEFAULT_BASE_PATH = ...)."

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

In `@packages/lm/src/stream.ts` around lines 31 - 32, Rename the module-level
constants _nativeDenseChatStream and _nativeMoeChatStream to UPPER_SNAKE_CASE
(NATIVE_DENSE_CHAT_STREAM and NATIVE_MOE_CHAT_STREAM) to follow the repo's
constant naming convention; update every reference to these constants (e.g.,
where Qwen35ModelNative.prototype.chatStream and
Qwen35MoeModelNative.prototype.chatStream are assigned) so the new symbol names
are used consistently across the file.

83-92: Add a defensive runtime check for required final-chunk fields.

The Rust ChatStreamChunk struct defines finishReason, numTokens, and rawText as Option<T> types. While all current implementations wrap these in Some() when emitting a final chunk (done: true), the type system allows None. The JS code unconditionally asserts them with !, creating an implicit contract.

A defensive check will fail fast if any implementation path ever emits an incomplete final chunk, instead of leaking undefined through a ChatStreamFinal.

Defensive guard
         if (chunk.done) {
+          if (chunk.finishReason == null || chunk.numTokens == null || chunk.rawText == null) {
+            throw new Error('Native chatStream returned an incomplete final chunk');
+          }
           yield {
             text: chunk.text,
             done: true,
-            finishReason: chunk.finishReason!,
+            finishReason: chunk.finishReason,
             toolCalls: chunk.toolCalls ?? [],
             thinking: chunk.thinking ?? null,
-            numTokens: chunk.numTokens!,
-            rawText: chunk.rawText!,
+            numTokens: chunk.numTokens,
+            rawText: chunk.rawText,
           } as ChatStreamFinal;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lm/src/stream.ts` around lines 83 - 92, The final-chunk assembly in
the generator currently uses non-null assertions on chunk.finishReason,
chunk.numTokens, and chunk.rawText when chunk.done is true (see the branch using
chunk.done and the ChatStreamFinal yield). Add a defensive runtime check inside
that branch that verifies chunk.finishReason, chunk.numTokens, and chunk.rawText
are not undefined/null and throw a clear Error (or reject) if any are missing,
instead of using the ! assertions; then construct and yield the ChatStreamFinal
only after the checks pass so consumers never receive an incomplete final chunk.

125-127: Consider using composition or method overloads instead of inheritance with @ts-expect-error.

The @ts-expect-error suppression masks a type contract mismatch. While the native classes are internal to this package and the public API safely exports only the wrapper classes, the inheritance relationship creates a maintenance burden and makes the override implicit rather than explicit. Consider either:

  1. Composition: Delegate to a native instance instead of inheriting from it, or
  2. Overloads: Keep the inheritance but define explicit method overloads that cover both signatures:
Overload example
  chatStream(messages: ChatMessage[], config?: Qwen35ChatConfig | null): AsyncGenerator<ChatStreamEvent>;
  chatStream(
    messages: ChatMessage[],
    config: Qwen35ChatConfig | null | undefined,
    callback: (err: Error | null, chunk: ChatStreamChunk) => void,
  ): Promise<ChatStreamHandle>;
  chatStream(
    messages: ChatMessage[],
    config?: Qwen35ChatConfig | null,
    callback?: (err: Error | null, chunk: ChatStreamChunk) => void,
  ): AsyncGenerator<ChatStreamEvent> | Promise<ChatStreamHandle> {
    if (callback) {
      return _nativeDenseChatStream.call(this, messages, config ?? null, callback);
    }
    return _createChatStream(_nativeDenseChatStream, this, messages, config);
  }

Apply to both Qwen35Model and Qwen35MoeModel.

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

In `@packages/lm/src/stream.ts` around lines 125 - 127, The current override of
chatStream using "@ts-expect-error" masks a type mismatch; refactor Qwen35Model
and Qwen35MoeModel to avoid suppressing the error by either (A) moving from
inheritance to composition: remove the direct inheritance of the native class,
add a private/native instance field (e.g., _nativeDenseChatStream or the native
class instance), and delegate chatStream to
_createChatStream(this._nativeInstance, this, messages, config), or (B) keep
inheritance but add explicit TypeScript overloads for chatStream that declare
both the original base signature and the AsyncGenerator signature before the
implementation so the override is properly typed; ensure references to
chatStream, _createChatStream, _nativeDenseChatStream, Qwen35Model, and
Qwen35MoeModel are updated accordingly and remove the `@ts-expect-error` comment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@__test__/models/qwen35-stream.test.ts`:
- Around line 36-53: The test currently replaces the implementation under test
by overriding chatStream on the Qwen35Model in createMockModel, so the wrapper
logic (callback bridge, finally-driven cancellation, native error propagation)
never runs; instead, stub the lower-level native callback source that chatStream
uses (the internal provider/adapter method invoked by chatStream) while leaving
Qwen35Model.chatStream unmodified, then iterate the real model.chatStream in
tests; ensure your stub emits the same token events and final object shape, and
add tests that simulate cancellation (throw from the callback source) and native
errors to exercise finally blocks and error propagation.

In `@crates/mlx-core/src/models/qwen3_5_moe/model.rs`:
- Around line 943-945: The spawn_blocking(...) call that assigns to result
currently only handles the join error via if let Err(e) = result, but the
closure returns Result<(), Error> so Ok(Err(_)) is possible and is ignored;
update the handling of result from napi::bindgen_prelude::spawn_blocking(...)
.await to fully match its type: handle Err(join_error) as before, handle
Ok(Err(inner_error)) by sending the appropriate error/terminal chunk or invoking
the stream error path (using the same error reporting you use for join errors),
and only proceed on Ok(Ok(())); locate the spawn_blocking invocation and the
variable result in the closure in model.rs (the closure that returns
std::result::Result<(), Error>) and implement this three-way match to ensure
inner errors are surfaced to stream consumers.

In `@crates/mlx-core/src/models/qwen3_5/model.rs`:
- Around line 981-983: The spawn_blocking closure returns Result<(), Error> but
the current join-result handling only checks the outer JoinError branch and
drops Ok(Err(...)); update the code that handles
napi::bindgen_prelude::spawn_blocking(...)'s returned result to match both cases
(Ok(Ok(())), Ok(Err(e)), Err(join_e)) and forward any inner Error to the
existing callback/response path; e.g., use .and_then(...) or a match on the join
result to convert Ok(Err(e)) into a callback error invocation (same way
Err(join_e) is handled) so tokenization/forward/tensor/lock errors from the
closure reach the callback.

In `@packages/core/index.d.cts`:
- Around line 720-724: The chatStream callback signature currently requires a
ChatStreamChunk even on errors; update the callback parameter in the declaration
for chatStream so the second parameter is optional (change (err: Error | null,
chunk: ChatStreamChunk) => void to (err: Error | null, chunk?: ChatStreamChunk)
=> void) for all overloads (referencing chatStream, ChatStreamChunk,
Qwen35ChatConfig, ChatStreamHandle) and also update the Rust ts_args_type source
that generates these TypeScript declarations so regeneration preserves chunk as
optional.

---

Nitpick comments:
In `@packages/lm/src/stream.ts`:
- Around line 31-32: Rename the module-level constants _nativeDenseChatStream
and _nativeMoeChatStream to UPPER_SNAKE_CASE (NATIVE_DENSE_CHAT_STREAM and
NATIVE_MOE_CHAT_STREAM) to follow the repo's constant naming convention; update
every reference to these constants (e.g., where
Qwen35ModelNative.prototype.chatStream and
Qwen35MoeModelNative.prototype.chatStream are assigned) so the new symbol names
are used consistently across the file.
- Around line 83-92: The final-chunk assembly in the generator currently uses
non-null assertions on chunk.finishReason, chunk.numTokens, and chunk.rawText
when chunk.done is true (see the branch using chunk.done and the ChatStreamFinal
yield). Add a defensive runtime check inside that branch that verifies
chunk.finishReason, chunk.numTokens, and chunk.rawText are not undefined/null
and throw a clear Error (or reject) if any are missing, instead of using the !
assertions; then construct and yield the ChatStreamFinal only after the checks
pass so consumers never receive an incomplete final chunk.
- Around line 125-127: The current override of chatStream using
"@ts-expect-error" masks a type mismatch; refactor Qwen35Model and
Qwen35MoeModel to avoid suppressing the error by either (A) moving from
inheritance to composition: remove the direct inheritance of the native class,
add a private/native instance field (e.g., _nativeDenseChatStream or the native
class instance), and delegate chatStream to
_createChatStream(this._nativeInstance, this, messages, config), or (B) keep
inheritance but add explicit TypeScript overloads for chatStream that declare
both the original base signature and the AsyncGenerator signature before the
implementation so the override is properly typed; ensure references to
chatStream, _createChatStream, _nativeDenseChatStream, Qwen35Model, and
Qwen35MoeModel are updated accordingly and remove the `@ts-expect-error` comment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f5e7d919-b891-441b-b997-5555e1f4cb49

📥 Commits

Reviewing files that changed from the base of the PR and between 9ec00c2 and f33e5ba.

📒 Files selected for processing (8)
  • __test__/models/qwen35-stream.test.ts
  • crates/mlx-core/src/models/qwen3_5/model.rs
  • crates/mlx-core/src/models/qwen3_5_moe/model.rs
  • packages/core/index.cjs
  • packages/core/index.d.cts
  • packages/lm/src/index.ts
  • packages/lm/src/models/model-loader.ts
  • packages/lm/src/stream.ts

Comment thread __test__/models/qwen35-stream.test.ts Resolved
Comment thread packages/core/index.d.cts Resolved
The spawn_blocking closure returns Result<(), Error>, so after .await
the result type is Result<Result<(), Error>, JoinError>. The previous
code only matched the outer Err (JoinError/panic), silently dropping
inner errors (tokenization failures, lock poisoning, array ops).
This caused the TypeScript AsyncGenerator to hang forever waiting for
a chunk that would never arrive.

Fix: use match on both Ok(Err(e)) and Err(e) to propagate both
inner closure errors and outer join errors via the callback.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit c81a084 into main Mar 12, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/chat-stream-api branch March 12, 2026 02:22
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
Add token-by-token streaming for interactive UIs via AsyncGenerator. The
Rust decode loop pushes each token through a ThreadsafeFunction
callback, and the TypeScript layer wraps it into `async *chatStream()`
directly on the model classes.

- Rust: chat_stream() on Qwen3_5Model and Qwen3_5MoeModel using
ThreadsafeFunction with cancellation via Arc<AtomicBool>
- TypeScript: Qwen35Model/Qwen35MoeModel subclasses override
chatStream() as AsyncGenerator<ChatStreamEvent>
- Cancellation automatic via generator finally block on break/return
- ModelLoader returns subclasses so loadPretrained() includes streaming

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Adds new token-by-token streaming generation paths in the Rust Qwen3.5
dense/MoE models and bridges them to JS via threadsafe callbacks, which
touches core inference loops and concurrency/cancellation behavior.
> 
> **Overview**
> Adds a **streaming chat** capability for Qwen3.5 dense and MoE models:
Rust now exposes `chat_stream()` that emits per-token `ChatStreamChunk`
callbacks and returns a `ChatStreamHandle` that can `cancel()` an
in-flight generation.
> 
> Updates the JS/TS surface to include
`ChatStreamChunk`/`ChatStreamHandle` types and wraps the native callback
API into an `AsyncGenerator`-based `chatStream()` via new
`packages/lm/src/stream.ts`, with automatic cancellation in a `finally`
block; `ModelLoader`/exports are adjusted so `loadPretrained()` returns
these streaming-enabled subclasses. Adds tests validating the
callback-to-async-iterator bridge, final-chunk field mapping,
cancellation on early break, and error propagation.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
09a0116. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Streaming chat for Qwen3.5 and Qwen3.5 MoE: real-time token streaming
via callback or async iterator, immediate stream handle with cancel(),
incremental delta events and a final event including finishReason,
toolCalls, thinking, token counts, and raw text; supports cancellation
and error propagation.

* **Tests**
* Added tests validating streaming tokens, final-chunk metadata,
cancellation behavior, and error propagation.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
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