Skip to content
Open
Prev Previous commit
Next Next commit
ai/openai: split the error status mapping out of post_json_once
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>
  • Loading branch information
12458 committed Nov 26, 2026
commit c8193546463ac97a467c9575473a945444538170
25 changes: 17 additions & 8 deletions src/ai/openai_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,6 @@ async fn post_json_once<T: DeserializeOwned>(
}

let status = res.status();
let status_code = status.as_u16();

let retry_after_duration = res
.headers()
Expand All @@ -413,10 +412,20 @@ async fn post_json_once<T: DeserializeOwned>(

let error_text = redact_secret(&res.text().await.unwrap_or_default());

match status_code {
Err(status_error(status, retry_after_duration, error_text))
}

/// Types an error status by what retrying can do about it. `error_text`
/// is the redacted body that came with it.
pub fn status_error(
status: reqwest::StatusCode,
retry_after_duration: Option<Duration>,
error_text: String,
) -> OpenAiCompatError {
match status.as_u16() {
429 if is_insufficient_quota(&error_text) => {
tracing::error!("OpenAI quota exhausted: {}", error_text);
Err(OpenAiCompatError::QuotaExhausted(error_text))
OpenAiCompatError::QuotaExhausted(error_text)
}
429 => {
let default_retry = retry_after_duration.unwrap_or(Duration::from_secs(60));
Expand All @@ -429,17 +438,17 @@ async fn post_json_once<T: DeserializeOwned>(
"OpenAI 429 Rate Limit. Retry in {}s",
retry_duration.as_secs_f64()
);
Err(OpenAiCompatError::RateLimitExceeded(retry_duration))
OpenAiCompatError::RateLimitExceeded(retry_duration)
}
401 | 403 => Err(OpenAiCompatError::AuthenticationError(error_text)),
401 | 403 => OpenAiCompatError::AuthenticationError(error_text),
500..=599 => {
tracing::warn!("OpenAI Server Error {}: {}", status, error_text);
Err(OpenAiCompatError::TransientError(
OpenAiCompatError::TransientError(
retry_after_duration.unwrap_or(Duration::from_secs(0)),
error_text,
))
)
}
_ => Err(OpenAiCompatError::ApiError(status, error_text)),
_ => OpenAiCompatError::ApiError(status, error_text),
}
}

Expand Down