Skip to content

ai: opt-in streaming for the Claude and OpenAI providers - #949

Open
12458 wants to merge 11 commits into
sashiko-dev:mainfrom
12458:ai-stream-responses
Open

12458 wants to merge 11 commits into
sashiko-dev:mainfrom
12458:ai-stream-responses

Conversation

@12458

@12458 12458 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Closes #947. Related: #572.

Problem

The claude provider and both OpenAI transports send non-streaming requests, so no HTTP byte arrives until generation ends. Gateways that close requests with no upstream bytes for a fixed time (often ~125 s, answered with HTTP 524) end every stage that thinks or writes longer, and each retry starts the generation over and hits the same limit.

Change

An opt-in stream setting, off by default, in [ai.claude] and [ai.openai_compat] (both api = "chat" and api = "responses"). With it on, the provider asks for a server-sent event stream and folds the events back into the exact JSON document a non-streamed request returns, which the existing code then parses. Stages see the same AiResponse either way. With it off, request bytes and code paths are unchanged.

  • src/ai/sse.rs: incremental SSE framing (LF/CRLF/CR, multi-line data, comments; a partial event at EOF is never dispatched; reading stops at the terminal event).
  • Responses: takes the response object from response.completed / .incomplete / .failed; an error event becomes a failed reply classified by the existing response_failure.
  • Chat Completions: folds deltas per choice and tool call (sends stream_options.include_usage); tolerates servers that omit [DONE], omit or reuse tool-call indices, or send empty identity fields; in-stream errors are classified like the status they name.
  • Anthropic Messages: an explicit, pure state machine (src/ai/claude_stream.rs) with its transition table documented, each transition traced, and illegal transitions reported as typed errors. Blocks are kept as JSON so unmodelled block types reach the parser unchanged.
  • Error classes match the non-streamed path: a stream cut before its terminal event is transient like a dropped body; a malformed stream is fatal like an unparseable body.
  • Separate commit: a Responses failure with rate_limit_exceeded is now a rate limit instead of fatal; a stream can only report a 429 that way.

Design: designs/DESIGN_STREAMED_RESPONSES.md. Docs: docs/configuration.md, docs/llm-providers.md.

api_timeout_secs still bounds the whole request on the OpenAI clients; turning it into an idle timeout is left for a follow-up.

Testing

  • make check-pr passes; every commit builds on its own.
  • Unit and mock-server tests per format, including an equivalence check that streamed and plain replies produce the same AiResponse (recorded Responses fixtures, Chat text and parallel tool calls, Claude thinking + text + tool use), one test per row of the Claude transition table, and cut, error and malformed streams.
  • Live, through a local proxy in front of a gateway with a ~125 s idle cutoff, one ~9,000-word request per route:
Route stream off stream on
Claude Messages 524 after 125.7 s 200 after 200 s
OpenAI Responses (GPT) 524 after 125.2 s 200 after 163 s
Responses translated to Gemini 524 after 125.2 s 200 after 215 s
Chat Completions 524 after 125.6 s 200 after 238 s
  • A sashiko review --project sashiko --agent --cheap with Claude and stream = true completed through the same proxy, with multi-turn tool calls over the stream.

@sashiko-bot

sashiko-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown

Sashiko review

Commit 2/10 — 7ca54cb7 ai: add server-sent events framing for streamed replies

  • [LOW] src/ai/sse.rs: next_line() returns None whenever a carriage return is
    the last byte in the buffer so it can wait for a following newline. When an
    event ends with a bare-CR blank line (\r\r) and no more bytes follow, the
    second CR remains buffered in SseParser::pending. At EOF, read_events()
    returns StreamEnd::Eof without flushing the trailing CR, dropping the last
    event, and if the server keeps the connection open after a bare-CR terminal
    event, read_events() stalls waiting for another chunk.

Commit 5/10 — 34e05d31 ai/openai: rebuild streamed chat completions

  • [MEDIUM] src/ai/openai.rs: ChatStream::on_event() unwraps chunk["error"]
    and passes the inner object to stream_error(), which serializes it without
    the outer {"error": ...} envelope before calling status_error(). Because
    is_insufficient_quota() and rejects_temperature_parameter() in
    src/ai/openai_common.rs parse the JSON string and look up fields under
    body["error"], an in-stream error chunk with code 429 and type
    insufficient_quota is classified as RateLimitExceeded instead of the fatal
    QuotaExhausted, and a 400 or 422 in-stream error chunk misses the
    structured temperature refusal check. Serialize the outer error envelope
    or pass the full chunk so status_error() sees the same JSON structure as a
    non-streamed HTTP error response.

Full review and stage logs on sashiko.sashiko.dev

@12458
12458 force-pushed the ai-stream-responses branch from cae1adf to 7d7fd0e Compare November 26, 2026 15:56
@12458
12458 marked this pull request as ready for review November 26, 2026 16:01
@sashiko-bot

sashiko-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

Sashiko review — v2

✓ No issues found across 10 commits.

Full review log on sashiko.sashiko.dev

12458 added 10 commits November 26, 2026 10:14
Providers send non-streaming requests, so no HTTP byte arrives until a
generation ends, and gateways that close idle requests (HTTP 524 after
100 to 125 seconds is common) end every long stage. The retry starts
the generation again and hits the same limit.

Describe an opt-in stream setting for the Claude provider and both
OpenAI transports. The SSE events are folded back into the document
the endpoint would have returned without streaming and parsed by the
existing code, so a stage sees the same response either way. The
Anthropic format is handled by an explicit state machine whose
transitions are listed, logged and tested one by one.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
Providers will ask for streamed replies only to keep bytes flowing
through gateways that close idle requests, and fold the events back
into the document a non-streamed request returns.

Add the framing they share: an incremental parser that turns body
chunks into complete events, and a reader that hands each event to a
provider callback until the callback marks one as the last. An event
counts only once its terminating blank line has arrived, so the partial
event a dropped connection leaves behind is never dispatched, and the
reader stops at the terminal event so a server that holds the
connection open cannot stall the request. It uses Response::chunk, so
no reqwest feature is added.

The test HTTP helpers gain variants that take a content type.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
A non-streamed reply sends nothing until the model is done, and
gateways that close idle requests end every long generation; the
retry starts the generation over and meets the same limit.

Let post_json take a stream assembler. When one is given and the reply
is an event stream, the events are folded back into the document a
non-streamed request returns, and that document is decoded by the same
code as a plain reply. A plain reply to a streamed request is still
read as a document. A transport failure or a body that ends before the
terminal event is transient, as a dropped body is today, and an event
that breaks the format is fatal, as an unparseable body is.

On the Responses transport every terminal event carries the finished
response object, so the assembler takes it and skips everything else.
An error event becomes a failed response carrying its code and message,
which the existing failure handling classifies. The client asks for a
stream only through with_stream, so nothing changes until a setting
enables it.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
A streamed chat completion can report a failure inside the stream,
with the HTTP status it stands for as its code. Move the mapping from
status to OpenAiCompatError into status_error so that failure can be
typed by the same rules as a reply that carries the status.

No functional change.

Signed-off-by: Shang En Sim <sim@shangen.org>
Give the chat transport the stream assembler the Responses transport
has. A streamed request also asks for stream_options.include_usage,
without which a stream reports no token counts.

Each chunk's deltas are folded into the choice they name. Text fields
are concatenated. A tool call delta continues the call its index names,
takes its id, type and name from the first delta carrying them, and
concatenates its argument fragments; a repeated name or type must
match. Some servers give every call index 0 or leave the index out and
send each call whole, so a delta naming a new id starts a new call and
one without an index continues the last call. finish_reason, usage and
service_tier keep the last value sent. Text that never arrived is left
out of the rebuilt message, as a plain reply that only calls tools has
no content while the first chunk of its stream carries an empty one.

The stream ends with data: [DONE]. One that ends without it is still
complete when every choice has finished, other than with "error", as
some servers close after the last chunk; anything else was cut off and
is transient.

An error object inside the stream fails the way the HTTP status it
names would, given as a number, a numeric string, or a kind such as
server_error, which OpenAI sends with a null code. An error none of
these place is fatal. With streaming on, extra_body may not set stream
or stream_options.

The client streams only through with_stream, so nothing changes until a
setting enables it.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
Gateways that close requests with no upstream bytes for a while,
often with an HTTP 524 after 100 to 125 seconds, end every review stage
that generates for longer, and each retry starts over and meets the
same limit.

Add stream to the openai_compat settings. It makes both transports ask
for an event stream and rebuild the reply from it, so bytes flow while
the model works and stages see the same response. It is off by default,
so existing configurations send the same requests as before, and it
stays out of the response cache identity because the rebuilt reply is
the same as the plain one.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
A streamed Messages reply can report a failure inside the stream as an
error event, whose type names the HTTP status it stands for. Move the
mapping from status to ClaudeError into status_error so that failure
can be typed by the same rules as a reply that carries the status.

No functional change.

Signed-off-by: Shang En Sim <sim@shangen.org>
Give the Claude provider the same choice the OpenAI transports have:
ask for an event stream, so bytes flow while the model works, and fold
the events back into the message a non-streamed request returns, which
the existing code then decodes.

The content-block lifecycle decides whether a message is complete, so
the stream is folded by an explicit state machine in claude_stream.rs.
Its transition function is pure, its table is in the module comment,
each transition is traced, and any pair outside the table is a typed
error naming the state and the event. Blocks are kept as the JSON
objects their start events carry with deltas applied, so a block type
the parser does not model reaches it unchanged. Unknown event types are
skipped as the API documents; an unknown delta type is an error,
since dropping it would lose part of a block.

A body that ends before message_stop is transient, like a dropped plain
body; an error event is typed like the HTTP status its error type
stands for; a stream that breaks the format is fatal. A tool input
that is not valid JSON is accepted only in the last block of a reply
cut off by max_tokens, which reaches the session as truncated as it
does today.

The stream field is left out of the request body unless set, and the
client streams only through with_stream, so nothing changes until a
setting enables it.

The design document is updated with the rule for a tool input cut off
by max_tokens.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
Add stream to the claude settings. It makes the provider ask for an
event stream and rebuild the message from it, so a gateway that closes
requests with no upstream bytes for a while no longer cuts off long
generations. It is off by default, so existing configurations send the
same requests as before.

Link: sashiko-dev#947
Signed-off-by: Shang En Sim <sim@shangen.org>
Once a streamed reply's 200 and headers have gone out, the endpoint can
only report a rate limit inside the stream, as a failed response or an
error event with code rate_limit_exceeded. response_failure treated
every code but server_error as fatal, so a limit that a plain request
would get as a retried 429 ended the review.

Classify rate_limit_exceeded as a rate limit that waits as long as a
429 without a Retry-After does. A plain reply carrying the same failure
is classified the same way; insufficient_quota, which no wait fixes,
stays fatal.

Link: sashiko-dev#947
Fixes: 19171a1 ("ai: Add a /v1/responses transport for the openai provider")
Signed-off-by: Shang En Sim <sim@shangen.org>
@12458
12458 force-pushed the ai-stream-responses branch from 7d7fd0e to fbaf79a Compare November 26, 2026 16:17
@sashiko-bot

sashiko-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

Sashiko review — v3

Commit 8/10 — ea6dbd6b ai/claude: rebuild streamed Messages replies

  • [MEDIUM] src/ai/claude_stream.rs: MessageStream::on_event() logs the raw
    StreamError with tracing::debug!() before returning it to collect_stream(),
    which only then passes the error through loggable_body() or
    redact_secret(). If an upstream or gateway error event echoes a credential
    from the request, the unredacted secret and untruncated message are written
    to the debug log. Pass the error string through loggable_body() before
    logging it in on_event().

Full review and stage logs on sashiko.sashiko.dev

Claude stream transition errors can include provider-supplied text in
both the event name and the error detail. Run the full debug message
through loggable_body to redact credentials and bound the output
before tracing records it.

Link: https://sashiko.sashiko.dev/#/patchset/sashiko-949
Fixes: ea6dbd6 ("ai/claude: rebuild streamed Messages replies")
Signed-off-by: Shang En Sim <sim@shangen.org>
@sashiko-bot

sashiko-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown

Sashiko review — v4

Commit 5/11 — 20c7e244 ai/openai: rebuild streamed chat completions

  • [MEDIUM] src/ai/openai.rs: stream_error_status() does not map
    invalid_request_error, unsupported_value, or unsupported_parameter to
    StatusCode::BAD_REQUEST. When a gateway sends an in-stream temperature
    refusal with OpenAI's standard string code or null code instead of a
    numeric 400, stream_error() returns OpenAiCompatError::ResponseFailed.
    rejects_temperature_parameter() in src/ai/openai_common.rs only matches
    OpenAiCompatError::ApiError with 400 or 422, so post_json() aborts the
    request as a fatal error instead of stripping temperature and retrying. Map
    those client error kinds to StatusCode::BAD_REQUEST in
    stream_error_status() or match OpenAiCompatError::ResponseFailed in
    rejects_temperature_parameter().

Commit 11/11 — ac2aca73 ai/claude: sanitize streamed error logs

  • [LOW] The commit message includes a Fixes: trailer pointing to "ai/claude:
    rebuild streamed Messages replies", which is an unmerged patch earlier in
    the same series. A Fixes: trailer must only reference commits already merged
    prior to the series baseline. Remove the Fixes: trailer or fold this fix
    into the earlier patch.

Full review and stage logs on sashiko.sashiko.dev

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.

ai: stream HTTP provider responses so idle-read gateways don't cut off long generations

1 participant