Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
ai/openai: add an opt-in stream setting
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: #947
Signed-off-by: Shang En Sim <sim@shangen.org>
  • Loading branch information
12458 committed Nov 26, 2026
commit 102a695a5d5d209065f528fa5965d4e7e8f11713
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ Settings for the OpenAI providers (`provider = "openai"` or `provider = "openai-
| `extra_body` | table | empty | Top-level JSON fields added to every request body. Fields Sashiko sets itself (`model`, `messages`, `tools`, `temperature`, `max_tokens`, `max_completion_tokens`, `response_format`, `reasoning_effort`, `service_tier`) are rejected at startup; set reasoning effort with `effort` instead. |
| `api` | string | `"chat"` | Which OpenAI endpoint to speak: `"chat"` for `/v1/chat/completions`, or `"responses"` for `/v1/responses`. Only OpenAI's own API serves the latter, and it is the only endpoint that accepts function tools and a reasoning effort in the same request. |
| `service_tier` | string | -- | Processing tier, one of `"auto"`, `"default"`, `"flex"`, `"priority"`, or `"scale"`, sent as `service_tier` on both endpoints and omitted when unset. `"flex"` runs at half the standard per-token price with higher latency and more 429s, which the usual retry absorbs; raise `api_timeout_secs` to at least `900` with it, since a flex response can take longer than the default timeout and a timed-out request is retried and billed again. `"priority"` pays more for lower latency. Only OpenAI's own API accepts the field, so it is an error with `provider = "openai-compatible"`. |
| `stream` | bool | `false` | Request server-sent events on either endpoint. Sashiko assembles the full reply and accepts regular JSON as a fallback. Chat requests ask for `stream_options.include_usage` to get token counts. With streaming enabled, `extra_body` cannot set `stream` or `stream_options`. `api_timeout_secs` still bounds the whole request. |

#### `[ai.ollama]`

Expand Down
16 changes: 16 additions & 0 deletions docs/llm-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,22 @@ a chat completion only.
Setting any of them with `api = "responses"` is refused at startup
rather than ignored.

If a gateway closes idle requests, set `stream = true` for either
OpenAI transport so the endpoint can send events during generation.
Sashiko assembles the full reply before handing it to a review stage.

```toml
[ai.openai_compat]
stream = true
```

An interrupted reply is retried from the start. Chat can treat a reply
as complete without `[DONE]` if it has at least one choice and each
choice has reported a finish reason other than `error`. Chat endpoints
must accept `stream_options.include_usage`, which Sashiko requests for
token counts. Set `api_timeout_secs` to cover the longest expected
request, including generation.

`service_tier` picks the processing tier and is sent on both endpoints,
omitted when unset. `"flex"` halves the per-token price in exchange
for slower responses and a higher rate of 429s, which the usual retry
Expand Down
64 changes: 54 additions & 10 deletions src/ai/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1060,7 +1060,8 @@ pub fn create_provider_from_ai(ai: &AiSettings) -> Result<Arc<dyn AiProvider>> {
.with_reasoning_content(compat.is_some_and(|c| c.send_reasoning_content))
.with_empty_tool_call_content(
compat.is_some_and(|c| c.send_empty_tool_call_content),
);
)
.with_stream(compat.is_some_and(|c| c.stream))?;
let provider = match compat {
Some(c) => provider
.with_extra_headers(&openai::extra_headers_from_env(
Expand Down Expand Up @@ -1104,15 +1105,18 @@ pub fn create_provider_from_ai(ai: &AiSettings) -> Result<Arc<dyn AiProvider>> {
.and_then(|c| c.base_url.clone())
.unwrap_or_else(openai_responses::OpenAiResponsesClient::default_base_url);

Ok(Arc::new(openai_responses::OpenAiResponsesClient::new(
base_url,
ai.model.clone(),
context_window,
max_tokens,
ai.api_timeout_secs,
effort,
service_tier,
)?))
Ok(Arc::new(
openai_responses::OpenAiResponsesClient::new(
base_url,
ai.model.clone(),
context_window,
max_tokens,
ai.api_timeout_secs,
effort,
service_tier,
)?
.with_stream(compat.is_some_and(|c| c.stream)),
))
}
other => bail!("Unsupported openai api: {}", other),
}
Expand Down Expand Up @@ -2016,6 +2020,7 @@ mod tests {
send_empty_tool_call_content: false,
api: api.map(str::to_string),
service_tier: None,
stream: false,
session_affinity_header: None,
};

Expand All @@ -2033,6 +2038,43 @@ mod tests {
Ok(())
}

/// The stream setting reaches both transports, and a chat stream
/// refuses extra_body fields that would override its own.
#[test]
fn test_openai_stream_setting_builds_both_transports() -> Result<()> {
let mut settings = Settings::new().expect("Failed to load settings");
settings.ai.provider = "openai".to_string();
settings.ai.model = "gpt-5.4".to_string();

let parsed: crate::settings::OpenAiCompatSettings = toml::from_str("stream = true")?;
assert!(parsed.stream);
let unset: crate::settings::OpenAiCompatSettings = toml::from_str("")?;
assert!(!unset.stream, "streaming is opt-in");

for api in ["chat", "responses"] {
let mut compat = parsed.clone();
compat.api = Some(api.to_string());
settings.ai.openai_compat = Some(compat);
assert!(create_provider(&settings).is_ok(), "api = {api}");
}

let mut compat = parsed.clone();
compat
.extra_body
.insert("stream".to_string(), serde_json::Value::Bool(false));
settings.ai.openai_compat = Some(compat.clone());
let err = create_provider(&settings)
.err()
.expect("extra_body may not set stream when streaming");
assert!(err.to_string().contains("stream"), "{err:#}");

compat.stream = false;
settings.ai.openai_compat = Some(compat);
assert!(create_provider(&settings).is_ok());

Ok(())
}

/// Both transports send service_tier for OpenAI itself and refuse it
/// for a compatible endpoint rather than dropping it on the floor.
#[test]
Expand All @@ -2051,6 +2093,7 @@ mod tests {
send_empty_tool_call_content: false,
api: Some(api.to_string()),
service_tier: Some(crate::settings::ServiceTier::Flex),
stream: false,
session_affinity_header: None,
});

Expand Down Expand Up @@ -2090,6 +2133,7 @@ mod tests {
send_empty_tool_call_content: false,
api: Some("responses".to_string()),
service_tier: None,
stream: false,
session_affinity_header: None,
};

Expand Down
1 change: 1 addition & 0 deletions src/ai/openai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2326,6 +2326,7 @@ mod tests {
send_empty_tool_call_content: false,
api: None,
service_tier: None,
stream: false,
});
let provider = crate::ai::create_provider(&settings)?;

Expand Down
6 changes: 6 additions & 0 deletions src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,12 @@ pub struct OpenAiCompatSettings {
/// it with `provider = "openai-compatible"` is a configuration error.
#[serde(default)]
pub service_tier: Option<ServiceTier>,
/// Ask for each reply as an event stream, on either endpoint, and
/// rebuild the document from its events. Bytes then keep flowing while
/// the model works, which keeps gateways that close idle requests from
/// cutting off long generations. Off by default.
#[serde(default)]
pub stream: bool,
}

/// OpenAI processing tier. The set is fixed by the API rather than by the
Expand Down