diff --git a/README.md b/README.md index 869d32cf9..1fe97eccb 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ > [!NOTE] -> 原生生成支持 [OpenAI Responses](docs/api.md#responses-请求与传输)、[Anthropic Messages](docs/api.md#messages-请求) 和 [GenAI](docs/api.md#antigravity-客户端原生生成);[Chat Completions](docs/api.md#chat-completions-请求) 直接转换到所选账号协议,其他跨协议转换不内置 +> 支持 OpenAI(Codex)、xAI(Grok)和 Google Antigravity 账号,以及兼容 OpenAI Responses 或 Anthropic Messages 的 API Key 服务,详见[账号接入](docs/api.md#账号能力导入与-oauth) ## 快速预览 diff --git a/backend/crates/gateway-api/src/client_error.rs b/backend/crates/gateway-api/src/client_error.rs index 03a358595..bce2788bc 100644 --- a/backend/crates/gateway-api/src/client_error.rs +++ b/backend/crates/gateway-api/src/client_error.rs @@ -118,13 +118,16 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option { /// Gateway 错误的 OpenAI HTTP 表达 pub fn gateway_error_response(error: &GatewayError) -> Response { let (status, default_type, default_code) = gateway_error_contract(error.kind()); - let mut response = openai_error_response( + let (status, Json(mut body)) = openai_error_response( status, error.client_message(), error.client_error_type().unwrap_or(default_type), error.client_error_code().unwrap_or(default_code), - ) - .into_response(); + ); + if let Some(parameter) = error.client_error_parameter() { + body["error"]["param"] = parameter.into(); + } + let mut response = (status, Json(body)).into_response(); response.extensions_mut().insert(error.clone()); if let Some(delay) = error.retry_after() && let Ok(value) = HeaderValue::from_str( diff --git a/backend/crates/gateway-api/src/data_plane/body.rs b/backend/crates/gateway-api/src/data_plane/body.rs index 8239d2f05..b322ba0d1 100644 --- a/backend/crates/gateway-api/src/data_plane/body.rs +++ b/backend/crates/gateway-api/src/data_plane/body.rs @@ -8,6 +8,9 @@ use thiserror::Error; /// 请求解码错误 #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum RequestDecodeError { + /// Chat 的入口校验与目标转换复用同一错误合同 + #[error(transparent)] + Chat(#[from] gateway_protocol::chat_completions::ChatError), /// 请求不是合法 JSON #[error("request body must be valid JSON")] MalformedJson, @@ -52,12 +55,6 @@ pub enum RequestDecodeError { /// 字段路径;不保存原始值 field: String, }, - /// 未知字段 - #[error("unknown field `{field}`")] - UnknownField { - /// 字段路径;不保存字段值 - field: String, - }, /// 已知但尚未实现的语义 #[error("field `{field}` is not supported by this gateway")] UnsupportedField { @@ -85,6 +82,11 @@ impl RequestDecodeError { #[must_use] pub fn protocol_body(&self) -> ProtocolErrorBody { let (code, message, param) = match self { + Self::Chat(error) => ( + error.code(), + error.to_string(), + error.parameter().map(str::to_owned), + ), Self::MalformedJson => ( "invalid_json", "Request body must be valid JSON.".to_owned(), @@ -127,11 +129,6 @@ impl RequestDecodeError { format!("Parameter `{field}` has an invalid value."), Some(field.clone()), ), - Self::UnknownField { field } => ( - "unknown_parameter", - format!("Unknown parameter `{field}`."), - Some(field.clone()), - ), Self::UnsupportedField { field } => ( "unsupported_parameter", format!("Parameter `{field}` is not supported by this gateway."), diff --git a/backend/crates/gateway-api/src/data_plane/chat_completions/http.rs b/backend/crates/gateway-api/src/data_plane/chat_completions/http.rs index 84928ce44..3b525fc77 100644 --- a/backend/crates/gateway-api/src/data_plane/chat_completions/http.rs +++ b/backend/crates/gateway-api/src/data_plane/chat_completions/http.rs @@ -78,15 +78,13 @@ pub(in crate::data_plane) fn decode_request( maximum: usize, ) -> Result { let body = decompress_request_body(body, headers, maximum)?; - let parsed = chat_completions::parse_request(&body).map_err(decode_error)?; + let parsed = chat_completions::parse_request(&body)?; let model = parsed - .body .get("model") .and_then(serde_json::Value::as_str) .unwrap_or_default() .to_owned(); let stream = parsed - .body .get("stream") .and_then(serde_json::Value::as_bool) .unwrap_or(false); @@ -107,27 +105,3 @@ pub(in crate::data_plane) fn decode_request( }, }) } - -fn decode_error(error: chat_completions::ChatError) -> RequestDecodeError { - use chat_completions::ChatError; - match error { - ChatError::MalformedJson => RequestDecodeError::MalformedJson, - ChatError::ExpectedObject => RequestDecodeError::ExpectedObject, - ChatError::MissingField { field } => RequestDecodeError::MissingField { field }, - ChatError::InvalidType { field, expected } => { - RequestDecodeError::InvalidType { field, expected } - } - ChatError::EmptyField { field } => RequestDecodeError::EmptyField { field }, - ChatError::InvalidValue { field } => RequestDecodeError::InvalidValue { field }, - ChatError::UnknownField { field } => RequestDecodeError::UnknownField { field }, - ChatError::UnsupportedField { field } => RequestDecodeError::UnsupportedField { field }, - ChatError::UnsupportedCombination { field, other } => { - RequestDecodeError::UnsupportedCombination { field, other } - } - ChatError::InvalidResponse | ChatError::IncompleteStream => { - RequestDecodeError::CanonicalContract { - field: "chat request".to_owned(), - } - } - } -} diff --git a/backend/crates/gateway-api/tests/data_plane/error.rs b/backend/crates/gateway-api/tests/data_plane/error.rs index 3ac174708..e18283c8a 100644 --- a/backend/crates/gateway-api/tests/data_plane/error.rs +++ b/backend/crates/gateway-api/tests/data_plane/error.rs @@ -887,3 +887,30 @@ fn final_connection_failures_and_local_capacity_have_distinct_http_statuses() { ); } } + +#[tokio::test] +async fn local_request_details_survive_execution_without_exposing_the_diagnostic_source() { + for with_details in [false, true] { + let mut provider = + ProviderError::invalid_request("The parameter is not supported by this upstream.") + .with_source(std::io::Error::other("PRIVATE_REQUEST_CONTENT")); + if with_details { + provider = provider + .with_request_details("unsupported_parameter", Some("tools[0].custom.format")); + } + let error = EngineError::Provider(provider.stable_snapshot()); + let response = engine_error_response(&error); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["error"]["type"], "invalid_request_error"); + if with_details { + assert_eq!(body["error"]["code"], "unsupported_parameter"); + assert_eq!(body["error"]["param"], "tools[0].custom.format"); + } else { + assert_eq!(body["error"]["code"], "invalid_request"); + assert!(body["error"].get("param").is_none()); + } + assert!(!String::from_utf8_lossy(&bytes).contains("PRIVATE_REQUEST_CONTENT")); + } +} diff --git a/backend/crates/gateway-core/src/error/mod.rs b/backend/crates/gateway-core/src/error/mod.rs index 8e634f3d3..a70830814 100644 --- a/backend/crates/gateway-core/src/error/mod.rs +++ b/backend/crates/gateway-core/src/error/mod.rs @@ -553,11 +553,19 @@ struct ProviderErrorUpstreamValues { #[derive(Clone, Default)] struct ProviderErrorFailureObservation { invalid_request_message: Option<&'static str>, + invalid_request_details: Option, unreachable_proxy: Option, continuation_unavailable_reason: Option<&'static str>, connection: Option, } +/// 本地校验显式提供的协议字段,不从任意错误来源或请求值反推 +#[derive(Clone)] +struct RequestErrorDetails { + code: &'static str, + parameter: Option, +} + #[derive(Clone)] struct AtomicClientEvents(Vec); @@ -603,6 +611,16 @@ impl ProviderError { error } + /// 附加本地请求校验的安全机器码与协议字段路径,禁止传入字段值 + #[must_use] + pub fn with_request_details(mut self, code: &'static str, parameter: Option<&str>) -> Self { + self.failure_observation_mut().invalid_request_details = Some(RequestErrorDetails { + code, + parameter: parameter.map(str::to_owned), + }); + self + } + /// 当前上游无法解析 Responses 历史,仅客户端持有完整输入可重放 #[must_use] pub fn responses_replay_required(reason: &'static str, send_state: UpstreamSendState) -> Self { @@ -1330,6 +1348,7 @@ pub struct GatewayError { #[derive(Debug, Clone, Default, PartialEq, Eq)] struct GatewayClientErrorDetails { code: Option<&'static str>, + parameter: Option, retry_after: Option, } @@ -1467,6 +1486,17 @@ impl GatewayError { "Upstream service is unavailable.", ), }; + let mut gateway = gateway; + if gateway.kind() == GatewayErrorKind::InvalidRequest + && let Some(details) = error + .failure_observation + .as_ref() + .and_then(|observation| observation.invalid_request_details.as_ref()) + { + let client = gateway.client_details.get_or_insert_with(Default::default); + client.code = Some(details.code); + client.parameter.clone_from(&details.parameter); + } let gateway = match error.diagnostic() { Some(diagnostic) => gateway.with_diagnostic(diagnostic.clone()), None => gateway, @@ -1538,6 +1568,14 @@ impl GatewayError { .and_then(|details| details.code) }) } + + /// 返回本地校验明确标注的协议字段路径,不包含请求值 + #[must_use] + pub fn client_error_parameter(&self) -> Option<&str> { + self.client_details + .as_ref() + .and_then(|details| details.parameter.as_deref()) + } } impl fmt::Debug for GatewayError { diff --git a/backend/crates/gateway-protocol/src/chat_completions/error.rs b/backend/crates/gateway-protocol/src/chat_completions/error.rs index a395c5b8f..450e82090 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/error.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/error.rs @@ -20,8 +20,6 @@ pub enum ChatError { EmptyField { field: String }, #[error("Parameter `{field}` has an invalid value.")] InvalidValue { field: String }, - #[error("Unknown parameter `{field}`.")] - UnknownField { field: String }, #[error("Parameter `{field}` is not supported by this upstream.")] UnsupportedField { field: String }, #[error("The requested `{field}` is not supported with `{other}`.")] @@ -36,6 +34,26 @@ pub enum ChatError { } impl ChatError { + /// Provider 保留静态分类提示,字段路径通过独立合同交付,不展开内部错误来源 + pub const fn safe_message(&self) -> &'static str { + match self { + Self::MalformedJson => "Request body must be valid JSON.", + Self::ExpectedObject => "Request body must be a JSON object.", + Self::MissingField { .. } => "A required parameter is missing.", + Self::InvalidType { .. } => "The parameter has an invalid type.", + Self::EmptyField { .. } => "The parameter must not be empty.", + Self::InvalidValue { .. } => "The parameter has an invalid value.", + Self::UnsupportedField { .. } => "The parameter is not supported by this upstream.", + Self::UnsupportedCombination { .. } => { + "The requested parameter combination is not supported." + } + Self::InvalidResponse => { + "The upstream response cannot be represented as a Chat completion." + } + Self::IncompleteStream => "The upstream stream ended before its terminal event.", + } + } + /// 供 API 出口构造稳定的机器码 pub const fn code(&self) -> &'static str { match self { @@ -44,7 +62,6 @@ impl ChatError { Self::MissingField { .. } => "missing_required_parameter", Self::InvalidType { .. } => "invalid_type", Self::EmptyField { .. } | Self::InvalidValue { .. } => "invalid_value", - Self::UnknownField { .. } => "unknown_parameter", Self::UnsupportedField { .. } | Self::UnsupportedCombination { .. } => { "unsupported_parameter" } @@ -60,7 +77,6 @@ impl ChatError { | Self::InvalidType { field, .. } | Self::EmptyField { field } | Self::InvalidValue { field } - | Self::UnknownField { field } | Self::UnsupportedField { field } => Some(field), Self::UnsupportedCombination { field, .. } => Some(field), _ => None, diff --git a/backend/crates/gateway-protocol/src/chat_completions/genai/request.rs b/backend/crates/gateway-protocol/src/chat_completions/genai/request.rs index 5f6137d17..ec7c7e13a 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/genai/request.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/genai/request.rs @@ -1,7 +1,7 @@ //! Chat 内容、工具与生成设置直接构造 GenAI 正文 use crate::chat_completions::{ - ChatError, + ChatError, custom_tool_schema, error::{invalid, unsupported}, request::string, validate_request, @@ -312,7 +312,7 @@ fn tools(chat: &Map, result: &mut Map) -> Result<( false, )?; let parameters = if kind == "custom" { - json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]}) + custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))? } else { definition .get("parameters") diff --git a/backend/crates/gateway-protocol/src/chat_completions/genai/stream.rs b/backend/crates/gateway-protocol/src/chat_completions/genai/stream.rs index c1bb678d6..24b70d0d1 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/genai/stream.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/genai/stream.rs @@ -60,13 +60,6 @@ impl ChatStreamEncoder { } } - pub fn is_completed(&self) -> bool { - self.completed - } - pub fn has_wire_failure(&self) -> bool { - self.failed - } - pub fn push_event( &mut self, _event: Option<&str>, diff --git a/backend/crates/gateway-protocol/src/chat_completions/messages/request.rs b/backend/crates/gateway-protocol/src/chat_completions/messages/request.rs index 0f7ef31ed..f2e7b85d7 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/messages/request.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/messages/request.rs @@ -2,7 +2,7 @@ use crate::anthropic::MessagesModelCapabilities; use crate::chat_completions::{ - ChatError, + ChatError, custom_tool_schema, error::{invalid, unsupported}, request::string, validate_request, @@ -236,14 +236,6 @@ fn content(value: &Value, path: &str, system: bool) -> Result, ChatEr } block } - "prompt_cache_breakpoint" => { - let last = output.last_mut().ok_or_else(|| invalid(&path))?; - last["cache_control"] = part - .get("cache_control") - .cloned() - .unwrap_or_else(|| json!({"type":"ephemeral"})); - continue; - } _ => return Err(unsupported(&format!("{path}.type"))), }; output.push(block); @@ -301,7 +293,7 @@ fn tools( false, )?; let schema = if kind == "custom" { - json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]}) + custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))? } else { declaration .get("parameters") diff --git a/backend/crates/gateway-protocol/src/chat_completions/messages/stream.rs b/backend/crates/gateway-protocol/src/chat_completions/messages/stream.rs index 0b683dbc3..691daaa30 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/messages/stream.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/messages/stream.rs @@ -62,13 +62,6 @@ impl ChatStreamEncoder { } } - pub fn is_completed(&self) -> bool { - self.completed - } - pub fn has_wire_failure(&self) -> bool { - self.failed - } - pub fn push_event( &mut self, event: Option<&str>, diff --git a/backend/crates/gateway-protocol/src/chat_completions/mod.rs b/backend/crates/gateway-protocol/src/chat_completions/mod.rs index 49c8ba78f..a0e2aa084 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/mod.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/mod.rs @@ -9,7 +9,7 @@ pub mod messages; pub mod responses; pub use error::ChatError; -pub use request::{ChatRequest, parse_request, validate_request}; +pub use request::{custom_tool_schema, parse_request, validate_request}; pub(crate) use request::{request_effort, request_facts}; pub use response::{ChatAccumulator, ChatIdentity, completion_chunks}; diff --git a/backend/crates/gateway-protocol/src/chat_completions/request.rs b/backend/crates/gateway-protocol/src/chat_completions/request.rs index ee6ddbcc1..293f83c93 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/request.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/request.rs @@ -1,4 +1,4 @@ -//! Chat 入站解析和能力提取,选路前保持 Chat 正文 +//! Chat 公共请求校验、声明事实与字符串工具合同,选路前保持原文 use super::{ ChatError, @@ -7,28 +7,14 @@ use super::{ use crate::capabilities::RequestFacts; use serde_json::{Map, Value, json}; -/// 已解码的 Chat 正文与交付选项 -pub struct ChatRequest { - pub body: Map, - pub include_usage: bool, -} - /// 仅解析当前协议,不构造目标平台报文 -pub fn parse_request(bytes: &[u8]) -> Result { +pub fn parse_request(bytes: &[u8]) -> Result, ChatError> { let value: Value = serde_json::from_slice(bytes).map_err(|_| ChatError::MalformedJson)?; let Value::Object(body) = value else { return Err(ChatError::ExpectedObject); }; validate_request(&body)?; - let include_usage = body - .get("stream_options") - .and_then(|v| v.get("include_usage")) - .and_then(Value::as_bool) - .unwrap_or(false); - Ok(ChatRequest { - body, - include_usage, - }) + Ok(body) } /// 校验各目标共同遵守的 Chat 请求合同 @@ -70,6 +56,11 @@ pub fn validate_request(body: &Map) -> Result<(), ChatError> { return Err(unsupported(&format!("{path}.{field}"))); } } + for field in ["name", "refusal"] { + if let Some(value) = message.get(field).filter(|v| !v.is_null()) { + string(Some(value), &format!("{path}.{field}"), true)?; + } + } if role == "tool" { string( message.get("tool_call_id"), @@ -124,15 +115,14 @@ pub fn validate_request(body: &Map) -> Result<(), ChatError> { &format!("{call_path}.{kind}.name"), false, )?; + let data_field = if kind == "function" { + "arguments" + } else { + "input" + }; string( - call.get(kind).and_then(|v| { - v.get(if kind == "function" { - "arguments" - } else { - "input" - }) - }), - &format!("{call_path}.{kind}"), + call.get(kind).and_then(|v| v.get(data_field)), + &format!("{call_path}.{kind}.{data_field}"), true, )?; } @@ -209,9 +199,27 @@ pub(crate) fn request_facts(body: &Map) -> RequestFacts { .get("tools") .and_then(Value::as_array) .is_some_and(|v| !v.is_empty()) - || body.contains_key("web_search_options"), - vision: has_type(body.get("messages"), &["image_url", "input_image"]), - image_generation: has_type(body.get("tools"), &["image_generation"]), + || body.get("web_search_options").is_some_and(|v| !v.is_null()), + // 只读取协议内容块,不将工具参数、扩展字段或 schema 示例解释为请求能力 + vision: body + .get("messages") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|message| message.get("content").and_then(Value::as_array)) + .flatten() + .any(|part| { + matches!( + part.get("type").and_then(Value::as_str), + Some("image_url" | "input_image") + ) + }), + image_generation: body + .get("tools") + .and_then(Value::as_array) + .into_iter() + .flatten() + .any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")), reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null()) || body.get("reasoning").is_some_and(Value::is_object), json_schema: body @@ -238,15 +246,17 @@ pub(crate) fn request_effort(body: &Map) -> Option<&str> { }) } -fn has_type(value: Option<&Value>, kinds: &[&str]) -> bool { - match value { - Some(Value::Object(v)) => { - v.get("type") - .and_then(Value::as_str) - .is_some_and(|v| kinds.contains(&v)) - || v.values().any(|v| has_type(Some(v), kinds)) +/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持 +pub fn custom_tool_schema(format: Option<&Value>, path: &str) -> Result { + if let Some(format) = format.filter(|value| !value.is_null()) { + if !format.is_object() { + return Err(invalid(path)); + } + if string(format.get("type"), &format!("{path}.type"), false)? != "text" { + return Err(unsupported(path)); } - Some(Value::Array(v)) => v.iter().any(|v| has_type(Some(v), kinds)), - _ => false, } + Ok( + json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"],"additionalProperties":false}), + ) } diff --git a/backend/crates/gateway-protocol/src/chat_completions/responses/request.rs b/backend/crates/gateway-protocol/src/chat_completions/responses/request.rs index 17623f998..3b2d33478 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/responses/request.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/responses/request.rs @@ -4,17 +4,16 @@ use std::collections::HashSet; use serde_json::{Map, Value, json}; -use crate::chat_completions::ChatError as RequestDecodeError; +use crate::chat_completions::{ChatError as RequestDecodeError, validate_request}; /// 将已验证的 Chat 正文直接转换为 Responses 请求 pub fn convert_request( request: &Map, ) -> Result, RequestDecodeError> { + validate_request(request)?; let mut chat = request.clone(); - validate_options(&chat)?; let model = required_string(&mut chat, "model", "model", false)?; let stream = optional_bool(&mut chat, "stream", "stream")?.unwrap_or(false); - stream_options(optional(&mut chat, "stream_options"), stream)?; let input = messages(required(&mut chat, "messages", "messages")?)?; let mut body = Map::from_iter([ ("model".into(), model.into()), @@ -127,23 +126,6 @@ pub fn convert_request( Ok(body) } -fn validate_options(chat: &Map) -> Result<(), RequestDecodeError> { - for (field, value) in chat.iter().filter(|(_, value)| !value.is_null()) { - let supported = match field.as_str() { - "n" => value.as_u64() == Some(1), - "store" | "background" => value == false, - "functions" => value.as_array().is_some_and(Vec::is_empty), - "modalities" => value == &json!(["text"]), - "audio" | "function_call" | "input" | "previous_response_id" | "conversation" => false, - _ => true, - }; - if !supported { - return Err(unsupported(field)); - } - } - Ok(()) -} - fn web_search_tool(value: Value) -> Result { let mut options = object(value, "web_search_options")?; let mut tool = json!({"type": "web_search"}); @@ -171,71 +153,15 @@ fn web_search_tool(value: Value) -> Result { Ok(tool) } -fn stream_options(value: Option, stream: bool) -> Result { - let Some(value) = value else { - return Ok(false); - }; - if !stream { - return Err(invalid("stream_options")); - } - let mut options = object(value, "stream_options")?; - let include_usage = optional_bool( - &mut options, - "include_usage", - "stream_options.include_usage", - )? - .unwrap_or(false); - if optional_bool( - &mut options, - "include_obfuscation", - "stream_options.include_obfuscation", - )? == Some(true) - { - // Chat 重编码会改变帧长度,不能声称继承上游流的长度混淆保证 - return Err(unsupported("stream_options.include_obfuscation")); - } - Ok(include_usage) -} - fn messages(value: Value) -> Result, RequestDecodeError> { let messages = array(value, "messages")?; - if messages.is_empty() { - return Err(RequestDecodeError::EmptyField { - field: "messages".into(), - }); - } let mut input = Vec::with_capacity(messages.len()); let mut custom_calls = HashSet::new(); for (index, value) in messages.into_iter().enumerate() { let path = format!("messages[{index}]"); let mut message = object(value, &path)?; let role = required_string(&mut message, "role", &format!("{path}.role"), false)?; - if !matches!( - role.as_str(), - "system" | "developer" | "user" | "assistant" | "tool" - ) { - return Err(unsupported(&format!("{path}.role"))); - } let name = optional(&mut message, "name").filter(|name| name != ""); - if let Some(name) = &name { - let name_path = format!("{path}.name"); - string(name, &name_path, true)?; - } - // Chat 的显示名称和明文推理历史没有对应的 Responses 输入语义 - for field in ["function_call", "audio"] { - if optional(&mut message, field).is_some() { - return Err(unsupported(&format!("{path}.{field}"))); - } - } - for (field, allowed_role) in [ - ("tool_calls", "assistant"), - ("refusal", "assistant"), - ("tool_call_id", "tool"), - ] { - if role != allowed_role && message.get(field).is_some_and(|value| !value.is_null()) { - return Err(invalid(&format!("{path}.{field}"))); - } - } if role == "tool" { let call_id = required_string( &mut message, @@ -268,13 +194,7 @@ fn messages(value: Value) -> Result, RequestDecodeError> { .transpose()? .unwrap_or_default(); let refusal = optional(&mut message, "refusal"); - if let Some(value) = &refusal { - string(value, &format!("{path}.refusal"), true)?; - } let content = optional(&mut message, "content"); - if content.is_none() && refusal.is_none() && calls.is_empty() { - return Err(invalid(&format!("{path}.content"))); - } let is_assistant = role == "assistant"; let mut parts = content .map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant)) diff --git a/backend/crates/gateway-protocol/src/chat_completions/responses/response.rs b/backend/crates/gateway-protocol/src/chat_completions/responses/response.rs index 18ea6b630..e050acfe3 100644 --- a/backend/crates/gateway-protocol/src/chat_completions/responses/response.rs +++ b/backend/crates/gateway-protocol/src/chat_completions/responses/response.rs @@ -223,11 +223,7 @@ impl ChatStreamEncoder { } } - pub fn is_completed(&self) -> bool { - self.terminal == Some(Terminal::Completed) - } - - pub fn has_wire_failure(&self) -> bool { + fn has_wire_failure(&self) -> bool { self.terminal == Some(Terminal::Failed) } diff --git a/backend/crates/gateway-protocol/src/openai/web_search.rs b/backend/crates/gateway-protocol/src/openai/web_search.rs index bbc15a7c1..16463f085 100644 --- a/backend/crates/gateway-protocol/src/openai/web_search.rs +++ b/backend/crates/gateway-protocol/src/openai/web_search.rs @@ -1,33 +1,7 @@ -//! Responses 内置搜索声明与强制工具选择,共用同一协议判定 +//! Responses 内置搜索声明与强制搜索事实 use serde_json::{Map, Value}; -/// 强制搜索无法对应唯一声明,不替调用方猜测搜索参数 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SearchSelectionError { - MissingDeclaration, - MultipleDeclarations, -} - -impl SearchSelectionError { - /// 只包含静态协议诊断,可交给请求边界展示 - #[must_use] - pub const fn message(self) -> &'static str { - match self { - Self::MissingDeclaration => "The selected web search tool must be declared.", - Self::MultipleDeclarations => "Select one web search declaration.", - } - } -} - -impl std::fmt::Display for SearchSelectionError { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str(self.message()) - } -} - -impl std::error::Error for SearchSelectionError {} - #[must_use] pub fn is_search(tool: &Value) -> bool { matches!( @@ -59,45 +33,3 @@ pub fn is_required(body: &Map) -> bool { }; tools.is_some_and(|tools| !tools.is_empty() && tools.iter().all(is_search)) } - -/// 只收窄搜索声明的允许范围,不把工具选择中的引用当成完整声明 -pub fn allowed_declarations(body: &Map) -> impl Iterator { - let choice = body.get("tool_choice").unwrap_or(&Value::Null); - body.get("tools") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter(move |tool| { - is_search(tool) - && (choice["type"] != "allowed_tools" - || choice["tools"].as_array().is_some_and(|allowed| { - allowed - .iter() - .any(|reference| reference["type"] == tool["type"]) - })) - }) -} - -/// 可选搜索返回 None;强制搜索必须选出唯一声明,缺失或歧义不能退回普通生成 -pub fn required_tool(body: &Map) -> Result, SearchSelectionError> { - if !is_required(body) { - return Ok(None); - } - let choice = body.get("tool_choice").unwrap_or(&Value::Null); - let mut tools = allowed_declarations(body) - .filter(|tool| !is_search(choice) || choice["type"] == tool["type"]); - let tool = tools - .next() - .ok_or(SearchSelectionError::MissingDeclaration)?; - if tools.next().is_some() { - return Err(SearchSelectionError::MultipleDeclarations); - } - Ok(Some(tool)) -} - -/// 未限制联网或明确选择 live 时允许实时访问;目标上游决定能否兑现其他模式 -#[must_use] -pub fn allows_live_access(tool: &Value) -> bool { - tool.get("external_web_access") - .is_none_or(|value| value.is_null() || value == true || value == "live") -} diff --git a/backend/crates/gateway-protocol/tests/chat_completions/genai/stream.rs b/backend/crates/gateway-protocol/tests/chat_completions/genai/stream.rs index 59fd4005b..95234a048 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/genai/stream.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/genai/stream.rs @@ -22,11 +22,9 @@ fn usage_after_finish_reason_is_included_once_at_eof() { accumulator.push(&chunk).unwrap(); } } - assert!(!encoder.is_completed()); for chunk in encoder.finish().unwrap() { accumulator.push(&chunk).unwrap(); } - assert!(encoder.is_completed()); assert!(encoder.finish().unwrap().is_empty()); let result = accumulator.finish().unwrap(); assert_eq!(result["choices"][0]["message"]["content"], "hello world"); diff --git a/backend/crates/gateway-protocol/tests/chat_completions/messages/stream.rs b/backend/crates/gateway-protocol/tests/chat_completions/messages/stream.rs index 486d75c6b..56a4bb3cb 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/messages/stream.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/messages/stream.rs @@ -24,7 +24,6 @@ fn native_json_and_stream_produce_the_same_chat_result() { accumulator.push(&chunk).unwrap(); } } - assert!(encoder.is_completed()); assert!(encoder.finish().unwrap().is_empty()); assert_eq!(accumulator.finish().unwrap(), expected); } @@ -91,7 +90,5 @@ fn upstream_error_preserves_error_type_without_finish_chunk() { encoder.push_event(None, &error).unwrap(), vec![json!({"error":error["error"]})] ); - assert!(encoder.has_wire_failure()); - assert!(!encoder.is_completed()); assert!(encoder.finish().unwrap().is_empty()); } diff --git a/backend/crates/gateway-protocol/tests/chat_completions/request.rs b/backend/crates/gateway-protocol/tests/chat_completions/request.rs index 0f1bdf168..edd0ab52a 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/request.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/request.rs @@ -1,7 +1,7 @@ //! Chat 原文解析与选路事实不依赖任何目标转换 use gateway_protocol::{ - chat_completions::{CHAT_PROTOCOL, ChatError, parse_request}, + chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses}, request::{request_facts, request_observation}, }; use serde_json::json; @@ -10,9 +10,8 @@ use serde_json::json; fn parsing_retains_original_protocol_and_usage_preference() { let value = json!({"model":"m","messages":[{"role":"user","content":"hello"}],"stream":true,"stream_options":{"include_usage":true},"future":{"store":true}}); let parsed = parse_request(&serde_json::to_vec(&value).unwrap()).unwrap(); - assert_eq!(parsed.body, value.as_object().unwrap().clone()); - assert!(parsed.include_usage); - assert!(!parsed.body.contains_key("input")); + assert_eq!(parsed, value.as_object().unwrap().clone()); + assert!(!parsed.contains_key("input")); } #[test] @@ -83,3 +82,100 @@ fn unsupported_content_is_rejected_before_any_target_is_selected() { assert!(!error.to_string().contains("SENSITIVE_CONTENT")); } } + +#[test] +fn capability_facts_only_read_protocol_declarations() { + let mut body = super::request(); + body.insert("tools".into(), json!([{"type":"function","function":{"name":"save","parameters":{"type":"object","properties":{"payload":{"type":"object","default":{"type":"image_generation"}}},"examples":[{"type":"image_generation"}]}}}])); + body.insert( + "messages".into(), + json!([{"role":"user","content":"hello","metadata":{"type":"image_url"}}]), + ); + let facts = request_facts(CHAT_PROTOCOL, &body); + assert!(!facts.image_generation && !facts.vision); + assert!(facts.tools); + body["tools"] + .as_array_mut() + .unwrap() + .push(json!({"type":"image_generation"})); + assert!(request_facts(CHAT_PROTOCOL, &body).image_generation); + body.remove("tools"); + body.insert("web_search_options".into(), json!(null)); + assert!(!request_facts(CHAT_PROTOCOL, &body).tools); +} + +#[test] +fn all_targets_apply_the_same_common_request_validation() { + for (field, value, parameter) in [ + ( + "messages", + json!([{"role":"assistant","content":"ok","refusal":17}]), + "messages[0].refusal", + ), + ( + "messages", + json!([{"role":"user","content":"ok","name":17}]), + "messages[0].name", + ), + ( + "messages", + json!([{"role":"user","content":"ok","tool_calls":[]}]), + "messages[0].tool_calls", + ), + ( + "messages", + json!([{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":17}}]}]), + "messages[0].tool_calls[0].function.arguments", + ), + ("n", json!(2), "n"), + ( + "stream_options", + json!({"include_usage":true}), + "stream_options", + ), + ] { + let mut body = super::request(); + body.insert(field.into(), value); + let expected = parse_request(&serde_json::to_vec(&body).unwrap()) + .err() + .unwrap(); + assert_eq!(expected.parameter(), Some(parameter)); + for result in [ + responses::convert_request(&body), + messages::convert_request(&body, &Default::default()), + genai::convert_request(&body), + ] { + assert_eq!(result.unwrap_err(), expected); + } + } +} + +#[test] +fn custom_format_constraints_are_preserved_or_rejected_by_the_target() { + for format in [ + json!(null), + json!({"type":"text"}), + json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}), + json!(17), + ] { + let mut body = super::request(); + body.insert( + "tools".into(), + json!([{"type":"custom","custom":{"name":"run","format":format}}]), + ); + let responses = responses::convert_request(&body).unwrap(); + assert_eq!(responses["tools"][0]["format"], format); + for result in [ + messages::convert_request(&body, &Default::default()), + genai::convert_request(&body), + ] { + if format.is_null() || format["type"] == "text" { + assert!(result.is_ok()); + } else { + let error = result.unwrap_err(); + assert_eq!(error.parameter(), Some("tools[0].custom.format")); + assert!(!error.to_string().contains("PRIVATE_GRAMMAR")); + } + } + } +} diff --git a/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs b/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs index 8ebec43aa..12d49fac2 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs @@ -274,7 +274,6 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { for event in events { chunks.extend(encoder.push_event(None, &event).unwrap()); } - assert!(encoder.is_completed()); assert!(encoder.finish().unwrap().is_empty()); assert_eq!(combined(&chunks, "content"), "你好 🌍"); assert_eq!( diff --git a/backend/crates/gateway-protocol/tests/openai/web_search.rs b/backend/crates/gateway-protocol/tests/openai/web_search.rs index 4efd66930..936c53c2c 100644 --- a/backend/crates/gateway-protocol/tests/openai/web_search.rs +++ b/backend/crates/gateway-protocol/tests/openai/web_search.rs @@ -1,6 +1,6 @@ -//! 搜索路由与声明解析共用 Responses 工具选择语义 +//! Responses 工具选择中的强制搜索事实 -use gateway_protocol::openai::web_search::{SearchSelectionError, is_required, required_tool}; +use gateway_protocol::openai::web_search::is_required; use serde_json::{Value, json}; #[test] @@ -20,7 +20,6 @@ fn optional_or_mixed_tool_choices_do_not_require_search() { let body = json!({"tools":[search,function],"tool_choice":choice}); let body = body.as_object().unwrap(); assert!(!is_required(body), "{choice}"); - assert_eq!(required_tool(body), Ok(None), "{choice}"); } assert!(!is_required( json!({"tool_choice":"required"}).as_object().unwrap() @@ -28,7 +27,7 @@ fn optional_or_mixed_tool_choices_do_not_require_search() { } #[test] -fn required_search_uses_the_original_selected_declaration() { +fn explicit_and_exclusive_tool_choices_require_search() { for kind in [ "web_search", "web_search_preview", @@ -49,42 +48,6 @@ fn required_search_uses_the_original_selected_declaration() { let body = json!({"tools":tools,"tool_choice":choice}); let body = body.as_object().unwrap(); assert!(is_required(body)); - assert_eq!(required_tool(body), Ok(Some(&search))); } } } - -#[test] -fn missing_or_ambiguous_required_search_cannot_fall_back_to_generation() { - let search = json!({"type":"web_search"}); - for (body, expected) in [ - ( - json!({"tool_choice":search}), - SearchSelectionError::MissingDeclaration, - ), - ( - json!({"tools":[search],"tool_choice":{"type":"web_search_preview"}}), - SearchSelectionError::MissingDeclaration, - ), - ( - json!({"tools":[search],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"web_search_preview"}]}}), - SearchSelectionError::MissingDeclaration, - ), - ( - json!({"tools":[search,search],"tool_choice":search}), - SearchSelectionError::MultipleDeclarations, - ), - ( - json!({"tools":[search,{"type":"web_search_preview"}],"tool_choice":"required"}), - SearchSelectionError::MultipleDeclarations, - ), - ( - json!({"tools":[search,search],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[search]}}), - SearchSelectionError::MultipleDeclarations, - ), - ] { - let body = body.as_object().unwrap(); - assert!(is_required(body)); - assert_eq!(required_tool(body), Err(expected)); - } -} diff --git a/backend/crates/providers/antigravity/src/provider/chat.rs b/backend/crates/providers/antigravity/src/provider/chat.rs index ec245d7de..ae503ec61 100644 --- a/backend/crates/providers/antigravity/src/provider/chat.rs +++ b/backend/crates/providers/antigravity/src/provider/chat.rs @@ -53,8 +53,11 @@ pub(super) fn prepare( .unwrap_or_default() .to_owned(), }; - let mut body = genai::convert_request(original) - .map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?; + let mut body = genai::convert_request(original).map_err(|error| { + ProviderError::invalid_request(error.safe_message()) + .with_request_details(error.code(), error.parameter()) + .with_source(error) + })?; if let Some(session) = affinity { body.insert( "sessionId".to_owned(), diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs index ba7d515e2..2ea78b5e3 100644 --- a/backend/crates/providers/antigravity/tests/provider/execution.rs +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -868,6 +868,13 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest); assert_eq!(error.send_state(), UpstreamSendState::NotSent); assert!(error.error_details().is_some()); + let public = gateway_core::error::GatewayError::from_provider(&error); + assert_eq!(public.client_error_code(), Some("unsupported_parameter")); + let field = options.as_object().unwrap().keys().next().unwrap(); + assert_eq!( + public.client_error_parameter(), + Some(format!("web_search_options.{field}").as_str()) + ); released(&fixture).await; } assert!(upstream.received_requests().await.unwrap().is_empty()); diff --git a/backend/crates/providers/openai/src/compat/messages.rs b/backend/crates/providers/openai/src/compat/chat.rs similarity index 96% rename from backend/crates/providers/openai/src/compat/messages.rs rename to backend/crates/providers/openai/src/compat/chat.rs index 5d462616e..0eac685a8 100644 --- a/backend/crates/providers/openai/src/compat/messages.rs +++ b/backend/crates/providers/openai/src/compat/chat.rs @@ -1,4 +1,4 @@ -//! Messages 跨协议转换的目标档位与 fast 协议头适配 +//! Chat 转换的目标档位与 fast 协议头适配 use bytes::Bytes; use gateway_core::engine::middleware::MiddlewareHeader; diff --git a/backend/crates/providers/openai/src/compat/mod.rs b/backend/crates/providers/openai/src/compat/mod.rs index 820112513..07df44e4f 100644 --- a/backend/crates/providers/openai/src/compat/mod.rs +++ b/backend/crates/providers/openai/src/compat/mod.rs @@ -1,8 +1,8 @@ //! OpenAI 上下游协议差异与外部缺陷补偿的统一入口 //! 规则只处理请求事实;身份保护、会话状态和连接生命周期由对应职责模块维护 +mod chat; mod headers; -mod messages; mod request; mod search_history; mod search_tools; @@ -10,8 +10,8 @@ mod search_tools; use gateway_core::engine::middleware::MiddlewareHeader; use serde_json::{Map, Value}; +pub(crate) use chat::{add_translated_fast_beta, normalize_translated_codex_service_tier}; pub(crate) use headers::is_non_codex_request_header; -pub(crate) use messages::{add_translated_fast_beta, normalize_translated_codex_service_tier}; pub(crate) use request::normalize_codex_request_body; pub(crate) use search_tools::declares_hosted_search; diff --git a/backend/crates/providers/openai/src/provider/chat/mod.rs b/backend/crates/providers/openai/src/provider/chat/mod.rs index bd5973330..a9c5e33c4 100644 --- a/backend/crates/providers/openai/src/provider/chat/mod.rs +++ b/backend/crates/providers/openai/src/provider/chat/mod.rs @@ -45,8 +45,12 @@ impl CodexProvider { .catalog .messages_model_capabilities(selected.lease.account(), &model) .unwrap_or_default(); - let mut body = messages::convert_request(original, &capabilities) - .map_err(|error| request_error().with_source(error))?; + let mut body = + messages::convert_request(original, &capabilities).map_err(|error| { + ProviderError::invalid_request(error.safe_message()) + .with_request_details(error.code(), error.parameter()) + .with_source(error) + })?; body.insert("model".to_owned(), Value::String(model.as_str().to_owned())); headers::retain_messages_headers(&mut source_context, &mut headers); if body.get("speed").and_then(Value::as_str) == Some("fast") { @@ -68,8 +72,11 @@ impl CodexProvider { Ok(stream.with_native_response_translator(translator)) } ApiKeyProtocol::Responses => { - let mut body = responses::convert_request(original) - .map_err(|error| request_error().with_source(error))?; + let mut body = responses::convert_request(original).map_err(|error| { + ProviderError::invalid_request(error.safe_message()) + .with_request_details(error.code(), error.parameter()) + .with_source(error) + })?; if matches!( selected.lease.authentication(), CodexRuntimeAuthentication::OAuth(_) diff --git a/backend/crates/providers/openai/tests/provider/contract/messages/translator.rs b/backend/crates/providers/openai/tests/provider/contract/messages/translator.rs index b03ba9859..7b46f5e27 100644 --- a/backend/crates/providers/openai/tests/provider/contract/messages/translator.rs +++ b/backend/crates/providers/openai/tests/provider/contract/messages/translator.rs @@ -1,4 +1,4 @@ -//! 转换失败保留受限诊断原因,不改变发送状态或公共错误 +//! 转换错误保留安全字段与受限诊断,响应交付保持所选协议 use super::*; use gateway_core::event::{ProtocolWireEvent, ProviderEvent}; @@ -75,6 +75,12 @@ async fn request_translation_preserves_the_unsent_validation_cause() { error.source().unwrap().downcast_ref::(), Some(ChatError::InvalidValue { .. }) )); + let public = gateway_core::error::GatewayError::from_provider(&error); + assert_eq!(public.client_error_code(), Some("invalid_value")); + assert_eq!( + public.client_error_parameter(), + Some("tool_choice.allowed_tools.tools") + ); assert!(server.received_requests().await.unwrap().is_empty()); } diff --git a/backend/crates/providers/xai/src/provider/failure.rs b/backend/crates/providers/xai/src/provider/failure.rs index b5696f226..3aec71990 100644 --- a/backend/crates/providers/xai/src/provider/failure.rs +++ b/backend/crates/providers/xai/src/provider/failure.rs @@ -368,9 +368,12 @@ pub(super) fn ensure_sent_context(context: &AttemptContext) -> Result<(), Provid pub(super) fn map_request_error(error: GrokRequestEncodeError) -> ProviderError { let kind = match error { - GrokRequestEncodeError::InvalidProtocolPayload - | GrokRequestEncodeError::InvalidRequestNormalization - | GrokRequestEncodeError::InvalidRequestField { .. } => ProviderErrorKind::InvalidRequest, + GrokRequestEncodeError::Chat(error) => { + return ProviderError::invalid_request(error.safe_message()) + .with_request_details(error.code(), error.parameter()) + .with_source(error); + } + GrokRequestEncodeError::InvalidProtocolPayload => ProviderErrorKind::InvalidRequest, GrokRequestEncodeError::UnsupportedPrewarm => ProviderErrorKind::Unsupported, GrokRequestEncodeError::Serialization => ProviderErrorKind::Protocol, }; diff --git a/backend/crates/providers/xai/src/transport/request/chat.rs b/backend/crates/providers/xai/src/transport/request/chat.rs index 7cc300164..58e8bdfb9 100644 --- a/backend/crates/providers/xai/src/transport/request/chat.rs +++ b/backend/crates/providers/xai/src/transport/request/chat.rs @@ -1,7 +1,7 @@ //! Chat 直接生成 Grok 实际使用的 Responses wire,不经过 Harness 归一化 use super::*; -use gateway_protocol::chat_completions::{CHAT_PROTOCOL, responses}; +use gateway_protocol::chat_completions::{CHAT_PROTOCOL, custom_tool_schema, responses}; impl GrokResponsesRequest { pub(crate) fn from_chat( @@ -14,29 +14,24 @@ impl GrokResponsesRequest { { return Err(GrokRequestEncodeError::InvalidProtocolPayload); } - let mut body = responses::convert_request(request.protocol_payload().body()) - .map_err(|_| GrokRequestEncodeError::InvalidRequestNormalization)?; + let mut body = responses::convert_request(request.protocol_payload().body())?; // 上游只接受函数工具,custom 的字符串输入直接编码到此目标的参数合同 if let Some(tools) = body.get_mut("tools").and_then(Value::as_array_mut) { - for tool in tools { + for (index, tool) in tools.iter_mut().enumerate() { if tool.get("type").and_then(Value::as_str) != Some("custom") { continue; } - if tool - .get("format") - .and_then(|format| format.get("type")) - .and_then(Value::as_str) - .is_some_and(|kind| kind != "text") - { - return Err(GrokRequestEncodeError::InvalidRequestField { field: "tools" }); - } + let source = &request.protocol_payload().body()["tools"][index]; + let path = if source.get("custom").is_some_and(|value| !value.is_null()) { + format!("tools[{index}].custom.format") + } else { + format!("tools[{index}].format") + }; + let schema = custom_tool_schema(tool.get("format"), &path)?; let mut function = Map::from_iter([ ("type".to_owned(), json!("function")), ("name".to_owned(), tool["name"].clone()), - ( - "parameters".to_owned(), - json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"],"additionalProperties":false}), - ), + ("parameters".to_owned(), schema), ]); if let Some(description) = tool.get("description") { function.insert("description".to_owned(), description.clone()); @@ -56,7 +51,7 @@ impl GrokResponsesRequest { Some("custom_tool_call") => { let input = item .remove("input") - .ok_or(GrokRequestEncodeError::InvalidRequestNormalization)?; + .ok_or(GrokRequestEncodeError::InvalidProtocolPayload)?; item.insert("type".to_owned(), json!("function_call")); item.insert( "arguments".to_owned(), diff --git a/backend/crates/providers/xai/src/transport/request/mod.rs b/backend/crates/providers/xai/src/transport/request/mod.rs index 3539bda5f..6591436ac 100644 --- a/backend/crates/providers/xai/src/transport/request/mod.rs +++ b/backend/crates/providers/xai/src/transport/request/mod.rs @@ -119,7 +119,7 @@ impl fmt::Debug for GrokResponsesRequest { } /// 编码错误仅包含字段名,不包含请求或账号数据 -#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum GrokRequestEncodeError { #[error("The request protocol is not supported by this Grok path.")] InvalidProtocolPayload, @@ -127,8 +127,6 @@ pub enum GrokRequestEncodeError { UnsupportedPrewarm, #[error("Grok request serialization failed.")] Serialization, - #[error("The Chat request cannot be represented by Grok Responses.")] - InvalidRequestNormalization, - #[error("The Chat request field `{field}` cannot be represented by Grok Responses.")] - InvalidRequestField { field: &'static str }, + #[error(transparent)] + Chat(#[from] gateway_protocol::chat_completions::ChatError), } diff --git a/backend/crates/providers/xai/tests/provider/contract/chat.rs b/backend/crates/providers/xai/tests/provider/contract/chat.rs index 5fd735321..e0ed38a81 100644 --- a/backend/crates/providers/xai/tests/provider/contract/chat.rs +++ b/backend/crates/providers/xai/tests/provider/contract/chat.rs @@ -110,3 +110,43 @@ async fn chat_allowed_custom_choice_matches_the_actual_function_declaration() { ); assert_eq!(body["tools"][0]["name"], "run"); } + +#[tokio::test] +async fn unsupported_custom_formats_keep_safe_fields_without_sending() { + for tool in [ + json!({"type":"custom","custom":{"name":"run","format":{"type":"grammar","grammar":{"definition":"PRIVATE_GRAMMAR"}}}}), + json!({"type":"custom","name":"run","format":{"type":"grammar","grammar":{"definition":"PRIVATE_GRAMMAR"}}}), + ] { + let transport = StubInferenceTransport::success(); + let provider = provider(StubSelector::success(), transport.clone()).await; + let field = if tool.get("custom").is_some() { + "tools[0].custom.format" + } else { + "tools[0].format" + }; + let operation = Operation::Generate(GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object( + CHAT_PROTOCOL, + object(json!({ + "model":MODEL,"messages":[{"role":"user","content":"hello"}],"tools":[tool] + })), + ) + .unwrap(), + )); + let error = provider + .execute( + provider_request_with_operation("xai", operation), + context(CancellationToken::new(), None), + ) + .await + .err() + .unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest); + assert_eq!(error.send_state(), UpstreamSendState::NotSent); + let public = gateway_core::error::GatewayError::from_provider(&error); + assert_eq!(public.client_error_code(), Some("unsupported_parameter")); + assert_eq!(public.client_error_parameter(), Some(field)); + assert!(!public.client_message().contains("PRIVATE_GRAMMAR")); + assert!(transport.requests.lock().unwrap().is_empty()); + } +} diff --git a/docs/api.md b/docs/api.md index 197aab7af..fff52541f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -350,6 +350,7 @@ Messages 目标直接生成 `system`、`messages`、`tool_use`/`tool_result` GenAI 目标直接生成 `systemInstruction`、`contents`、`functionCall`/`functionResponse` 和 `generationConfig`。 两个目标都校验工具调用与结果的配对;custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。 +Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.type: text`;grammar 等受约束格式返回 `400`,`param` 指向原始格式字段。 多模态字段按目标能力映射,不支持的内容或声明返回字段错误,不转成另一平台协议重试 #### 响应与共用规则 diff --git a/docs/architecture.md b/docs/architecture.md index 12baef360..6247469bc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -583,6 +583,8 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模 数据面协议入口位于 `gateway-api/src/data_plane`。Responses、Chat Completions、Messages 与 GenAI 共用 `generation` 的执行和交付流程。GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity 将选中的 GenAI 请求封装为 Cloud Code 上游请求 +Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。 + GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算 Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。 @@ -1368,6 +1370,7 @@ Provider metadata 的 `upstreamServiceTier`,不改写客户端收到的响应 不进入普通 Admin 错误信封、Debug、普通日志或持久化错误摘要。连接测试只展示该接口允许的诊断投影 错误分类负责公共响应、重试和账号处置,原始上游 code 独立保存,不受已知分类白名单限制。 +本地请求校验的安全消息、机器码与字段路径由校验方显式提供,Provider 和 Core 保留这些事实供 API 交付,不从错误来源或字段值推导。 本地异常通过标准 `Error::source` 跨层传播;Core 的不透明来源载体保持底层类型,不依赖数据库或 HTTP 库, 普通格式化不展开来源。Store 统一基础设施不可用的转换,Provider 拥有业务分类, 插件 Runtime 集中投影 RPC、fault 与上游适配事件,调用点只附加原始来源与执行上下文