Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 9 additions & 13 deletions crates/gateway/src/lifecycle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ pub(crate) fn build_chat_pump(
// Headers already went out as 200, so the refusal is said
// in the stream — and logged with the upstream's own status,
// so a throttled upstream stays 429 on the audit row.
let mut out = shaper.process(&error_frame(client, &e.to_string()));
let mut out = shaper.process(&error_frame(client, e.status_code(), &e.to_string()));
out.extend(shaper.finish());
yield Ok::<Bytes, std::convert::Infallible>(Bytes::from(out));
if let Some(tx) = done_tx.take() {
Expand Down Expand Up @@ -271,7 +271,7 @@ pub(crate) fn build_chat_pump(
tracing::warn!("{message}");
let tail = match convert.as_mut() {
Some(c) => c.fail(&message),
None => error_frame(client, &message),
None => error_frame(client, 502, &message),
};
let mut out = shaper.process(&tail);
out.extend(shaper.finish());
Expand Down Expand Up @@ -404,23 +404,19 @@ fn cut(
let mut out = shaper.process(safe);
let refusal = match convert {
Some(c) => c.fail(&message),
None => error_frame(client, &message),
None => error_frame(client, err.status_code(), &message),
};
out.extend(shaper.process(&refusal));
out.extend(shaper.finish());
out
}

/// An error in the caller's format, for a stream that was forwarded
/// untouched and so has no converter to write one.
fn error_frame(client: Dialect, message: &str) -> Vec<u8> {
let body = tw_dialect::convert::error_body(client, 502, message);
let v: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
match client {
Dialect::Chat => tw_dialect::frame::data(&v),
_ => tw_dialect::frame::named("error", &v),
}
.into_bytes()
/// A standalone error frame in the caller's format, for a stream that has
/// no converter to write one (forwarded as sent, or never opened). `status`
/// is what the error would have been as a response, and picks its class.
fn error_frame(client: Dialect, status: i64, message: &str) -> Vec<u8> {
let status = u16::try_from(status).unwrap_or(502);
tw_dialect::convert::error_frame(client, status, message).into_bytes()
}

impl Surface for ChatCompletionSurface {
Expand Down
26 changes: 19 additions & 7 deletions crates/gateway/src/proxy/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,6 @@ const RESPONSES: ClientSurface = ClientSurface {
caches: false,
};

/// Output length when the caller set none and the upstream insists on
/// one (Anthropic). The value the previous handlers used.
const DEFAULT_MAX_TOKENS: u64 = 4096;

/// POST /v1/chat/completions
pub async fn proxy_chat_completion(
State(state): State<GatewayState>,
Expand Down Expand Up @@ -179,10 +175,14 @@ impl Outbound {
official: bool,
) -> Result<Wire, GatewayError> {
let client = self.surface.dialect;
// Output length when the caller set none and the upstream insists
// on one (Anthropic). There is no per-model output limit on file
// here, so it goes by the upstream model's name.
let default_max_tokens = tw_dialect::official::fallback_max_output_tokens(model);
let target = |dialect| Target {
dialect,
official,
default_max_tokens: DEFAULT_MAX_TOKENS,
default_max_tokens,
};
let decode = |v: &Value| {
tw_dialect::convert::decode(client, v, self.surface.path, None)
Expand Down Expand Up @@ -358,12 +358,25 @@ pub(crate) async fn read_whole(

// ───────────────────────────────────────────── the pipeline

/// Every error on the way out is in the caller's own format.
async fn generate(
state: GatewayState,
headers: HeaderMap,
identity: GatewayRequestIdentity,
body: Bytes,
surface: ClientSurface,
) -> Result<axum::response::Response, GatewayErrorResponse> {
run(state, headers, identity, body, surface)
.await
.map_err(|e| e.in_dialect(surface.dialect))
}

async fn run(
state: GatewayState,
headers: HeaderMap,
identity: GatewayRequestIdentity,
body: Bytes,
surface: ClientSurface,
) -> Result<axum::response::Response, GatewayErrorResponse> {
let trace_id = resolve_trace_id(&headers);
let session_id = resolve_session_id(&headers);
Expand Down Expand Up @@ -778,9 +791,8 @@ async fn generate(
/// part; counting it the same way everywhere keeps one route from
/// looking cheaper than another for the same work.
pub(crate) fn tokens(u: &tw_dialect::usage::Usage) -> (u32, u32) {
let prompt = u.input + u.cache_read + u.cache_write;
(
u32::try_from(prompt).unwrap_or(u32::MAX),
u32::try_from(u.prompt_total()).unwrap_or(u32::MAX),
u32::try_from(u.output).unwrap_or(u32::MAX),
)
}
Expand Down
97 changes: 66 additions & 31 deletions crates/gateway/src/proxy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//! see the leaf modules' docs for what lives where.

use arc_swap::ArcSwap;
use axum::Json;
use axum::response::IntoResponse;
use sqlx::PgPool;
use std::sync::Arc;
Expand Down Expand Up @@ -136,49 +135,60 @@ pub(super) fn gateway_error_status(err: &GatewayError) -> i64 {

// ---------- Error adapter ----------

/// Newtype wrapper so we can implement `IntoResponse` for `GatewayError`.
pub struct GatewayErrorResponse(GatewayError);
/// A `GatewayError` on its way to the caller, in the caller's format.
///
/// The body is the one the caller's own SDK knows how to read: an
/// Anthropic client gets `{"type":"error","error":{…}}`, a Gemini client
/// `{"error":{"code","status",…}}`, Chat and Responses clients OpenAI's
/// `{"error":{"message","type",…}}`. Before, every surface got the Chat
/// shape, and an Anthropic SDK reported a gateway refusal as an
/// unparseable response.
pub struct GatewayErrorResponse {
error: GatewayError,
client: tw_dialect::ir::Dialect,
}

impl From<GatewayError> for GatewayErrorResponse {
fn from(err: GatewayError) -> Self {
Self(err)
/// In Chat's format until the surface says otherwise
/// ([`GatewayErrorResponse::in_dialect`]).
fn from(error: GatewayError) -> Self {
Self {
error,
client: tw_dialect::ir::Dialect::Chat,
}
}
}

impl GatewayErrorResponse {
/// Answer in `client`'s format.
pub(crate) fn in_dialect(mut self, client: tw_dialect::ir::Dialect) -> Self {
self.client = client;
self
}
}

impl IntoResponse for GatewayErrorResponse {
fn into_response(self) -> axum::response::Response {
use axum::http::{HeaderValue, StatusCode, header};

let status =
StatusCode::from_u16(self.0.status_code() as u16).unwrap_or(StatusCode::BAD_GATEWAY);
let error_type = match &self.0 {
GatewayError::ProviderError(_) => "provider_error",
GatewayError::ProviderHttpError { .. } => "provider_http_error",
GatewayError::ProviderTimeout(_) => "provider_timeout",
GatewayError::ProviderInvalidResponse(_) => "provider_invalid_response",
GatewayError::TransformError(_) => "transform_error",
GatewayError::NetworkError(_) => "network_error",
GatewayError::UpstreamRateLimited { .. } | GatewayError::LocalRateLimited(_) => {
"rate_limited"
}
GatewayError::UpstreamAuthError => "auth_error",
GatewayError::PolicyBlocked(_) => "policy_blocked",
};

let retry_after = self.0.retry_after_secs();
let body = serde_json::json!({
"error": {
"message": self.0.to_string(),
"type": error_type,
}
});

let mut response = (status, Json(body)).into_response();
let status = StatusCode::from_u16(self.error.status_code() as u16)
.unwrap_or(StatusCode::BAD_GATEWAY);
let body =
tw_dialect::convert::error_body(self.client, status.as_u16(), &self.error.to_string());
let mut response = (
status,
[(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
)],
body,
)
.into_response();
// Echo the upstream's Retry-After (or our local default) so
// well-behaved clients back off the right amount instead of
// burning quota with tight 3× retries that all hit the same
// open window.
if let Some(secs) = retry_after
if let Some(secs) = self.error.retry_after_secs()
&& let Ok(v) = HeaderValue::from_str(&secs.to_string())
{
response.headers_mut().insert(header::RETRY_AFTER, v);
Expand Down Expand Up @@ -354,6 +364,31 @@ mod helper_tests {
);
}

/// Each client gets the error in the shape its SDK reads.
#[tokio::test]
async fn the_error_body_is_in_the_callers_format() {
use tw_dialect::ir::Dialect;
async fn body(d: Dialect) -> serde_json::Value {
let resp = GatewayErrorResponse::from(GatewayError::LocalRateLimited("rule".into()))
.in_dialect(d)
.into_response();
assert_eq!(resp.status().as_u16(), 429);
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
serde_json::from_slice(&bytes).unwrap()
}
let chat = body(Dialect::Chat).await;
assert_eq!(chat["error"]["type"], "rate_limit_error");
assert_eq!(chat["error"]["message"], "Rate limited: rule");
let anthropic = body(Dialect::Anthropic).await;
assert_eq!(anthropic["type"], "error");
assert_eq!(anthropic["error"]["type"], "rate_limit_error");
let gemini = body(Dialect::Gemini).await;
assert_eq!(gemini["error"]["code"], 429);
assert_eq!(gemini["error"]["status"], "RESOURCE_EXHAUSTED");
}

#[test]
fn retry_after_parser_handles_delta_seconds_and_garbage() {
use crate::error::parse_retry_after_seconds;
Expand Down
37 changes: 17 additions & 20 deletions crates/gateway/src/proxy/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ pub use crate::bedrock::sigv4::Signer;
use crate::call_ctx::CallCtx;
use crate::error::GatewayError;

/// Sent to an Anthropic upstream when neither the caller nor the provider
/// row names a version. Without one the API refuses the request.
const ANTHROPIC_VERSION: &str = "2023-06-01";

/// The HTTP client every upstream call goes through.
///
/// **Different from the desktop gateway on purpose.** Desktop sets no
Expand Down Expand Up @@ -90,20 +86,7 @@ impl Upstream {
pub fn is_official(&self) -> bool {
match &self.shape {
Shape::Bedrock { .. } | Shape::Azure { .. } => true,
Shape::Standard => {
let host = self
.base_url
.split("://")
.nth(1)
.unwrap_or(&self.base_url)
.split(['/', ':'])
.next()
.unwrap_or_default();
matches!(
host,
"api.openai.com" | "api.anthropic.com" | "generativelanguage.googleapis.com"
)
}
Shape::Standard => tw_dialect::official::is_official_host(&self.base_url),
}
}

Expand Down Expand Up @@ -131,15 +114,16 @@ impl Upstream {
for (k, v) in extra {
req = req.header(k, v);
}
// Anthropic refuses a request without a version header.
// Anthropic refuses a request without a version header. One the
// provider row or the caller set wins.
if dialect == tw_dialect::ir::Dialect::Anthropic
&& !self
.headers
.iter()
.chain(extra)
.any(|(k, _)| k.eq_ignore_ascii_case("anthropic-version"))
{
req = req.header("anthropic-version", ANTHROPIC_VERSION);
req = req.header("anthropic-version", tw_dialect::official::ANTHROPIC_VERSION);
}
if let Some(trace) = &ctx.trace_id {
req = req.header("x-trace-id", trace.as_str());
Expand Down Expand Up @@ -282,6 +266,19 @@ mod tests {
);
}

#[test]
fn only_the_vendors_own_host_counts_as_official() {
assert!(up("https://api.anthropic.com/", Shape::Standard).is_official());
assert!(up("https://api.deepseek.com/anthropic", Shape::Standard).is_official());
// A relay cannot dress up as the vendor through its path or user info.
assert!(!up("https://relay.example/api.openai.com", Shape::Standard).is_official());
assert!(!up("https://api.openai.com@relay.example", Shape::Standard).is_official());
let azure = Shape::Azure {
api_version: "2024-02-01".into(),
};
assert!(up("https://x.openai.azure.com", azure).is_official());
}

#[test]
fn azure_addresses_the_model_by_deployment_in_the_url() {
let u = up(
Expand Down
10 changes: 5 additions & 5 deletions crates/server/src/handlers/providers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,12 +609,12 @@ pub(crate) async fn run_provider_test(

// Provider-specific probe URL. We always hit a cheap, read-only
// endpoint that requires auth so a wrong key is detected too.
let url = match req.provider_type.as_str() {
"anthropic" => format!("{}/v1/models", req.base_url.trim_end_matches('/')),
"google" => format!("{}/v1beta/models", req.base_url.trim_end_matches('/')),
// openai / azure / custom — all OpenAI-compatible /v1/models
_ => format!("{}/v1/models", req.base_url.trim_end_matches('/')),
let path = match req.provider_type.as_str() {
"google" => "/v1beta/models",
// anthropic / openai / azure / custom — all answer /v1/models
_ => "/v1/models",
};
let url = tw_dialect::url::upstream_url(&req.base_url, path, None);

// `client` is now passed in from `test_provider` — uses the
// shared http_client so this endpoint inherits the central
Expand Down
Loading
Loading