Repository navigation
feat: add chatStream() streaming API for Qwen3.5 models - #28
Conversation
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]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
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 |
- 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]>
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (3)
packages/lm/src/stream.ts (3)
31-32: Rename these module-level constants toUPPER_SNAKE_CASE.
_nativeDenseChatStreamand_nativeMoeChatStreamstand out from the package's constant naming convention.NATIVE_DENSE_CHAT_STREAM/NATIVE_MOE_CHAT_STREAMwould 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
ChatStreamChunkstruct definesfinishReason,numTokens, andrawTextasOption<T>types. While all current implementations wrap these inSome()when emitting a final chunk (done: true), the type system allowsNone. 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
undefinedthrough aChatStreamFinal.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-errorsuppression 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:
- Composition: Delegate to a native instance instead of inheriting from it, or
- 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
Qwen35ModelandQwen35MoeModel.🤖 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
📒 Files selected for processing (8)
__test__/models/qwen35-stream.test.tscrates/mlx-core/src/models/qwen3_5/model.rscrates/mlx-core/src/models/qwen3_5_moe/model.rspackages/core/index.cjspackages/core/index.d.ctspackages/lm/src/index.tspackages/lm/src/models/model-loader.tspackages/lm/src/stream.ts
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]>
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]>
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.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-tokenChatStreamChunkcallbacks and returns aChatStreamHandlethat cancancel()an in-flight generation.Updates the JS/TS surface to include
ChatStreamChunk/ChatStreamHandletypes and wraps the native callback API into anAsyncGenerator-basedchatStream()via newpackages/lm/src/stream.ts, with automatic cancellation in afinallyblock;ModelLoader/exports are adjusted soloadPretrained()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
Tests