From 41837f8d82147efbc37d956ea1e94f94681088e2 Mon Sep 17 00:00:00 2001 From: tree-zby <1454192575@qq.com> Date: Fri, 27 Nov 2026 12:04:54 +0800 Subject: [PATCH] feat(api): allow hosts to add outbound headers to model requests (#3407) Adds an optional per-client ExtraHeadersHook. Hosts that need routing, quota or cache-affinity metadata can install it with with_extra_headers_provider on AnthropicClient, OpenAiCompatClient or ProviderClient; headers are applied inside send_raw_request after the JSON body is built. There is no global state and no behaviour change when no provider is installed. count_tokens does not go through send_raw_request, so it stays unannotated. Transport-owned headers and malformed names/values are dropped, so a broken hook cannot rewrite credentials or fail a call. Co-authored-by: tree-zby <203675912+tree-zby@users.noreply.github.com> --- rust/crates/api/src/client.rs | 16 ++ rust/crates/api/src/extra_headers.rs | 150 ++++++++++++++++++ rust/crates/api/src/lib.rs | 2 + rust/crates/api/src/providers/anthropic.rs | 83 +++++++++- .../crates/api/src/providers/openai_compat.rs | 93 +++++++++-- 5 files changed, 333 insertions(+), 11 deletions(-) create mode 100644 rust/crates/api/src/extra_headers.rs diff --git a/rust/crates/api/src/client.rs b/rust/crates/api/src/client.rs index 3688179b..16edeafd 100644 --- a/rust/crates/api/src/client.rs +++ b/rust/crates/api/src/client.rs @@ -1,4 +1,5 @@ use crate::error::ApiError; +use crate::extra_headers::ExtraHeadersHook; use crate::prompt_cache::{PromptCache, PromptCacheRecord, PromptCacheStats}; use crate::providers::anthropic::{self, AnthropicClient, AuthSource}; use crate::providers::openai_compat::{self, OpenAiCompatClient, OpenAiCompatConfig}; @@ -200,6 +201,21 @@ impl ProviderClient { } } + /// Install a provider that may add outbound headers to each model request. + /// + /// Applies to every provider variant. Without a provider the request is + /// unchanged. + #[must_use] + pub fn with_extra_headers_provider(self, provider: ExtraHeadersHook) -> Self { + match self { + Self::Anthropic(client) => { + Self::Anthropic(client.with_extra_headers_provider(provider)) + } + Self::Xai(client) => Self::Xai(client.with_extra_headers_provider(provider)), + Self::OpenAi(client) => Self::OpenAi(client.with_extra_headers_provider(provider)), + } + } + #[must_use] pub fn prompt_cache_stats(&self) -> Option { match self { diff --git a/rust/crates/api/src/extra_headers.rs b/rust/crates/api/src/extra_headers.rs new file mode 100644 index 00000000..f9ebd166 --- /dev/null +++ b/rust/crates/api/src/extra_headers.rs @@ -0,0 +1,150 @@ +//! Optional outbound HTTP header provider for model requests. +//! +//! Some hosts must annotate each model request with routing, quota, or +//! cache-affinity metadata that only the caller can compute. A client opts in +//! with [`crate::providers::anthropic::AnthropicClient::with_extra_headers_provider`] +//! or [`crate::providers::openai_compat::OpenAiCompatClient::with_extra_headers_provider`]; +//! clients without a provider send byte-for-byte the same headers as before. +//! +//! The provider runs in-process and receives the exact JSON body that is about +//! to be sent. It must treat the body as read-only: the hook can only add +//! headers, never change the payload. + +use std::fmt; +use std::sync::Arc; + +use reqwest::header::{HeaderName, HeaderValue}; +use reqwest::RequestBuilder; +use serde_json::Value; + +/// Facts the host may use when deriving headers. +pub struct ExtraHeadersContext<'a> { + /// Provider label reported by the client (`"Anthropic"`, `"OpenAI"`, ...). + pub provider: &'a str, + /// Model id as it appears in the request body. + pub model: &'a str, + /// The JSON body that will be sent with this request. Read-only. + pub body: &'a Value, +} + +/// Returns `(name, value)` pairs to add to one outbound request. +pub type ExtraHeadersProvider = + dyn Fn(&ExtraHeadersContext<'_>) -> Vec<(String, String)> + Send + Sync; + +/// Headers owned by the transport. A provider cannot override them. +const RESERVED_HEADERS: &[&str] = &[ + "accept", + "accept-encoding", + "anthropic-beta", + "anthropic-version", + "authorization", + "connection", + "content-length", + "content-type", + "host", + "transfer-encoding", + "user-agent", + "x-api-key", +]; + +/// A header provider attached to one client. +/// +/// Cloning a client shares the provider; the closure must be `Send + Sync`. +#[derive(Clone)] +pub struct ExtraHeadersHook { + provider: Arc, +} + +impl ExtraHeadersHook { + #[must_use] + pub fn new( + provider: impl Fn(&ExtraHeadersContext<'_>) -> Vec<(String, String)> + Send + Sync + 'static, + ) -> Self { + Self { + provider: Arc::new(provider), + } + } + + /// Adds the provider's headers to one outbound model request. + /// + /// Invalid names or values, and headers the transport owns, are dropped: a + /// broken provider must never fail a model call or rewrite credentials. + pub fn apply( + &self, + mut builder: RequestBuilder, + context: &ExtraHeadersContext<'_>, + ) -> RequestBuilder { + for (name, value) in (self.provider)(context) { + let Ok(name) = HeaderName::from_bytes(name.as_bytes()) else { + continue; + }; + if RESERVED_HEADERS.contains(&name.as_str()) { + continue; + } + let Ok(value) = HeaderValue::from_str(&value) else { + continue; + }; + builder = builder.header(name, value); + } + builder + } +} + +impl fmt::Debug for ExtraHeadersHook { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ExtraHeadersHook").finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn context<'a>(body: &'a Value) -> ExtraHeadersContext<'a> { + ExtraHeadersContext { + provider: "Anthropic", + model: "claude-sonnet-4", + body, + } + } + + #[test] + fn apply_keeps_valid_headers_and_drops_the_rest() { + let body = json!({"messages": []}); + let hook = ExtraHeadersHook::new(|ctx: &ExtraHeadersContext<'_>| { + vec![ + ( + "x-route".to_string(), + format!("{}/{}", ctx.provider, ctx.model), + ), + ("authorization".to_string(), "Bearer nope".to_string()), + ("anthropic-version".to_string(), "2099-01-01".to_string()), + ("anthropic-beta".to_string(), "none".to_string()), + ("bad header".to_string(), "dropped".to_string()), + ("x-blank".to_string(), "bad\r\nvalue".to_string()), + ] + }); + + let request = hook + .apply( + reqwest::Client::new().post("http://127.0.0.1/"), + &context(&body), + ) + .build() + .expect("request builds"); + + assert_eq!( + request + .headers() + .get("x-route") + .and_then(|value| value.to_str().ok()), + Some("Anthropic/claude-sonnet-4") + ); + assert!(request.headers().get("authorization").is_none()); + assert!(request.headers().get("anthropic-version").is_none()); + assert!(request.headers().get("anthropic-beta").is_none()); + assert!(request.headers().get("bad header").is_none()); + assert!(request.headers().get("x-blank").is_none()); + } +} diff --git a/rust/crates/api/src/lib.rs b/rust/crates/api/src/lib.rs index aa59bdb5..a10b236c 100644 --- a/rust/crates/api/src/lib.rs +++ b/rust/crates/api/src/lib.rs @@ -1,6 +1,7 @@ mod client; mod error; +mod extra_headers; mod http_client; mod prompt_cache; mod providers; @@ -13,6 +14,7 @@ pub use client::{ ProviderConfigKind, }; pub use error::ApiError; +pub use extra_headers::{ExtraHeadersContext, ExtraHeadersHook, ExtraHeadersProvider}; pub use http_client::{ build_http_client, build_http_client_or_default, build_http_client_with, build_http_client_with_opts, ProxyConfig, TimeoutConfig, diff --git a/rust/crates/api/src/providers/anthropic.rs b/rust/crates/api/src/providers/anthropic.rs index 403cbf55..399341ae 100644 --- a/rust/crates/api/src/providers/anthropic.rs +++ b/rust/crates/api/src/providers/anthropic.rs @@ -13,6 +13,7 @@ use serde_json::{Map, Value}; use telemetry::{AnalyticsEvent, AnthropicRequestProfile, ClientIdentity, SessionTracer}; use crate::error::ApiError; +use crate::extra_headers::{ExtraHeadersContext, ExtraHeadersHook}; use crate::http_client::build_http_client_or_default; use crate::prompt_cache::{PromptCache, PromptCacheRecord, PromptCacheStats}; @@ -121,6 +122,7 @@ pub struct AnthropicClient { request_profile: AnthropicRequestProfile, session_tracer: Option, prompt_cache: Option, + extra_headers: Option, last_prompt_cache_record: Arc>>, } @@ -137,6 +139,7 @@ impl AnthropicClient { request_profile: AnthropicRequestProfile::default(), session_tracer: None, prompt_cache: None, + extra_headers: None, last_prompt_cache_record: Arc::new(Mutex::new(None)), } } @@ -153,6 +156,7 @@ impl AnthropicClient { request_profile: AnthropicRequestProfile::default(), session_tracer: None, prompt_cache: None, + extra_headers: None, last_prompt_cache_record: Arc::new(Mutex::new(None)), } } @@ -254,6 +258,16 @@ impl AnthropicClient { self } + /// Install a provider that may add outbound headers to each model request. + /// + /// The provider sees the final JSON body and can only add headers. Only + /// real model requests reach it: `count_tokens` does not. + #[must_use] + pub fn with_extra_headers_provider(mut self, provider: ExtraHeadersHook) -> Self { + self.extra_headers = Some(provider); + self + } + #[must_use] pub fn prompt_cache_stats(&self) -> Option { self.prompt_cache.as_ref().map(PromptCache::stats) @@ -488,7 +502,17 @@ impl AnthropicClient { ) -> Result { let request_url = format!("{}/v1/messages", self.base_url.trim_end_matches('/')); let request_body = render_standard_messages_body(&self.request_profile, request)?; - let request_builder = self.build_request(&request_url).json(&request_body); + let mut request_builder = self.build_request(&request_url).json(&request_body); + if let Some(extra_headers) = &self.extra_headers { + request_builder = extra_headers.apply( + request_builder, + &ExtraHeadersContext { + provider: "Anthropic", + model: &request.model, + body: &request_body, + }, + ); + } request_builder.send().await.map_err(ApiError::from) } @@ -1098,7 +1122,8 @@ mod tests { now_unix_timestamp, oauth_token_is_expired, resolve_saved_oauth_token, resolve_startup_auth_source, AnthropicClient, AuthSource, OAuthTokenSet, }; - use crate::types::{ContentBlockDelta, MessageRequest}; + use crate::extra_headers::ExtraHeadersHook; + use crate::types::{ContentBlockDelta, InputMessage, MessageRequest}; fn temp_config_home() -> std::path::PathBuf { std::env::temp_dir().join(format!( @@ -1891,4 +1916,58 @@ mod tests { crate::error::ApiError::InvalidSseFrame(_) )); } + + #[tokio::test] + async fn extra_headers_provider_annotates_the_wire_request() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().expect("local addr"); + let (request_tx, request_rx) = std::sync::mpsc::channel(); + thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept connection"); + let mut buffer = [0_u8; 8192]; + let read = stream.read(&mut buffer).expect("read request"); + request_tx + .send(String::from_utf8_lossy(&buffer[..read]).into_owned()) + .expect("send request"); + let body = r#"{"id":"msg_test","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}"#; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}", + body.len(), + body + ); + stream + .write_all(response.as_bytes()) + .expect("write response"); + }); + + let client = AnthropicClient::new("test-key") + .with_base_url(format!("http://{address}")) + .with_extra_headers_provider(ExtraHeadersHook::new( + |ctx: &crate::extra_headers::ExtraHeadersContext<'_>| { + vec![( + "x-route".to_string(), + format!("{}/{}", ctx.provider, ctx.model), + )] + }, + )); + let request = MessageRequest { + model: "claude-sonnet-4".to_string(), + max_tokens: 16, + messages: vec![InputMessage::user_text("hello")], + ..Default::default() + }; + + let response = client.send_raw_request(&request).await.expect("response"); + assert_eq!(response.status(), reqwest::StatusCode::OK); + + let captured = request_rx + .recv_timeout(Duration::from_secs(5)) + .expect("captured request"); + assert!( + captured + .to_lowercase() + .contains("x-route: anthropic/claude-sonnet-4"), + "wire request must carry the provider header: {captured}" + ); + } } diff --git a/rust/crates/api/src/providers/openai_compat.rs b/rust/crates/api/src/providers/openai_compat.rs index e40a94ec..d155309e 100644 --- a/rust/crates/api/src/providers/openai_compat.rs +++ b/rust/crates/api/src/providers/openai_compat.rs @@ -8,6 +8,7 @@ use serde::Deserialize; use serde_json::{json, Value}; use crate::error::ApiError; +use crate::extra_headers::{ExtraHeadersContext, ExtraHeadersHook}; use crate::http_client::build_http_client_or_default; use crate::types::{ ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent, @@ -129,6 +130,7 @@ pub struct OpenAiCompatClient { max_retries: u32, initial_backoff: Duration, max_backoff: Duration, + extra_headers: Option, } impl OpenAiCompatClient { @@ -150,6 +152,7 @@ impl OpenAiCompatClient { max_retries: DEFAULT_MAX_RETRIES, initial_backoff: DEFAULT_INITIAL_BACKOFF, max_backoff: DEFAULT_MAX_BACKOFF, + extra_headers: None, } } @@ -185,6 +188,7 @@ impl OpenAiCompatClient { max_retries: DEFAULT_MAX_RETRIES, initial_backoff: DEFAULT_INITIAL_BACKOFF, max_backoff: DEFAULT_MAX_BACKOFF, + extra_headers: None, }) } @@ -225,6 +229,15 @@ impl OpenAiCompatClient { self } + /// Install a provider that may add outbound headers to each model request. + /// + /// The provider sees the final JSON body and can only add headers. + #[must_use] + pub fn with_extra_headers_provider(mut self, provider: ExtraHeadersHook) -> Self { + self.extra_headers = Some(provider); + self + } + pub async fn send_message( &self, request: &MessageRequest, @@ -353,18 +366,25 @@ impl OpenAiCompatClient { check_request_body_size_for_base_url(request, self.config(), &self.base_url)?; let request_url = chat_completions_endpoint(&self.base_url); - self.http + let request_body = + build_chat_completion_request_for_base_url(request, self.config(), &self.base_url); + let mut request_builder = self + .http .post(&request_url) .header("content-type", "application/json") .bearer_auth(&self.api_key) - .json(&build_chat_completion_request_for_base_url( - request, - self.config(), - &self.base_url, - )) - .send() - .await - .map_err(ApiError::from) + .json(&request_body); + if let Some(extra_headers) = &self.extra_headers { + request_builder = extra_headers.apply( + request_builder, + &ExtraHeadersContext { + provider: self.config.provider_name, + model: &request.model, + body: &request_body, + }, + ); + } + request_builder.send().await.map_err(ApiError::from) } fn backoff_for_attempt(&self, attempt: u32) -> Result { @@ -1866,6 +1886,7 @@ mod tests { OpenAiCompatClient, OpenAiCompatConfig, StreamState, }; use crate::error::ApiError; + use crate::extra_headers::ExtraHeadersHook; use crate::test_env_lock as env_lock; use crate::types::{ ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent, @@ -3142,4 +3163,58 @@ mod tests { assert_eq!(super::strip_routing_prefix("kimi-k2.5"), "kimi-k2.5"); // no prefix, unchanged assert_eq!(super::strip_routing_prefix("kimi/kimi-k1.5"), "kimi-k1.5"); } + + #[tokio::test] + async fn extra_headers_provider_annotates_the_wire_request() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().expect("local addr"); + let (request_tx, request_rx) = std::sync::mpsc::channel(); + thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept connection"); + let mut buffer = [0_u8; 8192]; + let read = stream.read(&mut buffer).expect("read request"); + request_tx + .send(String::from_utf8_lossy(&buffer[..read]).into_owned()) + .expect("send request"); + let body = r#"{"id":"chatcmpl-test","object":"chat.completion","created":0,"model":"gpt-4o-mini","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}"#; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}", + body.len(), + body + ); + stream + .write_all(response.as_bytes()) + .expect("write response"); + }); + + let client = OpenAiCompatClient::new("test-key", OpenAiCompatConfig::openai()) + .with_base_url(format!("http://{address}")) + .with_extra_headers_provider(ExtraHeadersHook::new( + |ctx: &crate::extra_headers::ExtraHeadersContext<'_>| { + vec![( + "x-route".to_string(), + format!("{}/{}", ctx.provider, ctx.model), + )] + }, + )); + let request = MessageRequest { + model: "gpt-4o-mini".to_string(), + max_tokens: 16, + messages: vec![InputMessage::user_text("hello")], + ..Default::default() + }; + + let response = client.send_raw_request(&request).await.expect("response"); + assert_eq!(response.status(), reqwest::StatusCode::OK); + + let captured = request_rx + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("captured request"); + assert!( + captured + .to_lowercase() + .contains("x-route: openai/gpt-4o-mini"), + "wire request must carry the provider header: {captured}" + ); + } }