Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(ai-gateway): relay Anthropic Messages with usage telemetry (#17781)

Hassieb Pakzad7ad9dfed4441
diff --git a/ai-gateway/README.md b/ai-gateway/README.md
index 9f0c340731..97fcff2102 100644
--- a/ai-gateway/README.md
+++ b/ai-gateway/README.md
@@ -1,13 +1,19 @@
# AI Gateway service
-A standalone Rust gateway for `POST /openai/v1/responses`, `POST /openai/v1/responses/compact`,
-and `GET /openai/v1/models`. Web resolves the gateway key to a trusted provider connection;
-Rust relays native JSON or SSE without rewriting provider bytes. Compact uses the same
-Responses capture path. Models listing is a GET proxy of OpenAI's catalog and is not ingested
-as a generation. A bounded capture layer captures request/response facts and
-logs capture completeness at debug level. Each finalized generation is immediately
-uploaded as a Langfuse generation through OTLP. Building and testing need no real
-Web, database or provider credentials.
+A standalone Rust gateway for native provider APIs under two namespaces:
+
+| Namespace | Endpoints | Generation ingested |
+| --- | --- | --- |
+| `/openai/v1` | `POST /responses`, `POST /responses/compact`, `GET /models` | Responses and compact |
+| `/anthropic/v1` | `POST /messages`, `POST /messages/count_tokens`, `GET /models` | Messages |
+
+Web resolves the gateway key to a trusted provider connection for the namespace's API
+format; Rust relays native JSON or SSE without rewriting provider bytes. Models listings
+are GET proxies of the provider catalog and token counting returns the native count;
+neither is ingested as a generation. A bounded capture layer captures request/response
+facts and logs capture completeness at debug level. Each finalized generation is
+immediately uploaded as a Langfuse generation through OTLP. Building and testing need
+no real Web, database or provider credentials.
## Run locally
@@ -205,13 +211,69 @@ response = client.responses.create(model="gpt-4.1-mini", input="Say hello")
print(response.output_text)
```
-The gateway forwards inference to official OpenAI v1 paths only: Responses, Responses compact,
-and GET `/models`. It does not retry, follow redirects, or accept client routing overrides.
-Request parsing is best-effort capture only; Web still selects the provider connection.
-Compact `encrypted_content` is relayed unchanged. GET `/models` returns OpenAI's list
-payload as-is, drops request query strings, and does not upload a generation.
-Provider errors retain their status and body. Gateway errors use an OpenAI-style
-`{"error":{"message":"...","type":"...","param":null,"code":"..."}}` envelope.
+### Anthropic Messages and Claude Code
+
+The `/anthropic/v1` namespace serves the Anthropic Messages API. Claude Code treats the
+gateway as the Claude API once `ANTHROPIC_BASE_URL` points at the namespace root; the
+SDK appends `/v1/messages` itself, so the URL has no `/v1` suffix:
+
+```sh
+export ANTHROPIC_BASE_URL=http://localhost:8080/anthropic
+export ANTHROPIC_AUTH_TOKEN=$LANGFUSE_GATEWAY_KEY
+export ANTHROPIC_API_KEY= # a leftover Anthropic key here conflicts with the token
+claude
+```
+
+`ANTHROPIC_AUTH_TOKEN` arrives as `Authorization: Bearer`, `ANTHROPIC_API_KEY` as
+`x-api-key`; the gateway accepts its key in either position. When both headers are
+present they must carry the same value, otherwise the request is rejected with 401
+rather than guessing which credential the developer meant. Claude Code's
+`x-claude-code-session-id` header groups a session's generations; see the caller
+tracing context below.
+
+```sh
+curl http://localhost:8080/anthropic/v1/messages \
+ -H "x-api-key: $LANGFUSE_GATEWAY_KEY" \
+ -H 'anthropic-version: 2023-06-01' \
+ -H 'Content-Type: application/json' \
+ -d '{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"Say hello"}]}'
+# Add "stream":true and use curl -N for SSE.
+
+curl http://localhost:8080/anthropic/v1/messages/count_tokens \
+ -H "x-api-key: $LANGFUSE_GATEWAY_KEY" \
+ -H 'anthropic-version: 2023-06-01' \
+ -H 'Content-Type: application/json' \
+ -d '{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"Say hello"}]}'
+
+curl "http://localhost:8080/anthropic/v1/models?limit=1000" \
+ -H "x-api-key: $LANGFUSE_GATEWAY_KEY" -H 'anthropic-version: 2023-06-01'
+```
+
+Every `anthropic-*` request header is forwarded verbatim, including `anthropic-version`
+and `anthropic-beta`: Claude Code pairs beta body fields with beta header values and
+adds new headers between releases, so the gateway does not allowlist individual
+values. Request bodies, including the `system` array order and `cache_control`
+markers, are relayed byte for byte. On responses `request-id`, `x-should-retry`,
+`anthropic-organization-id` and every `anthropic-ratelimit-*` header are retained
+because the client uses them to decide whether and when to retry and to show usage
+limits. Provider error bodies are relayed unmodified; Claude Code matches on their
+wording to disable rejected capabilities. Model discovery
+(`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`) proxies Anthropic's catalog and
+forwards only the `limit`, `after_id` and `before_id` query parameters.
+
+### Relay rules
+
+The gateway forwards inference to official provider paths only. It does not retry, follow
+redirects, or accept client routing overrides. Request parsing is best-effort capture
+only; Web still selects the provider connection. Compact `encrypted_content` is relayed
+unchanged. Inference routes drop request query strings: the Anthropic SDK's
+`?beta=true` carries nothing beyond the `anthropic-beta` header. Provider errors retain
+their status and body. Gateway errors use the namespace's native envelope:
+`{"error":{"message":"...","type":"...","param":null,"code":"..."}}` for OpenAI and
+`{"type":"error","error":{"type":"...","message":"..."}}` for Anthropic, where the
+error type follows the status (`authentication_error`, `permission_error`,
+`not_found_error`, `request_too_large`, `invalid_request_error`, `overloaded_error`,
+`api_error`).
The gateway authenticates through Web before reserving execution capacity or
reading the request body. Web resolution uses a separate concurrency budget,
@@ -222,9 +284,9 @@ guardrails, not measured capacity: tune them independently using load tests for
instance resources, request sizes and stream durations. These limits bound work;
they do not guarantee fairness between clients or tenants.
-Other limits are 4 MiB request bodies, 10 seconds to read a request, 5 seconds to
+Other limits are 10 MiB request bodies in both namespaces, 10 seconds to read a request, 5 seconds to
connect, 120 seconds for provider response headers or an individual upstream read,
-and 600 seconds overall from execution admission. Response size is not capped: a single task pumps chunks
+and 600 seconds overall from execution admission in both namespaces. Response size is not capped: a single task pumps chunks
through a one-slot channel, with chunks at most 64 KiB. It stops reading when that
channel fills. Completion, disconnect and deadline release admission and context;
the deadline runs even when the downstream stops polling. A failure after headers
@@ -233,13 +295,16 @@ There is no separate downstream stall timeout; a client that stops reading can
retain execution capacity until the overall deadline. A progress-based downstream
stall policy is deferred to a separate change.
-Only request content type/encoding and accept cross the provider boundary, plus
-the resolved Bearer token. The gateway sets `Accept-Encoding: identity` upstream
-so client compression preferences cannot disable JSON/SSE capture. Response
-content type/encoding, cache control, retry-after, request ID and selected OpenAI
-timing/version/rate-limit
-headers are retained. Cookies, routing overrides, gateway/ingestion credentials,
-hop-by-hop headers and upstream framing are excluded.
+Only request content type/encoding and accept cross the provider boundary, plus the
+resolved credential in its provider's header (`Authorization: Bearer` for OpenAI,
+`x-api-key` for Anthropic) and, for Anthropic, the `anthropic-*` header family. The
+gateway sets `Accept-Encoding: identity` upstream so client compression preferences
+cannot disable JSON/SSE capture. Response content type/encoding, cache control and
+retry-after are retained in both namespaces, plus the request ID and selected OpenAI
+timing/version/rate-limit headers, or Anthropic's `request-id`, `x-should-retry`,
+`anthropic-organization-id` and `anthropic-ratelimit-*` headers. Cookies, routing
+overrides, gateway/ingestion credentials, client `x-claude-code-*` correlation
+headers, hop-by-hop headers and upstream framing are excluded.
## Langfuse uploads
@@ -263,8 +328,10 @@ attribution. Full mode includes the captured input/output; usage mode omits cont
Completion-start time is emitted only for upstream `text/event-stream` responses,
on the first nonempty text, reasoning, refusal, tool-input, audio, or partial-image content. JSON responses
and streams without a captured content delta have no completion-start time or TTFT.
-The exporter projects native OpenAI usage into the receiver's supported shape for
-pricing without duplicating it in metadata. Missing usage is not reported as zero.
+OpenAI Responses usage is projected into the receiver's strict native schema, keeping
+its nested detail counters. Anthropic usage is uploaded exactly as the provider reported
+it; ingestion decides what to price. Usage is not duplicated in metadata. Missing usage
+is not reported as zero.
Gateway metadata uses `langfuse.gateway.*`, grouped by the resource or exchange
each field describes:
@@ -274,11 +341,11 @@ each field describes:
| `organization.id`, `project.id` | Resolved Langfuse organization and ingestion project |
| `api_key.id`, `connection.id` | Authenticated gateway key and selected Langfuse connection |
| `ingestion.mode` | Effective capture mode |
-| `request.api_format` | Native API contract, such as `openai.responses` |
+| `request.api_format` | Native API contract: `openai.responses` or `anthropic.messages` |
| `request.metadata`, `request.prompt_cache_key`, `request.safety_identifier`, `request.user` | Native caller-supplied fields, captured only in full mode |
| `response.id` | Native response object's ID |
| `response.status_code` | HTTP status returned to the caller |
-| `upstream.request.id` | Provider request ID received in the upstream `x-request-id` response header |
+| `upstream.request.id` | Provider request ID from the upstream `x-request-id` (OpenAI) or `request-id` (Anthropic) header |
`request.id` is reserved for a future gateway-generated request ID and is not
emitted. The upstream request ID is separate and is omitted when unavailable.
@@ -457,9 +524,22 @@ stored under `langfuse.gateway.request.*` only in full mode.
In both modes, `usage_details` preserves the provider's entire usage object,
including nested and unknown fields. The gateway does not rename counters,
subtract cached tokens, or synthesize totals. Missing usage stays null.
-`api_format` identifies the payload format (`openai.responses` today).
-
-For SSE, only `response.output_item.done` adds output. Terminal Responses events
+`api_format` identifies the payload format (`openai.responses` or `anthropic.messages`).
+
+For Anthropic Messages, `message_start` supplies the response ID, actual model and the
+usage baseline; `message_delta` supplies `stop_reason` and cumulative usage counters that
+replace the baseline values (nothing is summed across snapshots); `message_stop` is the
+terminal event. `completion_start_ms` is set by the first `content_block_delta` carrying
+non-empty `text`, `thinking` or `partial_json`; signatures, citations and pings do not
+count. A mid-stream `error` event, or an HTTP error body, marks the generation failed;
+its `type` and `message` are retained only in full mode. Unknown event types are ignored.
+A `stop_reason` of `max_tokens` or `model_context_window_exceeded` sets a `WARNING`
+level. Only scalar model parameters (`max_tokens`, `temperature`, `top_p`, `top_k`,
+`stream`, `service_tier`, `speed`) are recorded; `speed` selects the fast-mode pricing
+tier. Request and response content are not captured
+in either mode yet, so full-mode output completeness is false and `input`/`output` are null.
+
+For OpenAI Responses SSE, only `response.output_item.done` adds output. Terminal Responses events
provide model, service tier, status and usage; their repeated output is not copied.
Deltas are never stitched or retained. A disconnect midway through an item loses
that unfinished item; already completed items remain in the partial record. Item
@@ -483,12 +563,12 @@ content does not make it false. Request inspection failure does not invalidate a
fully captured response, and downstream cancellation does not erase completed capture.
The implementation separates shared `ExecutionCapture` lifecycle/timing, the
-`OpenAiResponsesCapture` adapter and bounded `SseDecoder`. A private `ProtocolCapture`
-enum dispatches to the adapter. Finalization hands an owned `InferenceFacts` record
-to telemetry for a safe debug summary and immediate upload. Another provider can supply
-native facts through the same interface without changing the relay. The current
-usage mapping targets OpenAI Responses; no Anthropic adapter is implemented yet.
-Capture and upload run independently of log level; debug emission alone is gated.
+`OpenAiResponsesCapture` and `AnthropicMessagesCapture` adapters, the shared
+`ResponseBody` content-type sniffing and bounded `SseDecoder`. A private
+`ProtocolCapture` enum dispatches to the adapter selected by API format. Finalization
+hands an owned `InferenceFacts` record to telemetry for a safe debug summary and
+immediate upload. Capture and upload run independently of log level; debug emission
+alone is gated.
Capture is limited to 1 MiB request inspection, 1 MiB JSON/SSE event inspection,
1 MiB retained output and 256 output items per execution. The active-request limit
@@ -590,10 +670,7 @@ invalid response, even if Web selected it.
`ProviderConnection::credential()` exposes the secret in its header position
(`ProviderCredential::Bearer` or `ProviderCredential::XApiKey`) and has no `Debug`
-output. The Anthropic pairing is accepted by the contract ahead of its routes: no
-`/anthropic/v1` endpoint, transport or capture exists yet, so a resolver caller
-requesting `anthropic.messages` today is only the test suite. Ingestion tokens remain
-opaque. Resolution caching, provider execution and telemetry are separate slices.
+output. Ingestion tokens remain opaque. Resolution caching is a separate slice.
### Verification
@@ -632,8 +709,10 @@ cargo test --locked
- `main.rs`: configuration, logging, signal registration and process exit.
- `http.rs`: credential extraction, bounded body reads and gateway error envelopes.
- `inference.rs`: `InferenceService` coordinates resolution, admission and forwarding.
-- `providers/openai.rs`: fixed OpenAI v1 origin, route, provider credentials and admission.
-- `transport/mod.rs`: header allowlists, bounded byte relay and response lifetime.
+- `providers/mod.rs`: `ProviderTransport` with shared admission, the `Route` enum of
+ official operations (method, upstream path, capture, forwarded query) and credential
+ placement.
+- `transport/mod.rs`: per-format header policies, bounded byte relay and response lifetime.
- `resolution/mod.rs`: trusted base URL configuration and bounded Web HTTP client.
- `resolution/contracts.rs`: strict Web response validation and immutable execution context.
- `resolution/signing.rs`: Web v1 HMAC; a literal shared fixture pins byte compatibility.
diff --git a/ai-gateway/src/capture/anthropic_messages.rs b/ai-gateway/src/capture/anthropic_messages.rs
new file mode 100644
index 0000000000..e55cf698b3
--- /dev/null
+++ b/ai-gateway/src/capture/anthropic_messages.rs
@@ -0,0 +1,226 @@
+use super::{
+ MAX_CAPTURE_BYTES, MAX_FACT_STRING, bounded_string, facts::ProviderFacts, identity_encoding,
+ response::ResponseBody,
+};
+use crate::resolution::IngestionMode;
+use axum::http::HeaderMap;
+use serde_json::{Map, Value};
+
+pub(super) struct AnthropicMessagesCapture {
+ facts: ProviderFacts,
+ mode: IngestionMode,
+ body: ResponseBody,
+ usage: Option<Map<String, Value>>,
+ terminal: bool,
+ request_complete: bool,
+ response_valid: bool,
+}
+
+impl AnthropicMessagesCapture {
+ pub fn new(headers: &HeaderMap, body: &[u8], mode: IngestionMode) -> Self {
+ let mut capture = Self {
+ facts: ProviderFacts::default(),
+ mode,
+ body: ResponseBody::Unknown,
+ usage: None,
+ terminal: false,
+ request_complete: false,
+ response_valid: true,
+ };
+ if identity_encoding(headers)
+ && body.len() <= MAX_CAPTURE_BYTES
+ && let Ok(Value::Object(request)) = serde_json::from_slice(body)
+ {
+ capture.capture_request(&request);
+ capture.request_complete = true;
+ }
+ capture
+ }
+
+ pub fn record_response(&mut self, headers: &HeaderMap) {
+ self.facts.provider_request_id = headers
+ .get("request-id")
+ .and_then(|v| v.to_str().ok())
+ .and_then(bounded_string);
+ self.body = ResponseBody::from_headers(headers);
+ if matches!(self.body, ResponseBody::Unavailable) {
+ self.response_valid = false;
+ }
+ }
+
+ pub fn push_bytes(&mut self, bytes: &[u8]) -> bool {
+ let mut body = std::mem::replace(&mut self.body, ResponseBody::Unavailable);
+ let mut completion_started = false;
+ if !body.push(bytes, |event| {
+ completion_started |= self.handle_event(event);
+ }) {
+ self.response_valid = false;
+ }
+ self.body = body;
+ completion_started
+ }
+
+ pub fn end_body(&mut self) {
+ match std::mem::replace(&mut self.body, ResponseBody::Unavailable) {
+ ResponseBody::Json(bytes) => match serde_json::from_slice::<Value>(&bytes) {
+ Ok(Value::Object(response)) => {
+ if response.get("type").and_then(Value::as_str) == Some("error") {
+ self.record_failure(&response);
+ } else {
+ self.capture_message(&response);
+ self.terminal = true;
+ }
+ }
+ _ => self.response_valid = false,
+ },
+ ResponseBody::Sse(sse) => {
+ self.response_valid &= sse.finish();
+ }
+ ResponseBody::Unknown | ResponseBody::Unavailable => {}
+ }
+ self.facts.output_complete =
+ self.terminal && self.response_valid && self.mode != IngestionMode::Full;
+ self.facts.capture_complete = self.request_complete && self.facts.output_complete;
+ }
+
+ pub fn into_facts(mut self) -> ProviderFacts {
+ if matches!(self.body, ResponseBody::Sse(_)) {
+ self.end_body();
+ }
+ self.facts.usage_details = self.usage.take().map(Value::Object);
+ self.facts
+ }
+
+ fn capture_request(&mut self, request: &Map<String, Value>) {
+ self.facts.requested_model = request
+ .get("model")
+ .and_then(Value::as_str)
+ .and_then(bounded_string);
+ self.facts.model.clone_from(&self.facts.requested_model);
+ for key in [
+ "max_tokens",
+ "temperature",
+ "top_p",
+ "top_k",
+ "stream",
+ "service_tier",
+ "speed",
+ ] {
+ if let Some(value) = request.get(key).filter(|v| {
+ v.is_number()
+ || v.is_boolean()
+ || v.as_str().is_some_and(|s| s.len() <= MAX_FACT_STRING)
+ }) {
+ self.facts
+ .model_parameters
+ .insert(key.to_owned(), value.clone());
+ }
+ }
+ }
+
+ fn handle_event(&mut self, bytes: &[u8]) -> bool {
+ let Ok(Value::Object(event)) = serde_json::from_slice(bytes) else {
+ self.response_valid = false;
+ return false;
+ };
+ match event.get("type").and_then(Value::as_str) {
+ Some("message_start") => {
+ if let Some(message) = event.get("message").and_then(Value::as_object) {
+ self.capture_message(message);
+ } else {
+ self.response_valid = false;
+ }
+ }
+ Some("content_block_delta") => {
+ return event
+ .get("delta")
+ .and_then(Value::as_object)
+ .is_some_and(|delta| {
+ ["text", "thinking", "partial_json"].iter().any(|key| {
+ delta
+ .get(*key)
+ .and_then(Value::as_str)
+ .is_some_and(|content| !content.is_empty())
+ })
+ });
+ }
+ Some("message_delta") => {
+ if let Some(delta) = event.get("delta").and_then(Value::as_object) {
+ self.capture_stop(delta);
+ }
+ if let Some(usage) = event.get("usage").and_then(Value::as_object) {
+ self.merge_usage(usage);
+ }
+ }
+ Some("message_stop") => self.terminal = true,
+ Some("error") => self.record_failure(&event),
+ _ => {}
+ }
+ false
+ }
+
+ fn capture_message(&mut self, message: &Map<String, Value>) {
+ for (key, target) in [
+ ("id", &mut self.facts.provider_response_id),
+ ("model", &mut self.facts.model),
+ ] {
+ if let Some(value) = message
+ .get(key)
+ .and_then(Value::as_str)
+ .and_then(bounded_string)
+ {
+ *target = Some(value);
+ }
+ }
+ self.capture_stop(message);
+ if let Some(usage) = message.get("usage").and_then(Value::as_object) {
+ self.merge_usage(usage);
+ }
+ }
+
+ fn capture_stop(&mut self, source: &Map<String, Value>) {
+ let Some(stop_reason) = source.get("stop_reason").and_then(Value::as_str) else {
+ return;
+ };
+ self.facts.provider_status = Some(
+ match stop_reason {
+ "max_tokens" | "model_context_window_exceeded" => "incomplete",
+ _ => "completed",
+ }
+ .to_owned(),
+ );
+ }
+
+ fn merge_usage(&mut self, usage: &Map<String, Value>) {
+ let merged = self.usage.get_or_insert_with(Map::new);
+ for (key, value) in usage {
+ if !value.is_null() {
+ merged.insert(key.clone(), value.clone());
+ }
+ }
+ }
+
+ fn record_failure(&mut self, envelope: &Map<String, Value>) {
+ self.facts.provider_status = Some("failed".to_owned());
+ if self.mode != IngestionMode::Full {
+ return;
+ }
+ let Some(error) = envelope.get("error").and_then(Value::as_object) else {
+ return;
+ };
+ let detail = ["type", "message"]
+ .into_iter()
+ .filter_map(|key| error.get(key).and_then(Value::as_str))
+ .filter(|value| !value.is_empty())
+ .map(|value| &value[..value.floor_char_boundary(MAX_FACT_STRING)])
+ .collect::<Vec<_>>()
+ .join(": ");
+ if !detail.is_empty() {
+ self.facts.error_message =
+ Some(detail[..detail.floor_char_boundary(MAX_FACT_STRING)].to_owned());
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/ai-gateway/src/capture/anthropic_messages/tests.rs b/ai-gateway/src/capture/anthropic_messages/tests.rs
new file mode 100644
index 0000000000..a1c174487f
--- /dev/null
+++ b/ai-gateway/src/capture/anthropic_messages/tests.rs
@@ -0,0 +1,381 @@
+use super::*;
+use crate::{
+ capture::{ExecutionCapture, ProtocolCapture},
+ providers::{ProviderLimits, ProviderTransport, Route},
+ resolution::ApiFormat,
+ test_support::{FakeServer, resolved_request_context_for},
+};
+use axum::{
+ body::{Body, Bytes, to_bytes},
+ http::{HeaderValue, Response, header},
+};
+use serde_json::json;
+use std::{
+ sync::{Arc, Mutex},
+ time::Duration,
+};
+
+const REQUEST: &[u8] = br#"{"model":"claude-sonnet-4-5","max_tokens":32000,"temperature":1,"stream":true,"speed":"fast","system":[{"type":"text","text":"system-canary","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"prompt-canary"}],"tools":[{"name":"Bash","input_schema":{"type":"object"}}],"thinking":{"type":"adaptive"},"tool_choice":{"type":"auto"},"metadata":{"user_id":"{\"session_id\":\"session-canary\"}"},"future_field":{"kept":true}}"#;
+
+fn captured(execution: &ExecutionCapture) -> &AnthropicMessagesCapture {
+ let ProtocolCapture::AnthropicMessages(capture) = execution.protocol.as_ref().unwrap() else {
+ panic!("expected the Anthropic Messages adapter");
+ };
+ capture
+}
+
+async fn new_observer(mode: &'static str) -> ExecutionCapture {
+ let context =
+ resolved_request_context_for(ApiFormat::AnthropicMessages, "provider-secret", mode).await;
+ ExecutionCapture::for_request(
+ ApiFormat::AnthropicMessages,
+ &context,
+ &HeaderMap::new(),
+ REQUEST,
+ )
+}
+
+fn record_response(observer: &mut ExecutionCapture, status: u16, content_type: &'static str) {
+ let mut headers = HeaderMap::new();
+ headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
+ headers.insert("request-id", HeaderValue::from_static("req_provider_1"));
+ observer.record_response(status, &headers);
+}
+
+fn event(kind: &str, fields: Value) -> String {
+ let mut value = fields;
+ value["type"] = kind.into();
+ format!("event: {kind}\ndata: {value}\n\n")
+}
+
+fn message_start() -> String {
+ event(
+ "message_start",
+ json!({"message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-5-20250929","content":[],"stop_reason":null,"usage":{"input_tokens":7,"output_tokens":1,"cache_creation_input_tokens":2089,"cache_read_input_tokens":16399,"cache_creation":{"ephemeral_5m_input_tokens":2089,"ephemeral_1h_input_tokens":0},"service_tier":"standard"}}}),
+ )
+}
+
+fn text_stream() -> String {
+ [
+ message_start(),
+ event("ping", json!({})),
+ event(
+ "content_block_start",
+ json!({"index":0,"content_block":{"type":"text","text":""}}),
+ ),
+ event(
+ "content_block_delta",
+ json!({"index":0,"delta":{"type":"text_delta","text":"Hel"}}), // codespell:ignore
+ ),
+ event(
+ "content_block_delta",
+ json!({"index":0,"delta":{"type":"text_delta","text":"lo"}}),
+ ),
+ event("content_block_stop", json!({"index":0})),
+ event(
+ "message_delta",
+ json!({"delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":7,"output_tokens":445,"cache_creation_input_tokens":2089,"cache_read_input_tokens":16399,"cache_creation":{"ephemeral_5m_input_tokens":2089,"ephemeral_1h_input_tokens":0}}}),
+ ),
+ event("message_stop", json!({})),
+ ]
+ .concat()
+}
+
+#[tokio::test]
+async fn streaming_usage_is_replaced_by_cumulative_deltas_not_summed() {
+ let mut observer = new_observer("usage").await;
+ record_response(&mut observer, 200, "text/event-stream");
+ observer.push_bytes(text_stream().as_bytes());
+ observer.end_body();
+ let facts = captured(&observer);
+ assert_eq!(
+ facts
+ .usage
+ .as_ref()
+ .map(|usage| Value::Object(usage.clone())),
+ Some(json!({
+ "input_tokens":7,"output_tokens":445,"cache_creation_input_tokens":2089,
+ "cache_read_input_tokens":16399,
+ "cache_creation":{"ephemeral_5m_input_tokens":2089,"ephemeral_1h_input_tokens":0},
+ "service_tier":"standard"
+ }))
+ );
+ assert_eq!(facts.facts.provider_response_id.as_deref(), Some("msg_1"));
+ assert_eq!(
+ facts.facts.model.as_deref(),
+ Some("claude-sonnet-4-5-20250929")
+ );
+ assert_eq!(
+ facts.facts.requested_model.as_deref(),
+ Some("claude-sonnet-4-5")
+ );
+ assert_eq!(facts.facts.provider_status.as_deref(), Some("completed"));
+ assert_eq!(
+ facts.facts.provider_request_id.as_deref(),
+ Some("req_provider_1")
+ );
+ assert!(facts.facts.output_complete);
+ assert!(facts.facts.capture_complete);
+ assert!(facts.facts.input.is_none());
+}
+
+#[tokio::test]
+async fn completion_starts_on_the_first_text_thinking_or_tool_input_delta_only() {
+ for (delta, expected) in [
+ (json!({"type":"text_delta","text":"x"}), true),
+ (json!({"type":"thinking_delta","thinking":"x"}), true),
+ (json!({"type":"input_json_delta","partial_json":"{"}), true),
+ (json!({"type":"text_delta","text":""}), false),
+ (json!({"type":"signature_delta","signature":"abc"}), false),
+ (
+ json!({"type":"citations_delta","citation":{"type":"char_location"}}),
+ false,
+ ),
+ ] {
+ let mut observer = new_observer("usage").await;
+ record_response(&mut observer, 200, "text/event-stream");
+ observer.push_bytes(message_start().as_bytes());
+ observer.push_bytes(event("ping", json!({})).as_bytes());
+ observer.push_bytes(
+ event(
+ "content_block_start",
+ json!({"index":0,"content_block":{"type":"text","text":""}}),
+ )
+ .as_bytes(),
+ );
+ assert!(observer.completion_start_ms.is_none());
+ observer
+ .push_bytes(event("content_block_delta", json!({"index":0,"delta":delta})).as_bytes());
+ assert_eq!(observer.completion_start_ms.is_some(), expected, "{delta}");
+ }
+}
+
+#[tokio::test]
+async fn json_responses_capture_the_same_facts_and_error_bodies_mark_failure() {
+ let mut observer = new_observer("full").await;
+ record_response(&mut observer, 200, "application/json");
+ observer.push_bytes(br#"{"id":"msg_2","type":"message","role":"assistant","model":"claude-sonnet-4-5-20250929","content":[{"type":"text","text":"Hello"}],"stop_reason":"max_tokens","usage":{"input_tokens":10,"output_tokens":32000}}"#);
+ observer.end_body();
+ let facts = captured(&observer);
+ assert_eq!(facts.facts.provider_response_id.as_deref(), Some("msg_2"));
+ assert_eq!(facts.facts.provider_status.as_deref(), Some("incomplete"));
+ assert_eq!(
+ facts
+ .usage
+ .as_ref()
+ .map(|usage| Value::Object(usage.clone())),
+ Some(json!({"input_tokens":10,"output_tokens":32000}))
+ );
+ // Response content is not captured yet, so full mode cannot claim completeness.
+ assert!(!facts.facts.output_complete);
+ assert!(facts.facts.output.is_none());
+
+ for (mode, expected_message) in [
+ (
+ "full",
+ Some("invalid_request_error: messages.0.content: prompt-canary echoed"),
+ ),
+ ("usage", None),
+ ] {
+ let mut observer = new_observer(mode).await;
+ record_response(&mut observer, 400, "application/json");
+ observer.push_bytes(br#"{"type":"error","error":{"type":"invalid_request_error","message":"messages.0.content: prompt-canary echoed"},"request_id":"req_x"}"#);
+ observer.end_body();
+ let facts = captured(&observer);
+ assert_eq!(facts.facts.provider_status.as_deref(), Some("failed"));
+ assert_eq!(facts.facts.error_message.as_deref(), expected_message);
+ assert!(facts.usage.is_none());
+ assert!(!facts.facts.output_complete);
+ }
+}
+
+#[tokio::test]
+async fn in_stream_errors_unknown_events_and_truncation_are_tolerated() {
+ let mut observer = new_observer("full").await;
+ record_response(&mut observer, 200, "text/event-stream");
+ observer.push_bytes(message_start().as_bytes());
+ observer.push_bytes(event("future_event", json!({"payload":[1,2,3]})).as_bytes());
+ observer.push_bytes(
+ event(
+ "error",
+ json!({"error":{"type":"overloaded_error","message":"Overloaded"}}),
+ )
+ .as_bytes(),
+ );
+ observer.end_body();
+ let facts = captured(&observer);
+ assert_eq!(facts.facts.provider_status.as_deref(), Some("failed"));
+ assert_eq!(
+ facts.facts.error_message.as_deref(),
+ Some("overloaded_error: Overloaded")
+ );
+ // Usage from message_start survives the failure; nothing is invented.
+ assert_eq!(facts.usage.as_ref().unwrap()["output_tokens"], json!(1));
+ assert!(!facts.facts.output_complete);
+
+ let mut observer = new_observer("usage").await;
+ record_response(&mut observer, 200, "text/event-stream");
+ observer.push_bytes(message_start().as_bytes());
+ observer
+ .push_bytes(b"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"ind");
+ observer.end_body();
+ let facts = captured(&observer);
+ assert_eq!(facts.facts.provider_status, None);
+ assert!(!facts.facts.output_complete);
+ assert_eq!(facts.usage.as_ref().unwrap()["input_tokens"], json!(7));
+
+ let mut observer = new_observer("usage").await;
+ record_response(&mut observer, 200, "text/event-stream");
+ observer.push_bytes(b"event: message_start\ndata: not json\n\n");
+ observer.push_bytes(text_stream().as_bytes());
+ observer.end_body();
+ assert!(!captured(&observer).facts.output_complete);
+ assert_eq!(
+ captured(&observer).facts.provider_status.as_deref(),
+ Some("completed")
+ );
+}
+
+#[tokio::test]
+async fn only_scalar_parameters_are_recorded_and_content_is_never_captured() {
+ for mode in ["usage", "full"] {
+ let observer = new_observer(mode).await;
+ let facts = &captured(&observer).facts;
+ assert_eq!(
+ facts.model_parameters,
+ json!({"max_tokens":32000,"temperature":1,"stream":true,"speed":"fast"})
+ .as_object()
+ .cloned()
+ .unwrap()
+ );
+ assert!(facts.request_metadata.is_empty());
+ assert!(facts.input.is_none());
+ let serialized = serde_json::to_string(facts).unwrap();
+ for canary in ["system-canary", "prompt-canary", "session-canary"] {
+ assert!(
+ !serialized.contains(canary),
+ "{mode} mode captured {canary}"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn finalized_facts_carry_the_anthropic_api_format_and_native_usage() {
+ let mut observer = new_observer("usage").await;
+ record_response(&mut observer, 200, "text/event-stream");
+ observer.push_bytes(text_stream().as_bytes());
+ let (api_format, facts) = observer.protocol.take().unwrap().into_facts();
+ assert_eq!(api_format, "anthropic.messages");
+ assert_eq!(
+ facts.usage_details.unwrap()["cache_read_input_tokens"],
+ json!(16399)
+ );
+ assert!(facts.output_complete);
+}
+
+/// A fake ingestion endpoint that stores the last uploaded OTLP payload.
+async fn collector() -> (FakeServer, Arc<Mutex<Value>>) {
+ let uploaded = Arc::new(Mutex::new(Value::Null));
+ let received = uploaded.clone();
+ let collector = FakeServer::start(move |request| {
+ let received = received.clone();
+ async move {
+ let bytes = to_bytes(request.into_body(), 64 * 1024).await.unwrap();
+ *received.lock().unwrap() = serde_json::from_slice(&bytes).unwrap();
+ Response::new(Body::from("{}"))
+ }
+ })
+ .await;
+ (collector, uploaded)
+}
+
+fn span_attribute(span: &Value, key: &str) -> Value {
+ let attribute = span["attributes"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|attribute| attribute["key"] == key)
+ .unwrap_or_else(|| panic!("missing {key}"));
+ serde_json::from_str(attribute["value"]["stringValue"].as_str().unwrap()).unwrap()
+}
+
+#[tokio::test]
+async fn streamed_messages_upload_one_generation_with_native_usage() {
+ let upstream = FakeServer::start(|_| async {
+ Response::builder()
+ .header("content-type", "text/event-stream")
+ .header("request-id", "req_upstream")
+ .body(Body::from(text_stream()))
+ .unwrap()
+ })
+ .await;
+ let (collector, uploaded) = collector().await;
+ let telemetry = crate::telemetry::Telemetry::new(
+ &crate::resolution::ControlPlaneConfig::new(&collector.url, "test-service-key").unwrap(),
+ )
+ .unwrap();
+ let context =
+ resolved_request_context_for(ApiFormat::AnthropicMessages, "provider-secret", "usage")
+ .await;
+ let provider =
+ ProviderTransport::for_test(format!("{}/v1", upstream.url), ProviderLimits::default())
+ .with_telemetry(telemetry.clone());
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "x-claude-code-session-id",
+ HeaderValue::from_static("session-abc"),
+ );
+ let forwarded = provider
+ .forward_route(
+ provider.try_admit().unwrap(),
+ context,
+ &headers,
+ Bytes::from_static(REQUEST),
+ Route::AnthropicMessages,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ to_bytes(forwarded.into_body(), 8192).await.unwrap(),
+ text_stream()
+ );
+ telemetry
+ .shutdown(tokio::time::Instant::now() + Duration::from_secs(2))
+ .await;
+ assert_eq!(collector.calls(), 1);
+ let upload = uploaded.lock().unwrap();
+ let span = &upload["resourceSpans"][0]["scopeSpans"][0]["spans"][0];
+ assert_eq!(span["name"], "anthropic.messages");
+ assert_eq!(
+ span_attribute(span, "langfuse.observation.usage_details"),
+ json!({
+ "input_tokens": 7, "output_tokens": 445,
+ "cache_creation_input_tokens": 2089, "cache_read_input_tokens": 16399,
+ "cache_creation": {"ephemeral_5m_input_tokens": 2089, "ephemeral_1h_input_tokens": 0},
+ "service_tier": "standard"
+ })
+ );
+ let metadata = span_attribute(span, "langfuse.observation.metadata");
+ assert_eq!(
+ metadata["langfuse.gateway.request.api_format"],
+ "anthropic.messages"
+ );
+ assert_eq!(metadata["langfuse.gateway.response.id"], "msg_1");
+ assert_eq!(
+ metadata["langfuse.gateway.upstream.request.id"],
+ "req_upstream"
+ );
+ assert_eq!(metadata["agent.name"], "claude-code");
+ assert_eq!(metadata["agent.session_id"], "session-abc");
+ let serialized = upload.to_string();
+ for canary in [
+ "system-canary",
+ "prompt-canary",
+ "session-canary",
+ "provider-secret",
+ ] {
+ assert!(!serialized.contains(canary), "usage mode uploaded {canary}");
+ }
+}
diff --git a/ai-gateway/src/capture/mod.rs b/ai-gateway/src/capture/mod.rs
index 1d13b51d56..68c141d5be 100644
--- a/ai-gateway/src/capture/mod.rs
+++ b/ai-gateway/src/capture/mod.rs
@@ -1,6 +1,7 @@
-//! Best-effort capture around the existing relay lifecycle.
+mod anthropic_messages;
mod facts;
mod openai_responses;
+mod response;
mod sse;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -10,9 +11,10 @@ use serde_json::{Map, Value, json};
use tokio::time::Instant;
use crate::{
- resolution::{IngestionMode, MetadataValue, ResolvedRequestContext},
+ resolution::{ApiFormat, IngestionMode, MetadataValue, ResolvedRequestContext},
telemetry,
};
+use anthropic_messages::AnthropicMessagesCapture;
pub(crate) use facts::ProviderFacts;
pub(crate) use facts::{InferenceFacts, RelayOutcome};
use openai_responses::OpenAiResponsesCapture;
@@ -21,39 +23,55 @@ const MAX_CAPTURE_BYTES: usize = 1024 * 1024;
const MAX_ITEMS: usize = 256;
const MAX_FACT_STRING: usize = 512;
-/// Add another adapter here when another API is supported; the relay stays shared.
enum ProtocolCapture {
OpenAiResponses(OpenAiResponsesCapture),
+ AnthropicMessages(AnthropicMessagesCapture),
}
impl ProtocolCapture {
+ fn new(api_format: ApiFormat, headers: &HeaderMap, body: &[u8], mode: IngestionMode) -> Self {
+ match api_format {
+ ApiFormat::OpenAiResponses => {
+ Self::OpenAiResponses(OpenAiResponsesCapture::new(headers, body, mode))
+ }
+ ApiFormat::AnthropicMessages => {
+ Self::AnthropicMessages(AnthropicMessagesCapture::new(headers, body, mode))
+ }
+ }
+ }
+
fn record_response(&mut self, headers: &HeaderMap) {
match self {
Self::OpenAiResponses(capture) => capture.record_response(headers),
+ Self::AnthropicMessages(capture) => capture.record_response(headers),
}
}
fn push_bytes(&mut self, bytes: &[u8]) -> bool {
match self {
Self::OpenAiResponses(capture) => capture.push_bytes(bytes),
+ Self::AnthropicMessages(capture) => capture.push_bytes(bytes),
}
}
fn end_body(&mut self) {
match self {
Self::OpenAiResponses(capture) => capture.end_body(),
+ Self::AnthropicMessages(capture) => capture.end_body(),
}
}
fn into_facts(self) -> (&'static str, ProviderFacts) {
match self {
Self::OpenAiResponses(capture) => ("openai.responses", capture.into_facts()),
+ Self::AnthropicMessages(capture) => ("anthropic.messages", capture.into_facts()),
}
}
fn client_metadata(&self) -> Option<&Map<String, Value>> {
match self {
Self::OpenAiResponses(capture) => capture.client_metadata(),
+ Self::AnthropicMessages(_) => None,
}
}
}
@@ -90,7 +108,8 @@ impl ExecutionCapture {
}
}
- pub fn for_openai_responses(
+ pub fn for_request(
+ api_format: ApiFormat,
context: &ResolvedRequestContext,
headers: &HeaderMap,
body: &[u8],
@@ -123,10 +142,10 @@ impl ExecutionCapture {
otel.kind = "internal",
http.request.body.size = i64::try_from(body.len()).unwrap_or(i64::MAX)
)
- .in_scope(|| OpenAiResponsesCapture::new(headers, body, context.ingestion_mode()));
+ .in_scope(|| ProtocolCapture::new(api_format, headers, body, context.ingestion_mode()));
Self {
span,
- protocol: Some(ProtocolCapture::OpenAiResponses(protocol)),
+ protocol: Some(protocol),
started,
start_time_unix_ms,
first_byte_ms: None,
diff --git a/ai-gateway/src/capture/openai_responses.rs b/ai-gateway/src/capture/openai_responses.rs
index 3db27e8ba3..968e36d289 100644
--- a/ai-gateway/src/capture/openai_responses.rs
+++ b/ai-gateway/src/capture/openai_responses.rs
@@ -1,20 +1,13 @@
//! `OpenAI` Responses request, JSON response and completed SSE item capture.
use super::{
MAX_CAPTURE_BYTES, MAX_FACT_STRING, MAX_ITEMS, bounded_string, facts::ProviderFacts,
- identity_encoding, sse::SseDecoder,
+ identity_encoding, response::ResponseBody,
};
use crate::{resolution::IngestionMode, telemetry};
-use axum::http::{HeaderMap, header};
+use axum::http::HeaderMap;
use serde_json::{Map, Value};
use std::collections::BTreeMap;
-enum ResponseBody {
- Unknown,
- Json(Vec<u8>),
- Sse(SseDecoder),
- Unavailable,
-}
-
pub(super) struct OpenAiResponsesCapture {
facts: ProviderFacts,
mode: IngestionMode,
@@ -57,23 +50,7 @@ impl OpenAiResponsesCapture {
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.and_then(bounded_string);
- let content_type = headers
- .get(header::CONTENT_TYPE)
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .split(';')
- .next()
- .unwrap_or("")
- .trim();
- self.body = if !identity_encoding(headers) {
- ResponseBody::Unavailable
- } else if content_type.eq_ignore_ascii_case("text/event-stream") {
- ResponseBody::Sse(SseDecoder::default())
- } else if content_type.eq_ignore_ascii_case("application/json") {
- ResponseBody::Json(Vec::new())
- } else {
- ResponseBody::Unavailable
- };
+ self.body = ResponseBody::from_headers(headers);
if matches!(self.body, ResponseBody::Unavailable) {
self.response_valid = false;
}
@@ -82,22 +59,10 @@ impl OpenAiResponsesCapture {
pub fn push_bytes(&mut self, bytes: &[u8]) -> bool {
let mut body = std::mem::replace(&mut self.body, ResponseBody::Unavailable);
let mut completion_started = false;
- match &mut body {
- ResponseBody::Sse(sse) => {
- sse.push(bytes, MAX_CAPTURE_BYTES, |event| {
- completion_started |= self.handle_event(event);
- });
- }
- ResponseBody::Json(buffer)
- if buffer.len().saturating_add(bytes.len()) <= MAX_CAPTURE_BYTES =>
- {
- buffer.extend_from_slice(bytes);
- }
- ResponseBody::Json(_) => {
- body = ResponseBody::Unavailable;
- self.response_valid = false;
- }
- _ => {}
+ if !body.push(bytes, |event| {
+ completion_started |= self.handle_event(event);
+ }) {
+ self.response_valid = false;
}
self.body = body;
completion_started
diff --git a/ai-gateway/src/capture/openai_responses/tests.rs b/ai-gateway/src/capture/openai_responses/tests.rs
index 9b878c2ba0..072132b968 100644
--- a/ai-gateway/src/capture/openai_responses/tests.rs
+++ b/ai-gateway/src/capture/openai_responses/tests.rs
@@ -1,9 +1,11 @@
use super::*;
-use crate::capture::{ExecutionCapture, ProtocolCapture, RelayOutcome};
+use crate::capture::{ExecutionCapture, ProtocolCapture, RelayOutcome, sse::SseDecoder};
+use crate::resolution::ApiFormat;
use crate::{
- providers::openai::{OpenAiProvider, ProviderLimits},
+ providers::{ProviderLimits, ProviderTransport},
test_support::{FakeServer, resolved_request_context_with_mode},
};
+use axum::http::header;
use axum::{
body::{Body, Bytes, to_bytes},
http::{HeaderValue, Response},
@@ -18,13 +20,15 @@ use std::{
use tokio::sync::Notify;
fn captured(execution: &ExecutionCapture) -> &OpenAiResponsesCapture {
- let ProtocolCapture::OpenAiResponses(capture) = execution.protocol.as_ref().unwrap();
+ let ProtocolCapture::OpenAiResponses(capture) = execution.protocol.as_ref().unwrap() else {
+ panic!("expected the OpenAI Responses adapter");
+ };
capture
}
async fn observer(mode: &'static str) -> ExecutionCapture {
let context = resolved_request_context_with_mode("provider-secret", mode).await;
- ExecutionCapture::for_openai_responses(&context, &HeaderMap::new(), br#"{"model":"requested","instructions":"prompt-canary","input":[{"role":"user","content":"hello"}],"tools":[{"type":"function","name":"weather","parameters":{"type":"object"}}],"text":{"format":{"type":"json_schema","schema":{"description":"schema-canary"}}},"service_tier":"auto","metadata":{"label":"request-metadata-canary"},"safety_identifier":"safety-id-canary","prompt_cache_key":"cache-id-canary","user":"user-id-canary"}"#)
+ ExecutionCapture::for_request(ApiFormat::OpenAiResponses, &context, &HeaderMap::new(), br#"{"model":"requested","instructions":"prompt-canary","input":[{"role":"user","content":"hello"}],"tools":[{"type":"function","name":"weather","parameters":{"type":"object"}}],"text":{"format":{"type":"json_schema","schema":{"description":"schema-canary"}}},"service_tier":"auto","metadata":{"label":"request-metadata-canary"},"safety_identifier":"safety-id-canary","prompt_cache_key":"cache-id-canary","user":"user-id-canary"}"#)
}
fn record_response(observer: &mut ExecutionCapture, content_type: &'static str) {
@@ -301,7 +305,8 @@ async fn completion_time_requires_sse_generated_content_in_either_ingestion_mode
}
// The upstream content type controls timing even if the request asks to stream.
let context = resolved_request_context_with_mode("provider-secret", mode).await;
- let mut observer = ExecutionCapture::for_openai_responses(
+ let mut observer = ExecutionCapture::for_request(
+ ApiFormat::OpenAiResponses,
&context,
&HeaderMap::new(),
br#"{"stream":true,"input":"hello"}"#,
@@ -430,7 +435,9 @@ async fn debug_record_is_emitted_once_and_only_at_debug_level() {
observer.push_bytes(terminal("completed", 1).as_bytes());
observer.end_body();
observer.metadata["key_metadata"] = json!({"secret": "metadata-canary"});
- let ProtocolCapture::OpenAiResponses(capture) = observer.protocol.as_mut().unwrap();
+ let ProtocolCapture::OpenAiResponses(capture) = observer.protocol.as_mut().unwrap() else {
+ panic!("expected the OpenAI Responses adapter");
+ };
capture
.facts
.model_parameters
@@ -498,7 +505,7 @@ async fn upstream_read_timeout_is_logged_as_timeout() {
})
.await;
let context = resolved_request_context_with_mode("provider-secret", "full").await;
- let provider = OpenAiProvider::for_test(
+ let provider = ProviderTransport::for_test(
format!("{}/v1", upstream.url),
ProviderLimits {
active: 1,
@@ -553,7 +560,7 @@ async fn native_http_relay_logs_once_on_eof_drop_and_unpolled_deadline() {
})
.await;
let context = resolved_request_context_with_mode("provider-secret", "full").await;
- let provider = OpenAiProvider::for_test(
+ let provider = ProviderTransport::for_test(
format!("{}/v1", upstream.url),
ProviderLimits {
active: 1,
@@ -617,7 +624,7 @@ async fn provider_future_finalizes_on_timeout_and_cancellation_before_headers()
})
.await;
let context = resolved_request_context_with_mode("provider-secret", "full").await;
- let provider = OpenAiProvider::for_test(
+ let provider = ProviderTransport::for_test(
format!("{}/v1", upstream.url),
ProviderLimits {
active: 1,
@@ -721,7 +728,7 @@ async fn client_compression_preferences_do_not_disable_capture() {
.unwrap();
let context = resolved_request_context_with_mode("provider-secret", "full").await;
let provider =
- OpenAiProvider::for_test(format!("{}/v1", upstream.url), ProviderLimits::default())
+ ProviderTransport::for_test(format!("{}/v1", upstream.url), ProviderLimits::default())
.with_telemetry(telemetry.clone());
let mut headers = HeaderMap::new();
headers.insert(
@@ -791,7 +798,7 @@ async fn codex_body_metadata_reaches_the_generation_without_agent_headers() {
.unwrap();
let context = resolved_request_context_with_mode("provider-secret", "full").await;
let provider =
- OpenAiProvider::for_test(format!("{}/v1", upstream.url), ProviderLimits::default())
+ ProviderTransport::for_test(format!("{}/v1", upstream.url), ProviderLimits::default())
.with_telemetry(telemetry.clone());
let turn_metadata = json!({
"installation_id": "install-1", "session_id": "routing-session",
@@ -855,8 +862,12 @@ async fn capture_regression_large_request_does_not_invalidate_output() {
let context = resolved_request_context_with_mode("provider-secret", "full").await;
let request = json!({"input": "x".repeat(MAX_CAPTURE_BYTES)}).to_string();
for streaming in [false, true] {
- let mut observer =
- ExecutionCapture::for_openai_responses(&context, &HeaderMap::new(), request.as_bytes());
+ let mut observer = ExecutionCapture::for_request(
+ ApiFormat::OpenAiResponses,
+ &context,
+ &HeaderMap::new(),
+ request.as_bytes(),
+ );
record_response(
&mut observer,
if streaming {
@@ -892,7 +903,8 @@ async fn capture_regression_preserves_native_request_and_usage() {
] {
let request = json!({"model":"requested","input":input,"instructions":"be brief","future_request_field":{"enabled":true}});
for streaming in [false, true] {
- let mut execution = ExecutionCapture::for_openai_responses(
+ let mut execution = ExecutionCapture::for_request(
+ ApiFormat::OpenAiResponses,
&context,
&HeaderMap::new(),
request.to_string().as_bytes(),
diff --git a/ai-gateway/src/capture/response.rs b/ai-gateway/src/capture/response.rs
new file mode 100644
index 0000000000..bfcbc768ba
--- /dev/null
+++ b/ai-gateway/src/capture/response.rs
@@ -0,0 +1,49 @@
+use super::{MAX_CAPTURE_BYTES, identity_encoding, sse::SseDecoder};
+use axum::http::{HeaderMap, header};
+
+pub(super) enum ResponseBody {
+ Unknown,
+ Json(Vec<u8>),
+ Sse(SseDecoder),
+ Unavailable,
+}
+
+impl ResponseBody {
+ pub(super) fn from_headers(headers: &HeaderMap) -> Self {
+ let content_type = headers
+ .get(header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .split(';')
+ .next()
+ .unwrap_or("")
+ .trim();
+ if !identity_encoding(headers) {
+ Self::Unavailable
+ } else if content_type.eq_ignore_ascii_case("text/event-stream") {
+ Self::Sse(SseDecoder::default())
+ } else if content_type.eq_ignore_ascii_case("application/json") {
+ Self::Json(Vec::new())
+ } else {
+ Self::Unavailable
+ }
+ }
+
+ pub(super) fn push(&mut self, bytes: &[u8], on_event: impl FnMut(&[u8])) -> bool {
+ match self {
+ Self::Sse(sse) => {
+ sse.push(bytes, MAX_CAPTURE_BYTES, on_event);
+ true
+ }
+ Self::Json(buffer) if buffer.len().saturating_add(bytes.len()) <= MAX_CAPTURE_BYTES => {
+ buffer.extend_from_slice(bytes);
+ true
+ }
+ Self::Json(_) => {
+ *self = Self::Unavailable;
+ false
+ }
+ Self::Unknown | Self::Unavailable => true,
+ }
+ }
+}
diff --git a/ai-gateway/src/http.rs b/ai-gateway/src/http.rs
index 09f8bcf902..0d21f1c52f 100644
--- a/ai-gateway/src/http.rs
+++ b/ai-gateway/src/http.rs
@@ -1,4 +1,3 @@
-//! Public OpenAI-compatible envelope around the opaque resolve/execute flow.
use std::{error::Error, sync::Arc, time::Duration};
use axum::{
@@ -14,13 +13,14 @@ use tracing::Instrument;
use crate::{
inference::{InferenceService, RequestPreparationError},
- providers::openai::{OpenAiRoute, ProviderError},
- resolution::ResolutionError,
+ providers::{ProviderError, Route, forwarded_query},
+ resolution::{ApiFormat, ResolutionError},
server::GatewayLifecycleState,
};
-const MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;
+const MAX_REQUEST_BYTES: usize = 10 * 1024 * 1024;
const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(10);
+const MAX_GATEWAY_KEY_BYTES: usize = 8192;
#[derive(Clone)]
struct InferenceRouteState {
@@ -36,45 +36,72 @@ pub fn router(inference: Option<InferenceService>, lifecycle: GatewayLifecycleSt
"/openai/v1/responses/compact",
post(handle_responses_compact),
)
- .route("/openai/v1/models", get(handle_models))
+ .route("/openai/v1/models", get(handle_openai_models))
+ .route("/anthropic/v1/messages", post(handle_messages))
+ .route(
+ "/anthropic/v1/messages/count_tokens",
+ post(handle_count_tokens),
+ )
+ .route("/anthropic/v1/models", get(handle_anthropic_models))
.with_state(InferenceRouteState {
inference: inference.map(Arc::new),
lifecycle,
})
}
-async fn handle_responses(
+async fn handle_responses(State(state): State<InferenceRouteState>, request: Request) -> Response {
+ handle(state, request, Route::OpenAiResponses).await
+}
+
+async fn handle_responses_compact(
State(state): State<InferenceRouteState>,
request: Request,
-) -> Result<Response, InferenceHttpError> {
- handle_openai(state, request, OpenAiRoute::Responses).await
+) -> Response {
+ handle(state, request, Route::OpenAiResponsesCompact).await
}
-async fn handle_responses_compact(
+async fn handle_openai_models(
State(state): State<InferenceRouteState>,
request: Request,
-) -> Result<Response, InferenceHttpError> {
- handle_openai(state, request, OpenAiRoute::ResponsesCompact).await
+) -> Response {
+ handle(state, request, Route::OpenAiModels).await
}
-async fn handle_models(
+async fn handle_messages(State(state): State<InferenceRouteState>, request: Request) -> Response {
+ handle(state, request, Route::AnthropicMessages).await
+}
+
+async fn handle_count_tokens(
State(state): State<InferenceRouteState>,
request: Request,
-) -> Result<Response, InferenceHttpError> {
- handle_openai(state, request, OpenAiRoute::Models).await
+) -> Response {
+ handle(state, request, Route::AnthropicCountTokens).await
+}
+
+async fn handle_anthropic_models(
+ State(state): State<InferenceRouteState>,
+ request: Request,
+) -> Response {
+ handle(state, request, Route::AnthropicModels).await
}
-async fn handle_openai(
+async fn handle(state: InferenceRouteState, request: Request, route: Route) -> Response {
+ relay(state, request, route)
+ .await
+ .unwrap_or_else(|error| error.into_native_response(route.api_format()))
+}
+
+async fn relay(
state: InferenceRouteState,
request: Request,
- route: OpenAiRoute,
+ route: Route,
) -> Result<Response, InferenceHttpError> {
let inference = state
.inference
.as_ref()
.filter(|_| state.lifecycle.is_ready())
.ok_or(InferenceHttpError::Unavailable)?;
- let gateway_key = gateway_key(request.headers())?.to_owned();
+ let gateway_key = gateway_key(request.headers(), route.api_format())?.to_owned();
let (permit, context) = inference
.resolve_and_admit(&gateway_key, route.api_format())
.await
@@ -82,13 +109,22 @@ async fn handle_openai(
RequestPreparationError::Resolution(error) => InferenceHttpError::Resolution(error),
RequestPreparationError::Provider(error) => InferenceHttpError::Provider(error),
})?;
+ let query = forwarded_query(route, request.uri().query());
let (parts, body) = request.into_parts();
- let bytes = match route {
- OpenAiRoute::Models => Bytes::new(),
- OpenAiRoute::Responses | OpenAiRoute::ResponsesCompact => read_request_body(body).await?,
+ let bytes = if route.method() == axum::http::Method::GET {
+ Bytes::new()
+ } else {
+ read_request_body(body).await?
};
inference
- .forward(permit, context, &parts.headers, bytes, route)
+ .forward(
+ permit,
+ context,
+ &parts.headers,
+ bytes,
+ route,
+ query.as_deref(),
+ )
.await
.map_err(InferenceHttpError::Provider)
}
@@ -129,33 +165,59 @@ fn byte_count(len: usize) -> i64 {
i64::try_from(len).unwrap_or(i64::MAX)
}
-fn gateway_key(headers: &HeaderMap) -> Result<&str, InferenceHttpError> {
- let mut values = headers.get_all(header::AUTHORIZATION).iter();
- let value = values
- .next()
- .and_then(|value| value.to_str().ok())
- .ok_or(InferenceHttpError::Credential)?;
- if values.next().is_some() {
- return Err(InferenceHttpError::Credential);
- }
- let (scheme, token) = value
- .split_once(' ')
- .ok_or(InferenceHttpError::Credential)?;
- if !scheme.eq_ignore_ascii_case("Bearer")
- || token.is_empty()
- || token.len() > 8192
- || !token
+fn gateway_key(headers: &HeaderMap, api_format: ApiFormat) -> Result<&str, InferenceHttpError> {
+ let bearer = single_header(headers, header::AUTHORIZATION.as_str())?
+ .map(|value| {
+ value
+ .split_once(' ')
+ .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Bearer"))
+ .map(|(_, token)| token)
+ .ok_or(InferenceHttpError::Credential)
+ })
+ .transpose()?;
+ let api_key = match api_format {
+ ApiFormat::OpenAiResponses => None,
+ ApiFormat::AnthropicMessages => single_header(headers, "x-api-key")?,
+ };
+ let key = match (api_key, bearer) {
+ (Some(api_key), Some(bearer)) if api_key != bearer => {
+ return Err(InferenceHttpError::AmbiguousCredential);
+ }
+ (Some(key), _) | (None, Some(key)) => key,
+ (None, None) => return Err(InferenceHttpError::Credential),
+ };
+ if key.is_empty()
+ || key.len() > MAX_GATEWAY_KEY_BYTES
+ || !key
.bytes()
.all(|byte| byte.is_ascii_graphic() && byte != b',')
{
return Err(InferenceHttpError::Credential);
}
- Ok(token)
+ Ok(key)
+}
+
+fn single_header<'a>(
+ headers: &'a HeaderMap,
+ name: &str,
+) -> Result<Option<&'a str>, InferenceHttpError> {
+ let mut values = headers.get_all(name).iter();
+ let Some(value) = values.next() else {
+ return Ok(None);
+ };
+ if values.next().is_some() {
+ return Err(InferenceHttpError::Credential);
+ }
+ value
+ .to_str()
+ .map(Some)
+ .map_err(|_| InferenceHttpError::Credential)
}
enum InferenceHttpError {
Unavailable,
Credential,
+ AmbiguousCredential,
TooLarge,
RequestTimeout,
InvalidBody,
@@ -176,12 +238,26 @@ struct OpenAiErrorDetail {
code: &'static str,
}
+#[derive(Serialize)]
+struct AnthropicErrorResponse {
+ #[serde(rename = "type")]
+ kind: &'static str,
+ error: AnthropicErrorDetail,
+}
+#[derive(Serialize)]
+struct AnthropicErrorDetail {
+ #[serde(rename = "type")]
+ kind: &'static str,
+ message: &'static str,
+}
+
impl InferenceHttpError {
fn category(&self) -> (&'static str, &'static str) {
use ResolutionError as R;
match self {
Self::Unavailable => ("admission", "unavailable"),
Self::Credential => ("authentication", "invalid_credential"),
+ Self::AmbiguousCredential => ("authentication", "ambiguous_credential"),
Self::TooLarge => ("request", "body_too_large"),
Self::RequestTimeout => ("request", "body_timeout"),
Self::InvalidBody => ("request", "invalid_body"),
@@ -210,19 +286,22 @@ impl InferenceHttpError {
),
}
}
-}
-impl IntoResponse for InferenceHttpError {
- fn into_response(self) -> Response<Body> {
+ fn classify(&self) -> (StatusCode, &'static str, &'static str, &'static str) {
use ResolutionError as R;
- let (phase, reason) = self.category();
- let (status, message, kind, code) = match self {
+ match self {
Self::Credential | Self::Resolution(R::InvalidCredential | R::Authentication) => (
StatusCode::UNAUTHORIZED,
"Invalid gateway credential",
"authentication_error",
"invalid_api_key",
),
+ Self::AmbiguousCredential => (
+ StatusCode::UNAUTHORIZED,
+ "Conflicting gateway credentials in the Authorization and x-api-key headers",
+ "authentication_error",
+ "ambiguous_api_key",
+ ),
Self::Resolution(R::Forbidden) => (
StatusCode::FORBIDDEN,
"Gateway access forbidden",
@@ -274,7 +353,12 @@ impl IntoResponse for InferenceHttpError {
"server_error",
"upstream_error",
),
- };
+ }
+ }
+
+ fn into_native_response(self, api_format: ApiFormat) -> Response {
+ let (phase, reason) = self.category();
+ let (status, message, kind, code) = self.classify();
if status.is_server_error() {
tracing::warn!(
phase,
@@ -290,18 +374,43 @@ impl IntoResponse for InferenceHttpError {
"gateway request rejected"
);
}
- (
- status,
- Json(OpenAiErrorResponse {
- error: OpenAiErrorDetail {
- message,
- kind,
- param: None,
- code,
- },
- }),
- )
- .into_response()
+ match api_format {
+ ApiFormat::OpenAiResponses => (
+ status,
+ Json(OpenAiErrorResponse {
+ error: OpenAiErrorDetail {
+ message,
+ kind,
+ param: None,
+ code,
+ },
+ }),
+ )
+ .into_response(),
+ ApiFormat::AnthropicMessages => (
+ status,
+ Json(AnthropicErrorResponse {
+ kind: "error",
+ error: AnthropicErrorDetail {
+ kind: anthropic_error_type(status),
+ message,
+ },
+ }),
+ )
+ .into_response(),
+ }
+ }
+}
+
+fn anthropic_error_type(status: StatusCode) -> &'static str {
+ match status {
+ StatusCode::UNAUTHORIZED => "authentication_error",
+ StatusCode::FORBIDDEN => "permission_error",
+ StatusCode::NOT_FOUND => "not_found_error",
+ StatusCode::PAYLOAD_TOO_LARGE => "request_too_large",
+ StatusCode::SERVICE_UNAVAILABLE => "overloaded_error",
+ status if status.is_client_error() => "invalid_request_error",
+ _ => "api_error",
}
}
diff --git a/ai-gateway/src/http/tests.rs b/ai-gateway/src/http/tests.rs
index 1251f06971..3128f1e7be 100644
--- a/ai-gateway/src/http/tests.rs
+++ b/ai-gateway/src/http/tests.rs
@@ -1,7 +1,8 @@
use super::*;
use crate::{
- providers::openai::{OpenAiProvider, ProviderLimits},
- test_support::{FakeServer, resolution_response},
+ providers::{ProviderLimits, ProviderTransport},
+ resolution::ApiFormat,
+ test_support::{FakeServer, resolution_response, resolution_response_for},
};
use futures_util::{StreamExt, stream};
use std::{convert::Infallible, task::Poll};
@@ -18,7 +19,7 @@ async fn invalid_credentials_are_rejected_before_admission_or_body_reads() {
})
.await;
let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
- let provider_client = OpenAiProvider::for_test(
+ let provider_client = ProviderTransport::for_test(
provider.url.clone(),
ProviderLimits {
active: 1,
@@ -89,7 +90,7 @@ async fn resolution_capacity_is_bounded_and_released_on_cancellation_and_failure
let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
let service = InferenceService::for_test(
web.control_plane(),
- OpenAiProvider::for_test(provider.url.clone(), ProviderLimits::default()),
+ ProviderTransport::for_test(provider.url.clone(), ProviderLimits::default()),
1,
);
let gateway = Gateway::start(Some(service)).await;
@@ -194,7 +195,7 @@ impl Drop for Gateway {
fn inference(web: &FakeServer, provider: &FakeServer) -> InferenceService {
InferenceService::for_test(
web.control_plane(),
- OpenAiProvider::for_test(format!("{}/v1", provider.url), ProviderLimits::default()),
+ ProviderTransport::for_test(format!("{}/v1", provider.url), ProviderLimits::default()),
128,
)
}
@@ -351,7 +352,7 @@ async fn malformed_credentials_skip_resolution_and_oversized_body_releases_capac
let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
let service = InferenceService::for_test(
web.control_plane(),
- OpenAiProvider::for_test(
+ ProviderTransport::for_test(
provider.url.clone(),
ProviderLimits {
active: 1,
@@ -527,7 +528,7 @@ async fn pre_header_provider_failures_export_the_status_returned_to_the_caller()
}
});
let web = FakeServer::start(|_| async { resolution_response("provider-secret") }).await;
- let provider = OpenAiProvider::for_test(
+ let provider = ProviderTransport::for_test(
upstream_url,
ProviderLimits {
headers_timeout: Duration::from_millis(100),
@@ -636,7 +637,7 @@ async fn active_admission_is_held_through_stream_and_shutdown_drains_it() {
.await;
let service = InferenceService::for_test(
web.control_plane(),
- OpenAiProvider::for_test(
+ ProviderTransport::for_test(
provider.url.clone(),
ProviderLimits {
active: 1,
@@ -692,7 +693,7 @@ async fn client_disconnect_releases_capacity_for_the_next_request() {
.await;
let service = InferenceService::for_test(
web.control_plane(),
- OpenAiProvider::for_test(
+ ProviderTransport::for_test(
provider.url.clone(),
ProviderLimits {
active: 1,
@@ -733,3 +734,256 @@ async fn client_disconnect_releases_capacity_for_the_next_request() {
assert!(web.calls() >= 2);
assert_eq!(provider.calls(), 2);
}
+
+fn anthropic_gateway_key(request: &Request<Body>) -> Option<String> {
+ request
+ .headers()
+ .get(header::AUTHORIZATION)
+ .and_then(|value| value.to_str().ok())
+ .map(|value| value.trim_start_matches("Bearer ").to_owned())
+}
+
+#[tokio::test]
+async fn anthropic_messages_accept_either_credential_header_and_relay_native_sse() {
+ let web = FakeServer::start(|request| async move {
+ let key = anthropic_gateway_key(&request).unwrap();
+ assert_eq!(
+ to_bytes(request.into_body(), 1024).await.unwrap(),
+ r#"{"apiFormat":"anthropic.messages"}"#
+ );
+ if key == "gateway-anthropic" {
+ resolution_response_for(ApiFormat::AnthropicMessages, "provider-anthropic")
+ } else {
+ Response::builder()
+ .status(StatusCode::UNAUTHORIZED)
+ .body(Body::empty())
+ .unwrap()
+ }
+ })
+ .await;
+ let provider = FakeServer::start(|request| async move {
+ assert_eq!(request.uri(), "/v1/messages");
+ assert_eq!(request.headers()["x-api-key"], "provider-anthropic");
+ assert_eq!(request.headers()["anthropic-version"], "2023-06-01");
+ assert!(!request.headers().contains_key(header::AUTHORIZATION));
+ Response::builder()
+ .header("content-type", "text/event-stream")
+ .header("request-id", "req_upstream")
+ .body(Body::from_stream(stream::iter([
+ Ok::<_, Infallible>("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n"),
+ Ok("event: ping\ndata: {\"type\":\"ping\"}\n\n"),
+ Ok("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"),
+ ])))
+ .unwrap()
+ })
+ .await;
+ let gateway = Gateway::start(Some(inference(&web, &provider))).await;
+ let client = reqwest::Client::new();
+ // Claude Code sends x-api-key for ANTHROPIC_API_KEY, Authorization for
+ // ANTHROPIC_AUTH_TOKEN, and both when a helper supplies one credential.
+ for credential_headers in [
+ vec![("x-api-key", "gateway-anthropic")],
+ vec![("authorization", "Bearer gateway-anthropic")],
+ vec![
+ ("x-api-key", "gateway-anthropic"),
+ ("authorization", "Bearer gateway-anthropic"),
+ ],
+ ] {
+ let mut request = client
+ .post(format!("{}/anthropic/v1/messages?beta=true", gateway.url))
+ .header("anthropic-version", "2023-06-01")
+ .header("content-type", "application/json")
+ .body(r#"{"model":"claude-sonnet-4-5","stream":true,"messages":[]}"#);
+ for (name, value) in credential_headers {
+ request = request.header(name, value);
+ }
+ let response = request.send().await.unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response.headers()["request-id"], "req_upstream");
+ let body = response.text().await.unwrap();
+ assert!(body.starts_with("event: message_start\n"));
+ assert!(body.ends_with("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"));
+ }
+ assert_eq!(web.calls(), 3);
+ assert_eq!(provider.calls(), 3);
+}
+
+type EnvelopeCase = (
+ &'static [(&'static str, &'static str)],
+ StatusCode,
+ &'static str,
+ Option<&'static str>,
+);
+
+#[tokio::test]
+async fn anthropic_credential_conflicts_and_failures_use_the_native_error_envelope() {
+ let web = FakeServer::start(|request| async move {
+ let status = match anthropic_gateway_key(&request).as_deref() {
+ Some("forbidden") => StatusCode::FORBIDDEN,
+ Some("unrouted") => StatusCode::NOT_FOUND,
+ _ => StatusCode::UNAUTHORIZED,
+ };
+ Response::builder()
+ .status(status)
+ .body(Body::from("private-web-body"))
+ .unwrap()
+ })
+ .await;
+ let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
+ let gateway = Gateway::start(Some(inference(&web, &provider))).await;
+ let client = reqwest::Client::new();
+ let cases: [EnvelopeCase; 6] = [
+ (
+ &[
+ ("x-api-key", "real-anthropic-key"),
+ ("authorization", "Bearer gateway-key"),
+ ],
+ StatusCode::UNAUTHORIZED,
+ "authentication_error",
+ Some("Conflicting gateway credentials in the Authorization and x-api-key headers"),
+ ),
+ (&[], StatusCode::UNAUTHORIZED, "authentication_error", None),
+ (
+ &[("x-api-key", "bad key")],
+ StatusCode::UNAUTHORIZED,
+ "authentication_error",
+ None,
+ ),
+ (
+ &[("authorization", "Basic Zm9v")],
+ StatusCode::UNAUTHORIZED,
+ "authentication_error",
+ None,
+ ),
+ (
+ &[("x-api-key", "forbidden")],
+ StatusCode::FORBIDDEN,
+ "permission_error",
+ None,
+ ),
+ (
+ &[("x-api-key", "unrouted")],
+ StatusCode::NOT_FOUND,
+ "not_found_error",
+ None,
+ ),
+ ];
+ for (credential_headers, status, kind, message) in cases {
+ let mut request = client
+ .post(format!("{}/anthropic/v1/messages", gateway.url))
+ .body("{}");
+ for (name, value) in credential_headers {
+ request = request.header(*name, *value);
+ }
+ let response = request.send().await.unwrap();
+ assert_eq!(response.status(), status, "{credential_headers:?}");
+ let body: serde_json::Value =
+ serde_json::from_str(&response.text().await.unwrap()).unwrap();
+ assert_eq!(body["type"], "error", "{credential_headers:?}");
+ assert_eq!(body["error"]["type"], kind, "{credential_headers:?}");
+ assert!(body["error"]["message"].is_string());
+ if let Some(message) = message {
+ assert_eq!(body["error"]["message"], message);
+ }
+ assert!(!body.to_string().contains("private-web-body"));
+ }
+ // Conflicting or malformed credentials never reach Web; the two Web rejections do.
+ assert_eq!(web.calls(), 2);
+ assert_eq!(provider.calls(), 0);
+}
+
+#[tokio::test]
+async fn anthropic_capacity_rejections_use_the_native_envelope() {
+ let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
+ let busy = ProviderTransport::for_test(
+ format!("{}/v1", provider.url),
+ ProviderLimits {
+ active: 1,
+ ..ProviderLimits::default()
+ },
+ );
+ let _held = busy.try_admit().unwrap();
+ let web = FakeServer::start(|_| async {
+ resolution_response_for(ApiFormat::AnthropicMessages, "provider-anthropic")
+ })
+ .await;
+ let gateway = Gateway::start(Some(InferenceService::for_test(
+ web.control_plane(),
+ busy,
+ 1,
+ )))
+ .await;
+ let response = reqwest::Client::new()
+ .post(format!("{}/anthropic/v1/messages", gateway.url))
+ .header("x-api-key", "gateway-anthropic")
+ .body("{}")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ let body: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
+ assert_eq!(body["error"]["type"], "overloaded_error");
+ assert_eq!(provider.calls(), 0);
+}
+
+#[tokio::test]
+async fn openai_routes_ignore_x_api_key_and_keep_their_envelope() {
+ let web = FakeServer::start(|_| async {
+ Response::builder()
+ .status(StatusCode::UNAUTHORIZED)
+ .body(Body::empty())
+ .unwrap()
+ })
+ .await;
+ let provider = FakeServer::start(|_| async { Response::new(Body::empty()) }).await;
+ let gateway = Gateway::start(Some(inference(&web, &provider))).await;
+ let response = gateway
+ .post()
+ .header("x-api-key", "gateway-key")
+ .body("{}")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ let body: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
+ assert_eq!(body["error"]["code"], "invalid_api_key");
+ assert!(body.get("type").is_none());
+ assert_eq!(web.calls(), 0);
+}
+
+#[tokio::test]
+async fn anthropic_routes_share_the_request_body_limit() {
+ let web = FakeServer::start(|_| async {
+ resolution_response_for(ApiFormat::AnthropicMessages, "provider-anthropic")
+ })
+ .await;
+ let provider = FakeServer::start(|request| async move {
+ let body = to_bytes(request.into_body(), MAX_REQUEST_BYTES)
+ .await
+ .unwrap();
+ assert_eq!(body.len(), MAX_REQUEST_BYTES);
+ Response::new(Body::empty())
+ })
+ .await;
+ let gateway = Gateway::start(Some(inference(&web, &provider))).await;
+ let client = reqwest::Client::new();
+ for path in ["messages", "messages/count_tokens"] {
+ let send = |size| {
+ client
+ .post(format!("{}/anthropic/v1/{path}", gateway.url))
+ .header("x-api-key", "gateway-anthropic")
+ .body(vec![b'x'; size])
+ .send()
+ };
+ assert_eq!(
+ send(MAX_REQUEST_BYTES).await.unwrap().status(),
+ StatusCode::OK
+ );
+ let rejected = send(MAX_REQUEST_BYTES + 1).await.unwrap();
+ assert_eq!(rejected.status(), StatusCode::PAYLOAD_TOO_LARGE);
+ let body: serde_json::Value =
+ serde_json::from_str(&rejected.text().await.unwrap()).unwrap();
+ assert_eq!(body["error"]["type"], "request_too_large");
+ }
+ assert_eq!(provider.calls(), 2);
+}
diff --git a/ai-gateway/src/inference.rs b/ai-gateway/src/inference.rs
index a724b86bf2..36d8f92306 100644
--- a/ai-gateway/src/inference.rs
+++ b/ai-gateway/src/inference.rs
@@ -7,7 +7,7 @@ use tokio::sync::Semaphore;
use tracing::Instrument;
use crate::{
- providers::openai::{OpenAiProvider, OpenAiRoute, ProviderError, RequestPermit},
+ providers::{ProviderError, ProviderTransport, RequestPermit, Route},
resolution::{
ApiFormat, ControlPlaneClient, ControlPlaneConfig, ResolutionError, ResolvedRequestContext,
},
@@ -15,7 +15,7 @@ use crate::{
pub struct InferenceService {
control_plane: ControlPlaneClient,
- provider: OpenAiProvider,
+ provider: ProviderTransport,
resolution_capacity: Semaphore,
telemetry: Option<crate::telemetry::Telemetry>,
}
@@ -41,7 +41,7 @@ impl InferenceService {
let telemetry = crate::telemetry::Telemetry::new(&config)?;
Ok(Self {
control_plane: ControlPlaneClient::new(config)?,
- provider: OpenAiProvider::new(max_active_requests)
+ provider: ProviderTransport::new(max_active_requests)
.map_err(|_| ResolutionError::Configuration)?
.with_telemetry(telemetry.clone()),
resolution_capacity: Semaphore::new(max_concurrent_resolutions),
@@ -54,6 +54,7 @@ impl InferenceService {
}
/// Authenticate with a separate bounded budget before reserving execution capacity.
+ /// The API format comes from the public route, so Web selects a compatible connection.
pub(crate) async fn resolve_and_admit(
&self,
gateway_key: &str,
@@ -109,17 +110,18 @@ impl InferenceService {
context: ResolvedRequestContext,
headers: &HeaderMap,
body: Bytes,
- route: OpenAiRoute,
+ route: Route,
+ query: Option<&str>,
) -> Result<Response<Body>, ProviderError> {
self.provider
- .forward_route(permit, context, headers, body, route)
+ .forward_route(permit, context, headers, body, route, query)
.await
}
#[cfg(test)]
pub(crate) fn for_test(
control_plane: ControlPlaneClient,
- provider: OpenAiProvider,
+ provider: ProviderTransport,
resolutions: usize,
) -> Self {
Self {
diff --git a/ai-gateway/src/observability/http/tests.rs b/ai-gateway/src/observability/http/tests.rs
index 2786677ab3..33be8af730 100644
--- a/ai-gateway/src/observability/http/tests.rs
+++ b/ai-gateway/src/observability/http/tests.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::{
inference::InferenceService,
- providers::openai::{OpenAiProvider, ProviderLimits},
+ providers::{ProviderLimits, ProviderTransport},
resolution::ControlPlaneConfig,
server::GatewayLifecycleState,
telemetry::Telemetry,
@@ -178,7 +178,7 @@ async fn cancellation_releases_spans_before_and_after_headers() {
#[tokio::test]
async fn provider_http_errors_are_traced_without_changing_the_response() {
use crate::{
- providers::openai::{OpenAiProvider, ProviderLimits},
+ providers::{ProviderLimits, ProviderTransport},
test_support::{FakeServer, resolved_request_context},
};
for status in [429, 500] {
@@ -191,7 +191,7 @@ async fn provider_http_errors_are_traced_without_changing_the_response() {
})
.await;
let provider =
- OpenAiProvider::for_test(format!("{}/v1", upstream.url), ProviderLimits::default());
+ ProviderTransport::for_test(format!("{}/v1", upstream.url), ProviderLimits::default());
let recording = Recording::start();
let response = provider
.forward(
@@ -276,7 +276,7 @@ async fn generation_context_is_isolated_from_operational_spans_and_outbound_head
Telemetry::new(&ControlPlaneConfig::new(&web.url, "test-service-key").unwrap()).unwrap();
let service = InferenceService::for_test(
web.control_plane(),
- OpenAiProvider::for_test(provider.url.clone(), ProviderLimits::default())
+ ProviderTransport::for_test(provider.url.clone(), ProviderLimits::default())
.with_telemetry(telemetry.clone()),
1,
);
diff --git a/ai-gateway/src/providers/mod.rs b/ai-gateway/src/providers/mod.rs
index d8c308735b..496fa5a523 100644
--- a/ai-gateway/src/providers/mod.rs
+++ b/ai-gateway/src/providers/mod.rs
@@ -1 +1,300 @@
-pub mod openai;
+use std::{sync::Arc, time::Duration};
+
+use axum::{
+ body::{Body, Bytes},
+ http::{HeaderMap, HeaderName, HeaderValue, Method, Response, header},
+};
+use reqwest::Client;
+use reqwest_middleware::ClientWithMiddleware;
+use reqwest_tracing::DisableOtelPropagation;
+use tokio::{
+ sync::{OwnedSemaphorePermit, Semaphore},
+ time::Instant,
+};
+
+pub use crate::transport::ProviderError;
+use crate::{
+ capture::{ExecutionCapture, RelayOutcome},
+ resolution::{ApiFormat, Provider, ProviderCredential, ResolvedRequestContext},
+ transport,
+};
+
+#[derive(Clone, Copy)]
+pub(crate) enum Route {
+ OpenAiResponses,
+ OpenAiResponsesCompact,
+ OpenAiModels,
+ AnthropicMessages,
+ AnthropicCountTokens,
+ AnthropicModels,
+}
+
+impl Route {
+ pub(crate) fn provider(self) -> Provider {
+ match self {
+ Self::OpenAiResponses | Self::OpenAiResponsesCompact | Self::OpenAiModels => {
+ Provider::OpenAi
+ }
+ Self::AnthropicMessages | Self::AnthropicCountTokens | Self::AnthropicModels => {
+ Provider::Anthropic
+ }
+ }
+ }
+
+ pub(crate) fn api_format(self) -> ApiFormat {
+ match self.provider() {
+ Provider::OpenAi => ApiFormat::OpenAiResponses,
+ Provider::Anthropic => ApiFormat::AnthropicMessages,
+ }
+ }
+
+ pub(crate) fn method(self) -> Method {
+ match self {
+ Self::OpenAiModels | Self::AnthropicModels => Method::GET,
+ _ => Method::POST,
+ }
+ }
+
+ fn path(self) -> &'static str {
+ match self {
+ Self::OpenAiResponses => "/responses",
+ Self::OpenAiResponsesCompact => "/responses/compact",
+ Self::OpenAiModels | Self::AnthropicModels => "/models",
+ Self::AnthropicMessages => "/messages",
+ Self::AnthropicCountTokens => "/messages/count_tokens",
+ }
+ }
+
+ pub(crate) fn captures_generation(self) -> bool {
+ matches!(
+ self,
+ Self::OpenAiResponses | Self::OpenAiResponsesCompact | Self::AnthropicMessages
+ )
+ }
+
+ pub(crate) fn forwarded_query_parameters(self) -> &'static [&'static str] {
+ match self {
+ Self::AnthropicModels => &["limit", "after_id", "before_id"],
+ _ => &[],
+ }
+ }
+}
+
+pub(crate) struct ProviderLimits {
+ pub active: usize,
+ pub execution_timeout: Duration,
+ pub headers_timeout: Duration,
+ pub read_timeout: Duration,
+}
+
+impl Default for ProviderLimits {
+ fn default() -> Self {
+ Self {
+ active: 128,
+ execution_timeout: Duration::from_secs(600),
+ headers_timeout: Duration::from_secs(120),
+ read_timeout: Duration::from_secs(120),
+ }
+ }
+}
+
+pub struct RequestPermit {
+ _permit: OwnedSemaphorePermit,
+ _active: crate::observability::Active,
+ deadline: Instant,
+}
+
+pub struct ProviderTransport {
+ client: ClientWithMiddleware,
+ capacity: Arc<Semaphore>,
+ limits: ProviderLimits,
+ telemetry: Option<crate::telemetry::Telemetry>,
+ origin_override: Option<String>,
+}
+
+impl ProviderTransport {
+ /// # Errors
+ /// Returns [`ProviderError::Configuration`] when the HTTPS client cannot be initialized.
+ pub fn new(max_active_requests: usize) -> Result<Self, ProviderError> {
+ Self::with_limits(ProviderLimits {
+ active: max_active_requests,
+ ..ProviderLimits::default()
+ })
+ }
+
+ fn with_limits(limits: ProviderLimits) -> Result<Self, ProviderError> {
+ if !(1..=Semaphore::MAX_PERMITS).contains(&limits.active) {
+ return Err(ProviderError::Configuration);
+ }
+ let client = Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .retry(reqwest::retry::never())
+ .no_proxy()
+ .no_gzip()
+ .no_brotli()
+ .no_deflate()
+ .no_zstd()
+ .connect_timeout(Duration::from_secs(5))
+ .read_timeout(limits.read_timeout)
+ .pool_max_idle_per_host(16)
+ .build()
+ .map_err(|_| ProviderError::Configuration)?;
+ Ok(Self {
+ client: crate::observability::instrument_client(client, "provider.headers"),
+ capacity: Arc::new(Semaphore::new(limits.active)),
+ limits,
+ telemetry: None,
+ origin_override: None,
+ })
+ }
+
+ pub(crate) fn with_telemetry(mut self, telemetry: crate::telemetry::Telemetry) -> Self {
+ self.telemetry = Some(telemetry);
+ self
+ }
+
+ /// # Errors
+ /// Returns [`ProviderError::Busy`] immediately when all execution slots are occupied.
+ pub fn try_admit(&self) -> Result<RequestPermit, ProviderError> {
+ let permit = self.capacity.clone().try_acquire_owned().map_err(|_| {
+ crate::observability::rejected("execution");
+ ProviderError::Busy
+ })?;
+ Ok(RequestPermit {
+ _permit: permit,
+ _active: crate::observability::Active::new("execution"),
+ deadline: Instant::now() + self.limits.execution_timeout,
+ })
+ }
+
+ /// # Errors
+ /// See [`Self::forward_route`].
+ pub async fn forward(
+ &self,
+ permit: RequestPermit,
+ context: ResolvedRequestContext,
+ headers: &HeaderMap,
+ body: Bytes,
+ ) -> Result<Response<Body>, ProviderError> {
+ self.forward_route(permit, context, headers, body, Route::OpenAiResponses, None)
+ .await
+ }
+
+ pub(crate) async fn forward_route(
+ &self,
+ permit: RequestPermit,
+ context: ResolvedRequestContext,
+ headers: &HeaderMap,
+ body: Bytes,
+ route: Route,
+ query: Option<&str>,
+ ) -> Result<Response<Body>, ProviderError> {
+ let api_format = route.api_format();
+ let (credential_name, mut credential) = provider_credential(&context)?;
+ credential.set_sensitive(true);
+ let mut capture = if route.captures_generation() {
+ let mut capture = ExecutionCapture::for_request(api_format, &context, headers, &body);
+ if let Some(telemetry) = &self.telemetry {
+ capture.deliver_to(telemetry.clone(), &context, headers);
+ }
+ capture
+ } else {
+ ExecutionCapture::unobserved()
+ };
+ let mut upstream = self
+ .client
+ .request(route.method(), self.request_url(route, query))
+ .with_extension(DisableOtelPropagation)
+ .headers(transport::request_headers(headers, api_format))
+ .header(header::ACCEPT_ENCODING, "identity")
+ .header(credential_name, credential);
+ if route.method() != Method::GET {
+ upstream = upstream.body(body);
+ }
+ let response = tokio::time::timeout_at(
+ permit
+ .deadline
+ .min(Instant::now() + self.limits.headers_timeout),
+ upstream.send(),
+ )
+ .await
+ .map_err(|_| ProviderError::Timeout)
+ .and_then(|result| {
+ result.map_err(|error| {
+ if error.is_timeout() {
+ ProviderError::Timeout
+ } else {
+ ProviderError::Transport
+ }
+ })
+ });
+ let response = match response {
+ Ok(response) => response,
+ Err(error) => {
+ capture.finish(if matches!(error, ProviderError::Timeout) {
+ RelayOutcome::Timeout
+ } else {
+ RelayOutcome::TransportError
+ });
+ return Err(error);
+ }
+ };
+ capture.record_response(response.status().as_u16(), response.headers());
+ let mut downstream = Response::new(Body::empty());
+ *downstream.status_mut() = response.status();
+ *downstream.headers_mut() = transport::response_headers(response.headers(), api_format);
+ *downstream.body_mut() =
+ transport::relay(response, permit.deadline, (permit, context), capture);
+ Ok(downstream)
+ }
+
+ fn request_url(&self, route: Route, query: Option<&str>) -> String {
+ let base = self
+ .origin_override
+ .as_deref()
+ .unwrap_or_else(|| route.provider().official_origin())
+ .trim_end_matches('/');
+ let mut url = String::with_capacity(base.len() + route.path().len());
+ url.push_str(base);
+ url.push_str(route.path());
+ if let Some(query) = query.filter(|query| !query.is_empty()) {
+ url.push('?');
+ url.push_str(query);
+ }
+ url
+ }
+
+ #[cfg(test)]
+ pub(crate) fn for_test(base_url: String, limits: ProviderLimits) -> Self {
+ let mut provider = Self::with_limits(limits).unwrap();
+ provider.origin_override = Some(base_url);
+ provider
+ }
+}
+
+fn provider_credential(
+ context: &ResolvedRequestContext,
+) -> Result<(HeaderName, HeaderValue), ProviderError> {
+ let (name, value) = match context.connection().credential() {
+ ProviderCredential::Bearer(token) => (header::AUTHORIZATION, format!("Bearer {token}")),
+ ProviderCredential::XApiKey(key) => (HeaderName::from_static("x-api-key"), key.to_owned()),
+ };
+ let value = HeaderValue::from_str(&value).map_err(|_| ProviderError::Configuration)?;
+ Ok((name, value))
+}
+
+pub(crate) fn forwarded_query(route: Route, query: Option<&str>) -> Option<String> {
+ let allowed = route.forwarded_query_parameters();
+ let query = query?;
+ let kept: Vec<&str> = query
+ .split('&')
+ .filter(|pair| {
+ let key = pair.split('=').next().unwrap_or("");
+ allowed.contains(&key)
+ })
+ .collect();
+ (!kept.is_empty()).then(|| kept.join("&"))
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/ai-gateway/src/providers/openai.rs b/ai-gateway/src/providers/openai.rs
deleted file mode 100644
index 8c06584fe5..0000000000
--- a/ai-gateway/src/providers/openai.rs
+++ /dev/null
@@ -1,260 +0,0 @@
-//! Native `OpenAI` v1 transport. Provider requests use only resolved credentials.
-use std::{sync::Arc, time::Duration};
-
-use axum::{
- body::{Body, Bytes},
- http::{HeaderMap, HeaderValue, Method, Response, header},
-};
-use reqwest::Client;
-use reqwest_middleware::ClientWithMiddleware;
-use reqwest_tracing::DisableOtelPropagation;
-use tokio::{
- sync::{OwnedSemaphorePermit, Semaphore},
- time::Instant,
-};
-
-use crate::{
- capture::{ExecutionCapture, RelayOutcome},
- resolution::{ApiFormat, ProviderCredential, ResolvedRequestContext},
- transport,
-};
-
-pub use crate::transport::ProviderError;
-
-const OPENAI_V1: &str = "https://api.openai.com/v1";
-
-/// Official `OpenAI` paths relayed without translation. Compact is Responses JSON;
-/// models listing is GET with no request query forwarding and no generation ingest.
-#[derive(Clone, Copy)]
-pub(crate) enum OpenAiRoute {
- Responses,
- ResponsesCompact,
- Models,
-}
-
-impl OpenAiRoute {
- fn method(self) -> Method {
- match self {
- Self::Models => Method::GET,
- Self::Responses | Self::ResponsesCompact => Method::POST,
- }
- }
-
- fn path(self) -> &'static str {
- match self {
- Self::Responses => "/responses",
- Self::ResponsesCompact => "/responses/compact",
- Self::Models => "/models",
- }
- }
-
- fn captures_generation(self) -> bool {
- !matches!(self, Self::Models)
- }
-
- pub(crate) fn api_format(self) -> ApiFormat {
- match self {
- Self::Responses | Self::ResponsesCompact | Self::Models => ApiFormat::OpenAiResponses,
- }
- }
-}
-
-pub(crate) struct ProviderLimits {
- pub active: usize,
- pub execution_timeout: Duration,
- pub headers_timeout: Duration,
- pub read_timeout: Duration,
-}
-
-impl Default for ProviderLimits {
- fn default() -> Self {
- Self {
- active: 128,
- execution_timeout: Duration::from_secs(600),
- headers_timeout: Duration::from_secs(120),
- read_timeout: Duration::from_secs(120),
- }
- }
-}
-
-/// An admitted execution. Dropping it releases capacity; there is no waiting queue.
-pub struct RequestPermit {
- _permit: OwnedSemaphorePermit,
- _active: crate::observability::Active,
- deadline: Instant,
-}
-
-/// A pooled client for the official `OpenAI` Responses endpoint.
-pub struct OpenAiProvider {
- client: ClientWithMiddleware,
- capacity: Arc<Semaphore>,
- limits: ProviderLimits,
- telemetry: Option<crate::telemetry::Telemetry>,
- base_url: String,
-}
-
-impl OpenAiProvider {
- /// Construct the provider transport with bounded admission and transport waits.
- ///
- /// # Errors
- /// Returns [`ProviderError::Configuration`] when the HTTPS client cannot be initialized.
- pub fn new(max_active_requests: usize) -> Result<Self, ProviderError> {
- Self::with_limits(ProviderLimits {
- active: max_active_requests,
- ..ProviderLimits::default()
- })
- }
-
- fn with_limits(limits: ProviderLimits) -> Result<Self, ProviderError> {
- if !(1..=Semaphore::MAX_PERMITS).contains(&limits.active) {
- return Err(ProviderError::Configuration);
- }
- let client = Client::builder()
- .redirect(reqwest::redirect::Policy::none())
- .retry(reqwest::retry::never())
- .no_proxy()
- .no_gzip()
- .no_brotli()
- .no_deflate()
- .no_zstd()
- .connect_timeout(Duration::from_secs(5))
- .read_timeout(limits.read_timeout)
- .pool_max_idle_per_host(16)
- .build()
- .map_err(|_| ProviderError::Configuration)?;
- Ok(Self {
- client: crate::observability::instrument_client(client, "provider.headers"),
- capacity: Arc::new(Semaphore::new(limits.active)),
- limits,
- telemetry: None,
- base_url: OPENAI_V1.to_owned(),
- })
- }
-
- pub(crate) fn with_telemetry(mut self, telemetry: crate::telemetry::Telemetry) -> Self {
- self.telemetry = Some(telemetry);
- self
- }
-
- /// Reserve capacity for an authenticated request before reading its body.
- ///
- /// # Errors
- /// Returns [`ProviderError::Busy`] immediately when all execution slots are occupied.
- pub fn try_admit(&self) -> Result<RequestPermit, ProviderError> {
- let permit = self.capacity.clone().try_acquire_owned().map_err(|_| {
- crate::observability::rejected("execution");
- ProviderError::Busy
- })?;
- Ok(RequestPermit {
- _permit: permit,
- _active: crate::observability::Active::new("execution"),
- deadline: Instant::now() + self.limits.execution_timeout,
- })
- }
-
- /// Execute once and stream native status, safe headers and entity bytes.
- /// The response body owns admission and the trusted context until completion/drop.
- ///
- /// # Errors
- /// Returns a sanitized error for invalid credentials, transport failures or a
- /// deadline before response headers arrive. Later failures terminate the body.
- pub async fn forward(
- &self,
- permit: RequestPermit,
- context: ResolvedRequestContext,
- headers: &HeaderMap,
- body: Bytes,
- ) -> Result<Response<Body>, ProviderError> {
- self.forward_route(permit, context, headers, body, OpenAiRoute::Responses)
- .await
- }
-
- pub(crate) async fn forward_route(
- &self,
- permit: RequestPermit,
- context: ResolvedRequestContext,
- headers: &HeaderMap,
- body: Bytes,
- route: OpenAiRoute,
- ) -> Result<Response<Body>, ProviderError> {
- let ProviderCredential::Bearer(token) = context.connection().credential() else {
- return Err(ProviderError::Configuration);
- };
- let mut authorization = HeaderValue::from_str(&format!("Bearer {token}"))
- .map_err(|_| ProviderError::Configuration)?;
- authorization.set_sensitive(true);
- let mut capture = if route.captures_generation() {
- let mut capture = ExecutionCapture::for_openai_responses(&context, headers, &body);
- if let Some(telemetry) = &self.telemetry {
- capture.deliver_to(telemetry.clone(), &context, headers);
- }
- capture
- } else {
- ExecutionCapture::unobserved()
- };
- let mut upstream = self
- .client
- .request(route.method(), self.request_url(route))
- .with_extension(DisableOtelPropagation)
- .headers(transport::request_headers(headers))
- // Observe plain JSON/SSE while relaying the provider bytes unchanged.
- .header(header::ACCEPT_ENCODING, "identity")
- .header(header::AUTHORIZATION, authorization);
- if route.captures_generation() {
- upstream = upstream.body(body);
- }
- let response = tokio::time::timeout_at(
- permit
- .deadline
- .min(Instant::now() + self.limits.headers_timeout),
- upstream.send(),
- )
- .await
- .map_err(|_| ProviderError::Timeout)
- .and_then(|result| {
- result.map_err(|error| {
- if error.is_timeout() {
- ProviderError::Timeout
- } else {
- ProviderError::Transport
- }
- })
- });
- let response = match response {
- Ok(response) => response,
- Err(error) => {
- capture.finish(if matches!(error, ProviderError::Timeout) {
- RelayOutcome::Timeout
- } else {
- RelayOutcome::TransportError
- });
- return Err(error);
- }
- };
- capture.record_response(response.status().as_u16(), response.headers());
- let mut downstream = Response::new(Body::empty());
- *downstream.status_mut() = response.status();
- *downstream.headers_mut() = transport::response_headers(response.headers());
- *downstream.body_mut() =
- transport::relay(response, permit.deadline, (permit, context), capture);
- Ok(downstream)
- }
-
- fn request_url(&self, route: OpenAiRoute) -> String {
- let base = self.base_url.trim_end_matches('/');
- let mut url = String::with_capacity(base.len() + route.path().len());
- url.push_str(base);
- url.push_str(route.path());
- url
- }
-
- #[cfg(test)]
- pub(crate) fn for_test(base_url: String, limits: ProviderLimits) -> Self {
- let mut provider = Self::with_limits(limits).unwrap();
- provider.base_url = base_url;
- provider
- }
-}
-
-#[cfg(test)]
-mod tests;
diff --git a/ai-gateway/src/providers/openai/tests.rs b/ai-gateway/src/providers/tests.rs
similarity index 73%
rename from ai-gateway/src/providers/openai/tests.rs
rename to ai-gateway/src/providers/tests.rs
index 854a9df365..dc7955f87e 100644
--- a/ai-gateway/src/providers/openai/tests.rs
+++ b/ai-gateway/src/providers/tests.rs
@@ -1,12 +1,15 @@
use super::*;
-use crate::test_support::{FakeServer, resolved_request_context};
-use axum::{body::to_bytes, http::StatusCode};
+use crate::test_support::{FakeServer, resolved_request_context, resolved_request_context_for};
+use axum::{
+ body::to_bytes,
+ http::{HeaderName, StatusCode},
+};
use futures_util::{StreamExt, stream};
use std::{convert::Infallible, future::pending};
use tokio::sync::Notify;
-fn provider(server: &FakeServer, active: usize) -> OpenAiProvider {
- OpenAiProvider::for_test(
+fn provider(server: &FakeServer, active: usize) -> ProviderTransport {
+ ProviderTransport::for_test(
format!("{}/v1", server.url),
ProviderLimits {
active,
@@ -304,7 +307,7 @@ async fn deadlines_bound_headers_and_stalled_bodies_without_exposing_transport_d
Response::new(Body::empty())
})
.await;
- let relay = OpenAiProvider::for_test(
+ let relay = ProviderTransport::for_test(
upstream.url.clone(),
ProviderLimits {
headers_timeout: Duration::from_millis(30),
@@ -324,7 +327,7 @@ async fn deadlines_bound_headers_and_stalled_bodies_without_exposing_transport_d
let dropped = Arc::new(Notify::new());
let upstream = stalled_provider(dropped.clone()).await;
- let relay = OpenAiProvider::for_test(
+ let relay = ProviderTransport::for_test(
upstream.url.clone(),
ProviderLimits {
execution_timeout: Duration::from_millis(100),
@@ -483,7 +486,7 @@ async fn cancelled_and_timed_out_executions_upload_after_provider_context_is_rel
Telemetry::new(&ControlPlaneConfig::new(&sink.url, "service-key").unwrap()).unwrap();
let dropped = Arc::new(Notify::new());
let upstream = stalled_provider(dropped).await;
- let relay = OpenAiProvider::for_test(
+ let relay = ProviderTransport::for_test(
upstream.url.clone(),
ProviderLimits {
active: 1,
@@ -601,7 +604,8 @@ async fn compact_posts_compact_path_and_models_get_skips_ingestion() {
resolved_request_context("provider-secret").await,
&HeaderMap::new(),
Bytes::from_static(COMPACT),
- OpenAiRoute::ResponsesCompact,
+ Route::OpenAiResponsesCompact,
+ None,
)
.await
.unwrap();
@@ -623,7 +627,8 @@ async fn compact_posts_compact_path_and_models_get_skips_ingestion() {
resolved_request_context("provider-secret").await,
&HeaderMap::new(),
Bytes::new(),
- OpenAiRoute::Models,
+ Route::OpenAiModels,
+ None,
)
.await
.unwrap();
@@ -711,3 +716,240 @@ fn assert_completed_upload(payload: &serde_json::Value, streaming: bool) {
assert!(!payload.to_string().contains(secret));
}
}
+
+fn transport(server: &FakeServer) -> ProviderTransport {
+ ProviderTransport::for_test(
+ format!("{}/v1", server.url),
+ ProviderLimits {
+ active: 1,
+ ..ProviderLimits::default()
+ },
+ )
+}
+
+/// Headers the gateway consumes for attribution or that belong to the client
+/// hop; none may reach the provider.
+const CONSUMED_HEADERS: &[(&str, &str)] = &[
+ ("x-claude-code-session-id", "session-1"),
+ ("x-claude-code-agent-id", "agent-1"),
+ ("cookie", "session=secret"),
+ ("langfuse-gateway-authorization", "service-signature"),
+ (
+ "traceparent",
+ "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
+ ),
+ ("baggage", "langfuse_user_id=private"),
+ ("langfuse-session-id", "private-session"),
+ ("x-forwarded-host", "attacker.example"),
+ ("x-stainless-retry-count", "0"),
+];
+
+fn headers(pairs: &[(&'static str, &'static str)]) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ for (name, value) in pairs {
+ headers.append(
+ HeaderName::from_static(name),
+ HeaderValue::from_static(value),
+ );
+ }
+ headers
+}
+
+#[tokio::test]
+async fn sends_the_x_api_key_credential_and_forwards_the_open_anthropic_header_family() {
+ const REQUEST: &[u8] = br#"{"model":"claude-sonnet-4-5","system":[{"type":"text","text":"attribution","cache_control":{"type":"ephemeral"}}],"future_field":true}"#;
+ let upstream = FakeServer::start(|request| async move {
+ assert_eq!(request.uri(), "/v1/messages");
+ assert_eq!(request.method(), "POST");
+ assert_eq!(request.headers()["x-api-key"], "provider-secret");
+ assert!(!request.headers().contains_key(header::AUTHORIZATION));
+ assert_eq!(request.headers()["anthropic-version"], "2023-06-01");
+ assert_eq!(
+ request.headers()["anthropic-beta"],
+ "interleaved-thinking-2025-05-14,context-1m-2025-08-07"
+ );
+ assert_eq!(request.headers()["anthropic-future-capability"], "on");
+ assert_eq!(request.headers()[header::ACCEPT_ENCODING], "identity");
+ for (name, _) in CONSUMED_HEADERS {
+ assert!(!request.headers().contains_key(*name), "forwarded {name}");
+ }
+ assert_eq!(to_bytes(request.into_body(), 1024).await.unwrap(), REQUEST);
+ Response::builder()
+ .status(StatusCode::OK)
+ .header("content-type", "application/json")
+ .header("request-id", "req_123")
+ .header("x-should-retry", "false")
+ .header("anthropic-ratelimit-unified-status", "allowed")
+ .header("anthropic-ratelimit-input-tokens-remaining", "1000")
+ .header("anthropic-organization-id", "org_456")
+ .header("retry-after", "7")
+ .header("set-cookie", "private-cookie")
+ .header("cf-ray", "edge-private")
+ .body(Body::from(r#"{"type":"message","content":[]}"#))
+ .unwrap()
+ })
+ .await;
+ let relay = transport(&upstream);
+ let context =
+ resolved_request_context_for(ApiFormat::AnthropicMessages, "provider-secret", "usage")
+ .await;
+ let response = relay
+ .forward_route(
+ relay.try_admit().unwrap(),
+ context,
+ &headers(
+ &[
+ &[
+ ("x-api-key", "gateway-secret"),
+ ("authorization", "Bearer gateway-secret"),
+ ("anthropic-version", "2023-06-01"),
+ (
+ "anthropic-beta",
+ "interleaved-thinking-2025-05-14,context-1m-2025-08-07",
+ ),
+ ("anthropic-future-capability", "on"),
+ ("content-type", "application/json"),
+ ("accept-encoding", "gzip"),
+ ],
+ CONSUMED_HEADERS,
+ ]
+ .concat(),
+ ),
+ Bytes::from_static(REQUEST),
+ Route::AnthropicMessages,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ let response_headers = response.headers().clone();
+ for (name, value) in [
+ ("request-id", "req_123"),
+ ("x-should-retry", "false"),
+ ("anthropic-ratelimit-unified-status", "allowed"),
+ ("anthropic-ratelimit-input-tokens-remaining", "1000"),
+ ("anthropic-organization-id", "org_456"),
+ ("retry-after", "7"),
+ ("content-type", "application/json"),
+ ] {
+ assert_eq!(response_headers[name], value, "missing {name}");
+ }
+ for name in ["set-cookie", "cf-ray"] {
+ assert!(!response_headers.contains_key(name), "retained {name}");
+ }
+ assert_eq!(
+ to_bytes(response.into_body(), 1024).await.unwrap(),
+ r#"{"type":"message","content":[]}"#
+ );
+ assert_eq!(upstream.calls(), 1);
+}
+
+#[tokio::test]
+async fn count_tokens_relays_the_body_and_models_forwards_only_pagination() {
+ let upstream = FakeServer::start(|request| async move {
+ let path = request.uri().path().to_owned();
+ let query = request.uri().query().map(str::to_owned);
+ match path.as_str() {
+ "/v1/messages/count_tokens" => {
+ assert_eq!(request.method(), "POST");
+ assert_eq!(query, None);
+ assert_eq!(
+ to_bytes(request.into_body(), 1024).await.unwrap(),
+ r#"{"model":"claude-sonnet-4-5","messages":[]}"#
+ );
+ Response::builder()
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"input_tokens":42}"#))
+ .unwrap()
+ }
+ "/v1/models" => {
+ assert_eq!(request.method(), "GET");
+ assert_eq!(query.as_deref(), Some("limit=1000&after_id=model_x"));
+ assert!(request.headers().get(header::CONTENT_LENGTH).is_none());
+ Response::builder()
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"data":[{"id":"claude-sonnet-4-5"}]}"#))
+ .unwrap()
+ }
+ other => panic!("unexpected upstream path {other}"),
+ }
+ })
+ .await;
+ let relay = transport(&upstream);
+ for (route, query, body, expected) in [
+ (
+ Route::AnthropicCountTokens,
+ Some("beta=true"),
+ r#"{"model":"claude-sonnet-4-5","messages":[]}"#,
+ r#"{"input_tokens":42}"#,
+ ),
+ (
+ Route::AnthropicModels,
+ Some("limit=1000&evil=1&after_id=model_x"),
+ "",
+ r#"{"data":[{"id":"claude-sonnet-4-5"}]}"#,
+ ),
+ ] {
+ let context =
+ resolved_request_context_for(ApiFormat::AnthropicMessages, "provider-secret", "usage")
+ .await;
+ let query = forwarded_query(route, query);
+ let response = relay
+ .forward_route(
+ relay.try_admit().unwrap(),
+ context,
+ &headers(&[("content-type", "application/json")]),
+ Bytes::from(body),
+ route,
+ query.as_deref(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ to_bytes(response.into_body(), 1024).await.unwrap(),
+ expected
+ );
+ }
+ assert_eq!(upstream.calls(), 2);
+}
+
+#[test]
+fn only_inference_routes_capture_generations_and_only_models_forwards_query() {
+ assert!(Route::AnthropicMessages.captures_generation());
+ assert!(!Route::AnthropicCountTokens.captures_generation());
+ assert!(!Route::AnthropicModels.captures_generation());
+ assert_eq!(
+ forwarded_query(Route::AnthropicMessages, Some("beta=true&limit=5")),
+ None
+ );
+ assert_eq!(
+ forwarded_query(
+ Route::AnthropicModels,
+ Some("before_id=a&limit=&evil&after_id=b%20c")
+ ),
+ Some("before_id=a&limit=&after_id=b%20c".to_owned())
+ );
+ assert_eq!(
+ forwarded_query(Route::AnthropicModels, Some("evil=1")),
+ None
+ );
+}
+
+#[test]
+fn openai_and_anthropic_admissions_draw_from_one_execution_budget() {
+ let relay = ProviderTransport::for_test(
+ "http://127.0.0.1:9".to_owned(),
+ ProviderLimits {
+ active: 1,
+ ..ProviderLimits::default()
+ },
+ );
+ let held = relay.try_admit().unwrap();
+ assert!(relay.try_admit().is_err());
+ drop(held);
+ let held = relay.try_admit().unwrap();
+ assert!(relay.try_admit().is_err());
+ drop(held);
+ assert!(relay.try_admit().is_ok());
+}
diff --git a/ai-gateway/src/telemetry/mapping.rs b/ai-gateway/src/telemetry/mapping.rs
index 7b7f46edc5..e2173b5834 100644
--- a/ai-gateway/src/telemetry/mapping.rs
+++ b/ai-gateway/src/telemetry/mapping.rs
@@ -36,7 +36,7 @@ pub(super) fn span(facts: InferenceFacts, context: &GenerationContext) -> Value
));
}
if let Some(usage) = inference.usage_details
- && let Some(projected) = openai_usage(&usage)
+ && let Some(projected) = usage_projection(facts.api_format, &usage)
{
attributes.push(attribute(
"langfuse.observation.usage_details",
@@ -200,6 +200,14 @@ fn attribute(key: &str, value: impl Into<String>) -> Value {
json!({"key": key, "value": {"stringValue": value.into()}})
}
+fn usage_projection(api_format: &str, usage: &Value) -> Option<Value> {
+ match api_format {
+ "openai.responses" => openai_usage(usage),
+ "anthropic.messages" => usage.is_object().then(|| usage.clone()),
+ _ => None,
+ }
+}
+
/// The receiver's native `OpenAI` usage schema is strict at the top level, but
/// accepts new numeric detail counters.
fn openai_usage(usage: &Value) -> Option<Value> {
@@ -505,6 +513,44 @@ mod tests {
assert!(metadata(&attrs).get("native_usage").is_none());
}
+ fn projected_usage(api_format: &'static str, usage: Value) -> Option<Value> {
+ let mut facts = facts();
+ facts.api_format = api_format;
+ facts.inference.usage_details = Some(usage);
+ let attrs = attributes(&span(facts, &context()));
+ attrs
+ .get("langfuse.observation.usage_details")
+ .map(|value| serde_json::from_str(value.as_str().unwrap()).unwrap())
+ }
+
+ #[test]
+ fn anthropic_usage_is_uploaded_as_native() {
+ let native = json!({
+ "input_tokens": 7, "output_tokens": 445,
+ "cache_creation_input_tokens": 2089, "cache_read_input_tokens": 16399,
+ "cache_creation": {"ephemeral_5m_input_tokens": 2000, "ephemeral_1h_input_tokens": 89},
+ "output_tokens_details": {"thinking_tokens": 300},
+ "server_tool_use": {"web_search_requests": 1},
+ "service_tier": "standard", "inference_geo": null
+ });
+ assert_eq!(
+ projected_usage("anthropic.messages", native.clone()),
+ Some(native)
+ );
+ assert_eq!(
+ projected_usage("anthropic.messages", json!({"input_tokens": 7})),
+ Some(json!({"input_tokens": 7}))
+ );
+ // The Anthropic shape never projects through the OpenAI rules.
+ assert_eq!(
+ projected_usage(
+ "openai.responses",
+ json!({"input_tokens": 7, "output_tokens": 1, "cache_read_input_tokens": 5})
+ ),
+ None
+ );
+ }
+
#[test]
fn provider_request_metadata_is_namespaced_and_keeps_native_types() {
let mut facts = facts();
diff --git a/ai-gateway/src/test_support.rs b/ai-gateway/src/test_support.rs
index 7191fbe02b..1e38c7b376 100644
--- a/ai-gateway/src/test_support.rs
+++ b/ai-gateway/src/test_support.rs
@@ -62,19 +62,30 @@ impl Drop for FakeServer {
}
}
-pub(crate) fn resolution_response(provider_token: &str) -> Response<Body> {
+pub(crate) fn resolution_response_for(
+ api_format: ApiFormat,
+ provider_secret: &str,
+) -> Response<Body> {
let expires_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
+ 300;
- let body = json!({
- "version": 1,
- "connection": {
+ let connection = match api_format {
+ ApiFormat::OpenAiResponses => json!({
"id": "connection-1", "provider": "openai", "api_format": "openai.responses",
"base_url": "https://api.openai.com/v1",
- "auth": {"type": "Bearer", "token": provider_token}
- },
+ "auth": {"type": "Bearer", "token": provider_secret}
+ }),
+ ApiFormat::AnthropicMessages => json!({
+ "id": "connection-1", "provider": "anthropic", "api_format": "anthropic.messages",
+ "base_url": "https://api.anthropic.com/v1",
+ "auth": {"type": "x-api-key", "header": "x-api-key", "value": provider_secret}
+ }),
+ };
+ let body = json!({
+ "version": 1,
+ "connection": connection,
"attribution": {
"organization_id": "org-1", "project_id": "project-1", "key_id": "key-1", "key_metadata": {},
"provider_connection_id": "provider-connection-1"
@@ -88,6 +99,10 @@ pub(crate) fn resolution_response(provider_token: &str) -> Response<Body> {
.unwrap()
}
+pub(crate) fn resolution_response(provider_token: &str) -> Response<Body> {
+ resolution_response_for(ApiFormat::OpenAiResponses, provider_token)
+}
+
pub(crate) async fn resolved_request_context(provider_token: &str) -> ResolvedRequestContext {
resolved_request_context_with_mode(provider_token, "usage").await
}
@@ -96,13 +111,24 @@ pub(crate) async fn resolved_request_context_with_mode(
provider_token: &str,
mode: &'static str,
) -> ResolvedRequestContext {
- let token = provider_token.to_owned();
+ resolved_request_context_for(ApiFormat::OpenAiResponses, provider_token, mode).await
+}
+
+pub(crate) async fn resolved_request_context_for(
+ api_format: ApiFormat,
+ provider_secret: &str,
+ mode: &'static str,
+) -> ResolvedRequestContext {
+ let secret = provider_secret.to_owned();
let web = FakeServer::start(move |_| {
- let token = token.clone();
+ let secret = secret.clone();
async move {
- let bytes = axum::body::to_bytes(resolution_response(&token).into_body(), 4096)
- .await
- .unwrap();
+ let bytes = axum::body::to_bytes(
+ resolution_response_for(api_format, &secret).into_body(),
+ 4096,
+ )
+ .await
+ .unwrap();
let mut body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
body["ingestion_mode"] = mode.into();
Response::builder()
@@ -113,7 +139,7 @@ pub(crate) async fn resolved_request_context_with_mode(
})
.await;
web.control_plane()
- .resolve("gateway-secret", ApiFormat::OpenAiResponses)
+ .resolve("gateway-secret", api_format)
.await
.unwrap()
}
diff --git a/ai-gateway/src/transport/mod.rs b/ai-gateway/src/transport/mod.rs
index 6551c55bfd..8665f71a20 100644
--- a/ai-gateway/src/transport/mod.rs
+++ b/ai-gateway/src/transport/mod.rs
@@ -9,7 +9,10 @@ use std::{
task::{Context, Poll},
};
-use crate::capture::{ExecutionCapture, RelayOutcome};
+use crate::{
+ capture::{ExecutionCapture, RelayOutcome},
+ resolution::ApiFormat,
+};
use axum::{
body::{Body, Bytes},
http::{HeaderMap, header},
@@ -44,48 +47,79 @@ impl std::error::Error for ProviderError {}
// An allowlist prevents gateway credentials, tenant routing overrides and cookies
// from crossing the boundary. Headers nominated by `Connection` are never end-to-end.
-fn selected_headers(source: &HeaderMap, allowed: &[&'static str]) -> HeaderMap {
- let mut selected = HeaderMap::new();
- for &name in allowed {
- let hop_by_hop = source.get_all(header::CONNECTION).iter().any(|value| {
+// Prefixes admit a provider's own evolving header family without naming each member.
+fn selected_headers(source: &HeaderMap, allowed: &[&str], prefixes: &[&str]) -> HeaderMap {
+ let hop_by_hop = |name: &str| {
+ source.get_all(header::CONNECTION).iter().any(|value| {
value.to_str().map_or(true, |value| {
value
.split(',')
.any(|token| token.trim().eq_ignore_ascii_case(name))
})
- });
- if !hop_by_hop {
- for value in source.get_all(name) {
- selected.append(header::HeaderName::from_static(name), value.clone());
- }
+ })
+ };
+ let mut selected = HeaderMap::new();
+ for (name, value) in source {
+ let admitted = allowed.contains(&name.as_str())
+ || prefixes
+ .iter()
+ .any(|prefix| name.as_str().starts_with(prefix));
+ if admitted && !hop_by_hop(name.as_str()) {
+ selected.append(name.clone(), value.clone());
}
}
selected
}
-pub(crate) fn request_headers(source: &HeaderMap) -> HeaderMap {
- selected_headers(source, &["content-type", "content-encoding", "accept"])
+const COMMON_REQUEST_HEADERS: &[&str] = &["content-type", "content-encoding", "accept"];
+
+const COMMON_RESPONSE_HEADERS: &[&str] = &[
+ "content-type",
+ "content-encoding",
+ "cache-control",
+ "retry-after",
+];
+
+pub(crate) fn request_headers(source: &HeaderMap, api_format: ApiFormat) -> HeaderMap {
+ match api_format {
+ ApiFormat::OpenAiResponses => selected_headers(source, COMMON_REQUEST_HEADERS, &[]),
+ ApiFormat::AnthropicMessages => {
+ selected_headers(source, COMMON_REQUEST_HEADERS, &["anthropic-"])
+ }
+ }
}
-pub(crate) fn response_headers(source: &HeaderMap) -> HeaderMap {
- selected_headers(
- source,
- &[
- "content-type",
- "content-encoding",
- "cache-control",
- "retry-after",
- "x-request-id",
- "openai-processing-ms",
- "openai-version",
- "x-ratelimit-limit-requests",
- "x-ratelimit-limit-tokens",
- "x-ratelimit-remaining-requests",
- "x-ratelimit-remaining-tokens",
- "x-ratelimit-reset-requests",
- "x-ratelimit-reset-tokens",
- ],
- )
+pub(crate) fn response_headers(source: &HeaderMap, api_format: ApiFormat) -> HeaderMap {
+ match api_format {
+ ApiFormat::OpenAiResponses => selected_headers(
+ source,
+ &[
+ COMMON_RESPONSE_HEADERS,
+ &[
+ "x-request-id",
+ "openai-processing-ms",
+ "openai-version",
+ "x-ratelimit-limit-requests",
+ "x-ratelimit-limit-tokens",
+ "x-ratelimit-remaining-requests",
+ "x-ratelimit-remaining-tokens",
+ "x-ratelimit-reset-requests",
+ "x-ratelimit-reset-tokens",
+ ],
+ ]
+ .concat(),
+ &[],
+ ),
+ ApiFormat::AnthropicMessages => selected_headers(
+ source,
+ &[
+ COMMON_RESPONSE_HEADERS,
+ &["request-id", "x-should-retry", "anthropic-organization-id"],
+ ]
+ .concat(),
+ &["anthropic-ratelimit-"],
+ ),
+ }
}
pub(crate) fn relay<T: Send + 'static>(