Repository navigation
Add streaming responses to LLM provider interface - #57
Conversation
Issue #44: Add StreamWithTools to Provider interface with callback-based streaming. Scoped to providers + OpenAI API endpoint for this iteration. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Adds StreamEvent types and StreamWithTools method with callback-based streaming API. Updates mock providers in test files. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Uses SDK's Messages.NewStreaming + Accumulate for token-by-token delivery. CompleteWithTools now delegates to StreamWithTools(nil). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Parses SSE line-by-line, emits text deltas via callback, accumulates tool call deltas by index. CompleteWithTools now delegates to StreamWithTools(nil). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Phase 1 streams tokens directly from the provider via StreamFromProvider callback. Phase 2 keeps simulated streaming via the existing StreamResponse function. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis PR implements token-by-token streaming support for the LLM provider interface and wires it through the OpenAI-compatible API endpoint. New ChangesProvider Streaming Feature
Sequence Diagram(s)sequenceDiagram
participant Client
participant APIHandler as OpenAI API<br/>Handler
participant Provider
participant SSEWriter as HTTP Response<br/>(SSE)
Client->>APIHandler: POST /chat/completions<br/>(stream=true)
APIHandler->>APIHandler: Resolve model, generate ID
APIHandler->>Provider: StreamWithTools(ctx, msgs, tools, onEvent)
loop For each stream event
Provider->>Provider: Parse/accumulate<br/>(SSE or SDK event)
Provider->>APIHandler: onEvent(StreamEventTextDelta)
APIHandler->>SSEWriter: Write chunk (text delta)
SSEWriter->>Client: SSE chunk
end
Provider->>APIHandler: onEvent(StreamEventDone)<br/>with usage
APIHandler->>SSEWriter: Write final chunk<br/>(finish_reason)
SSEWriter->>Client: SSE [DONE]
Provider->>APIHandler: Return accumulated Response
APIHandler->>Client: Stream complete
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
- Log malformed SSE chunks with slog.Debug instead of silently skipping - Send SSE error event to client when streaming fails Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
internal/openaiapi/stream.go (1)
72-137: 💤 Low valueLGTM for
StreamFromProvideritself — SSE header setup, role chunk, and per-event dispatch are correct.Note: the
flushreturn value is silently discarded at the call site inhandler.go(onEvent, _ := StreamFromProvider(...)). Since everyonEventinvocation already callsflusher.Flush(), this is harmless today, but the exported function API returning an unused closure is confusing. Consider either always using the return or removing it from the signature.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/openaiapi/stream.go` around lines 72 - 137, The StreamFromProvider function returns an unused flush closure which is confusing; remove the second return value and all related flush code instead: update StreamFromProvider signature to only return onEvent func(llm.StreamEvent), delete the local flush func and all references to the variable (but keep using flusher.Flush() inside onEvent), and update callers (e.g., the site that does onEvent, _ := StreamFromProvider(...) in handler.go) to only receive one return value. Ensure compilation by removing any places that expect the second return.internal/openai/openai.go (2)
494-510: ⚡ Quick winTool-call reconstruction assumes contiguous 0-based indices.
Iterating with
for i := 0; i < len(toolCalls); i++and looking uptoolCalls[i]silently drops any tool call whoseindexisn't dense from 0 (e.g., if a backend ever emits indices0, 2or starts at 1). Iterate over the actual keys in sorted order so reconstruction is robust to whatever the upstream sends.♻️ Proposed fix
+ // Convert accumulated tool calls to response, sorted by index. + indices := make([]int, 0, len(toolCalls)) + for idx := range toolCalls { + indices = append(indices, idx) + } + sort.Ints(indices) - // Convert accumulated tool calls to response - for i := 0; i < len(toolCalls); i++ { - tc, ok := toolCalls[i] - if !ok { - continue - } + for _, idx := range indices { + tc := toolCalls[idx] var args map[string]any rawArgs := tc.ArgsJSON.String() if err := json.Unmarshal([]byte(rawArgs), &args); err != nil { args = map[string]any{"_raw": rawArgs} } resp.ToolCalls = append(resp.ToolCalls, llm.ToolCall{ ID: tc.ID, Name: tc.Name, Args: args, }) }Add
"sort"to the import block.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/openai/openai.go` around lines 494 - 510, The current reconstruction loop assumes toolCalls is a dense 0-based slice by using for i := 0; i < len(toolCalls); i++ and toolCalls[i]; instead iterate the actual map keys of toolCalls, collect and sort the keys (add "sort" to imports), then loop over the sorted keys to fetch each tc, decode tc.ArgsJSON as before, and append to resp.ToolCalls (llm.ToolCall) so missing/non-contiguous indices are handled correctly.
376-463: 💤 Low valueConsider checking
ctx.Err()inside the scan loop.The design doc explicitly states the streaming loop should check
ctx.Err()to exit early on cancellation. Today this relies entirely on the HTTP transport tearing down the body when the request context is cancelled, which works in practice but adds latency before the loop notices. A cheapselect/ctx.Err()check at the top of each iteration makes cancellation deterministic and matches the documented contract.♻️ Proposed snippet
for scanner.Scan() { + if err := ctx.Err(); err != nil { + return nil, err + } line := scanner.Text()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/openai/openai.go` around lines 376 - 463, Inside the SSE scanning loop that uses bufio.NewScanner(httpResp.Body) (the scanner loop in openai.go), add a cheap ctx cancellation check (e.g. test ctx.Err() or a non-blocking select on ctx.Done()) at the top of each iteration and exit the loop immediately when cancelled; ensure you propagate the cancellation error (use ctx.Err()) instead of waiting for the HTTP body to close so the function returns deterministically on context cancellation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/anthropic/anthropic.go`:
- Around line 200-206: The code that emits text deltas on the Anthropic stream
directly reads event.Delta.Text (inside the block checking event.Type ==
"content_block_delta"); update this to use the SDK's discriminated-union
accessors: first assert the event to the concrete ContentBlockDeltaEvent via
event.AsAny() or a type switch on the event (e.g., handling
ContentBlockDeltaEvent), then perform a second type switch on the event.Delta
(the discriminated union) to handle the TextDelta variant and extract its text
safely, and only then call onEvent with llm.StreamEventTextDelta; modify the
logic in the streaming handler where ContentBlockDeltaEvent is processed to
follow this two-level AsAny/type-switch pattern instead of directly accessing
.Delta.Text.
In `@internal/openai/openai.go`:
- Line 389: The scanner created with bufio.NewScanner(httpResp.Body) can hit
bufio.ErrTooLong for large SSE lines; update the code that constructs the
scanner (the scanner variable from bufio.NewScanner(httpResp.Body)) to call
scanner.Buffer with a larger maximum token size (e.g., several MiB) immediately
after creation — e.g., create the scanner, then invoke
scanner.Buffer(make([]byte, 0, initialSize), maxSize) with maxSize set to a few
megabytes to prevent token-too-long errors during streaming.
In `@internal/openaiapi/handler.go`:
- Around line 107-112: The handler currently calls StreamError twice because
Provider.StreamWithTools already emits StreamEventError via the onEvent
callback; update the error branch in the handler (the block after calling
h.Provider.StreamWithTools / the onEvent variable) to remove the redundant
StreamError(w, "LLM error: "+err.Error()) call and keep only logging (e.g.,
slog.Error("streaming failed", "error", err)); alternatively, if you want to
preserve handler-driven emission for providers that might not callback, add a
boolean sentinel (e.g., sentError) set by the onEvent handler when it sees
StreamEventError and only call StreamError from the handler when sentError is
false—refer to StreamWithTools, onEvent, and StreamError to locate where to
change the code.
---
Nitpick comments:
In `@internal/openai/openai.go`:
- Around line 494-510: The current reconstruction loop assumes toolCalls is a
dense 0-based slice by using for i := 0; i < len(toolCalls); i++ and
toolCalls[i]; instead iterate the actual map keys of toolCalls, collect and sort
the keys (add "sort" to imports), then loop over the sorted keys to fetch each
tc, decode tc.ArgsJSON as before, and append to resp.ToolCalls (llm.ToolCall) so
missing/non-contiguous indices are handled correctly.
- Around line 376-463: Inside the SSE scanning loop that uses
bufio.NewScanner(httpResp.Body) (the scanner loop in openai.go), add a cheap ctx
cancellation check (e.g. test ctx.Err() or a non-blocking select on ctx.Done())
at the top of each iteration and exit the loop immediately when cancelled;
ensure you propagate the cancellation error (use ctx.Err()) instead of waiting
for the HTTP body to close so the function returns deterministically on context
cancellation.
In `@internal/openaiapi/stream.go`:
- Around line 72-137: The StreamFromProvider function returns an unused flush
closure which is confusing; remove the second return value and all related flush
code instead: update StreamFromProvider signature to only return onEvent
func(llm.StreamEvent), delete the local flush func and all references to the
variable (but keep using flusher.Flush() inside onEvent), and update callers
(e.g., the site that does onEvent, _ := StreamFromProvider(...) in handler.go)
to only receive one return value. Ensure compilation by removing any places that
expect the second return.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Enterprise
Run ID: 3a2249f3-e2eb-4350-9cd5-4b1d47a5c8b4
📒 Files selected for processing (11)
docs/superpowers/plans/2026-05-05-provider-streaming.mddocs/superpowers/specs/2026-05-05-provider-streaming-design.mdinternal/anthropic/anthropic.gointernal/openai/openai.gointernal/openai/openai_test.gointernal/openaiapi/handler.gointernal/openaiapi/handler_test.gointernal/openaiapi/stream.gopkg/llm/provider.gopkg/llm/types.gopkg/tools/loop_test.go
|
|
||
| if len(chatResp.Choices) == 0 { | ||
| return nil, fmt.Errorf("empty response from API") | ||
| scanner := bufio.NewScanner(httpResp.Body) |
There was a problem hiding this comment.
SSE scanner can fail with token too long on large chunks.
bufio.Scanner defaults to a 64 KiB max token size. OpenAI-compatible streams routinely emit single SSE lines that exceed this when tool-call arguments contain large strings or when backends batch deltas (vLLM/LiteLLM in particular). When that happens, scanner.Scan() returns false with bufio.ErrTooLong, the scanner.Err() branch fires, and the request fails mid-stream. Raise the buffer to at least a few MiB.
🛡️ Proposed fix
scanner := bufio.NewScanner(httpResp.Body)
+ // SSE lines may carry large tool-call argument chunks; bump from the
+ // default 64KiB to avoid bufio.ErrTooLong on big deltas.
+ scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for scanner.Scan() {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| scanner := bufio.NewScanner(httpResp.Body) | |
| scanner := bufio.NewScanner(httpResp.Body) | |
| // SSE lines may carry large tool-call argument chunks; bump from the | |
| // default 64KiB to avoid bufio.ErrTooLong on big deltas. | |
| scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024) | |
| for scanner.Scan() { |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/openai/openai.go` at line 389, The scanner created with
bufio.NewScanner(httpResp.Body) can hit bufio.ErrTooLong for large SSE lines;
update the code that constructs the scanner (the scanner variable from
bufio.NewScanner(httpResp.Body)) to call scanner.Buffer with a larger maximum
token size (e.g., several MiB) immediately after creation — e.g., create the
scanner, then invoke scanner.Buffer(make([]byte, 0, initialSize), maxSize) with
maxSize set to a few megabytes to prevent token-too-long errors during
streaming.
- Use SDK type-safe accessors for Anthropic stream text deltas - Remove double StreamError emission in handler (provider already sends error via onEvent callback) - Remove unused flush return from StreamFromProvider - Add ctx cancellation check in OpenAI SSE scanner loop Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Summary
Adds
StreamWithToolsto thellm.Providerinterface with acallback-based streaming API, implements native streaming in both
Anthropic and OpenAI providers, and wires real token-by-token
streaming into the OpenAI-compatible API endpoint for phase 1 mode.
StreamWithTools(ctx, messages, tools, onEvent)— callsonEventwithTextDeltaevents as tokens arrive, returnsaccumulated
*ResponseMessages.NewStreaming+Accumulatebufio.Scanner,accumulates tool call deltas by index
the provider; phase 2 keeps simulated streaming (feat: add real streaming to agentic tool loop (phase 2) #56)
CompleteWithToolsto delegate toStreamWithTools(ctx, msgs, tools, nil)Verified with
Closes #44
Test plan
streaming, nil callback, tool call deltas)
make test/make lint/make build— all greenSummary by CodeRabbit
New Features
Documentation
Tests