Skip to content

Add streaming responses to LLM provider interface - #57

Merged
pavelanni merged 8 commits into
mainfrom
feature/provider-streaming
May 5, 2026
Merged

pavelanni merged 8 commits into
mainfrom
feature/provider-streaming

Conversation

@pavelanni

@pavelanni pavelanni commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds StreamWithTools to the llm.Provider interface with a
callback-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) — calls
    onEvent with TextDelta events as tokens arrive, returns
    accumulated *Response
  • Anthropic: uses SDK's Messages.NewStreaming + Accumulate
  • OpenAI: parses SSE line-by-line with bufio.Scanner,
    accumulates tool call deltas by index
  • OpenAI API endpoint: phase 1 streams tokens directly from
    the provider; phase 2 keeps simulated streaming (feat: add real streaming to agentic tool loop (phase 2) #56)
  • Both providers simplify CompleteWithTools to delegate to
    StreamWithTools(ctx, msgs, tools, nil)

Verified with

  • curl: tokens arrive progressively (20+ chunks for longer responses)
  • Open WebUI: real-time token rendering
  • Unit tests: SSE parsing, tool call accumulation, nil callback

Closes #44

Test plan

  • OpenAI provider: 3 tests with httptest mock server (text
    streaming, nil callback, tool call deltas)
  • Handler mock updated with StreamWithTools
  • All existing tests pass (no regressions)
  • make test / make lint / make build — all green
  • Manual curl verification (streaming and non-streaming)

Summary by CodeRabbit

  • New Features

    • Added token-by-token streaming support for LLM provider responses with tool/function calling capabilities
    • Enabled real streaming through the OpenAI-compatible API endpoint
  • Documentation

    • Added implementation plan and design specification for provider streaming
  • Tests

    • Added comprehensive test coverage for streaming functionality across multiple providers

pavelanni added 6 commits May 5, 2026 12:34
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]>
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 31 minutes and 14 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 522cef34-7bd3-47ee-9123-9a70b71609fd

📥 Commits

Reviewing files that changed from the base of the PR and between 1555020 and 3c4b758.

📒 Files selected for processing (4)
  • internal/anthropic/anthropic.go
  • internal/openai/openai.go
  • internal/openaiapi/handler.go
  • internal/openaiapi/stream.go
📝 Walkthrough

Walkthrough

This PR implements token-by-token streaming support for the LLM provider interface and wires it through the OpenAI-compatible API endpoint. New StreamEvent types and a StreamWithTools method are added to the provider contract, with native implementations for Anthropic (using SDK streaming) and OpenAI (using SSE parsing), while the OpenAI API handler branches "real streaming" requests to provider streaming and keeps existing tool-loop simulated streaming for phase 2.

Changes

Provider Streaming Feature

Layer / File(s) Summary
Type Definitions
pkg/llm/types.go
Introduces StreamEventType constants (StreamEventTextDelta, StreamEventDone, StreamEventError) and StreamEvent struct with Type, Content, and Usage fields.
Provider Interface
pkg/llm/provider.go
Adds StreamWithTools(ctx, messages, tools, onEvent func(StreamEvent)) method returning (*Response, error) to the Provider interface.
Anthropic Provider Streaming
internal/anthropic/anthropic.go
Implements StreamWithTools using Anthropic SDK's Messages.NewStreaming, accumulating events and emitting StreamEventTextDelta for text, StreamEventError on failure, and StreamEventDone with usage. Simplifies CompleteWithTools to delegate to StreamWithTools.
OpenAI Provider Streaming
internal/openai/openai.go
Implements StreamWithTools with SSE parsing via bufio.Scanner, reconstructing tool calls from streamed deltas by index, emitting StreamEventTextDelta, StreamEventError, and StreamEventDone. Removes prior non-streaming tool request/response structs and delegates CompleteWithTools to StreamWithTools.
OpenAI Streaming Tests
internal/openai/openai_test.go
Adds three test scenarios using httptest SSE server: TestStreamWithTools (text deltas with callback), TestStreamWithToolsNilCallback (streaming without callback), and TestStreamWithToolsToolCalls (streamed tool-call argument accumulation and parsing).
API Handler & Streaming Wiring
internal/openaiapi/handler.go, internal/openaiapi/stream.go
ChatCompletion refactors to route streaming to streamCompletion helper; streamCompletion handles phase 2 tool-loop streaming and phase 1 real provider streaming. New StreamFromProvider translates provider StreamEvent callbacks into OpenAI SSE chunk emission.
Handler Test Mock
internal/openaiapi/handler_test.go
Adds StreamWithTools to mockProvider test double, delegating to CompleteWithTools and emitting simulated StreamEventTextDelta and StreamEventDone events.
Tool Loop Test Mock
pkg/tools/loop_test.go
Adds StreamWithTools to test mock provider, delegating to CompleteWithTools with background context.
Documentation
docs/superpowers/plans/2026-05-05-provider-streaming.md, docs/superpowers/specs/2026-05-05-provider-streaming-design.md
Implementation plan and design specification defining streaming event types, provider interface additions, provider-side implementations (Anthropic SDK streaming, OpenAI SSE parsing), API endpoint phase 1 (real streaming) and phase 2 (tool-loop simulated streaming) behavior, error handling, and testing approach.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main addition in this PR: streaming support via a new StreamWithTools method added to the LLM Provider interface.
Linked Issues check ✅ Passed The PR implements all core objectives from issue #44: adds StreamWithTools to Provider with typed StreamEvents, implements native streaming for Anthropic and OpenAI, delegates CompleteWithTools to StreamWithTools, and wires real streaming into OpenAI API endpoint.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #44: documentation, interface definitions, provider implementations, API handler updates, tests, and mocks. No unrelated refactoring or feature additions are present.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/provider-streaming

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.

- 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]>
@pavelanni
pavelanni marked this pull request as ready for review May 5, 2026 17:28

@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: 3

🧹 Nitpick comments (3)
internal/openaiapi/stream.go (1)

72-137: 💤 Low value

LGTM for StreamFromProvider itself — SSE header setup, role chunk, and per-event dispatch are correct.

Note: the flush return value is silently discarded at the call site in handler.go (onEvent, _ := StreamFromProvider(...)). Since every onEvent invocation already calls flusher.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 win

Tool-call reconstruction assumes contiguous 0-based indices.

Iterating with for i := 0; i < len(toolCalls); i++ and looking up toolCalls[i] silently drops any tool call whose index isn't dense from 0 (e.g., if a backend ever emits indices 0, 2 or 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 value

Consider 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 cheap select / 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

📥 Commits

Reviewing files that changed from the base of the PR and between f2c6e85 and 1555020.

📒 Files selected for processing (11)
  • docs/superpowers/plans/2026-05-05-provider-streaming.md
  • docs/superpowers/specs/2026-05-05-provider-streaming-design.md
  • internal/anthropic/anthropic.go
  • internal/openai/openai.go
  • internal/openai/openai_test.go
  • internal/openaiapi/handler.go
  • internal/openaiapi/handler_test.go
  • internal/openaiapi/stream.go
  • pkg/llm/provider.go
  • pkg/llm/types.go
  • pkg/tools/loop_test.go

Comment thread internal/anthropic/anthropic.go Resolved
Comment thread internal/openai/openai.go

if len(chatResp.Choices) == 0 {
return nil, fmt.Errorf("empty response from API")
scanner := bufio.NewScanner(httpResp.Body)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment thread internal/openaiapi/handler.go Resolved
- 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]>
@pavelanni
pavelanni merged commit e2e2d2c into main May 5, 2026
3 checks passed
@pavelanni
pavelanni deleted the feature/provider-streaming branch May 5, 2026 18:01
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.

feat: add streaming responses to LLM provider interface

1 participant