fix(protocol): preserve semantics across provider translations

Centralize Responses web search selection across protocol and provider adapters. Map GenAI generation settings directly from Responses while sharing content, tool, and signature conversion.

Preserve translator error sources and cover request parameters, search selection, and failure propagation.

Validation: 292 scoped tests, cargo fmt, and scoped Clippy.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-26 14:21:29 +08:00
co-authored by Codex
parent 3da3338908
commit 88da31137b
21 changed files with 693 additions and 175 deletions
@@ -12,6 +12,7 @@ mod tools;
mod usage;
pub(crate) use content::GENAI_CARRIER;
pub(crate) use request::responses_to_messages_content;
pub use capabilities::MessagesModelCapabilities;
pub use error::TranslationError;
@@ -259,7 +259,6 @@ pub fn responses_to_messages_request(
request: &Map<String, Value>,
capabilities: &MessagesModelCapabilities,
) -> Result<Map<String, Value>, TranslationError> {
let tools = ToolSet::from_responses(request);
let mut result = Map::new();
copy_fields(
request,
@@ -291,6 +290,47 @@ pub fn responses_to_messages_request(
}
_ => {}
}
result.extend(responses_to_messages_content(
request,
capabilities.hosted_web_search != Some(false),
)?);
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
if request
.get("tool_choice")
.is_some_and(|c| c["type"] == "allowed_tools" && c["mode"] == "required")
&& result["tool_choice"]["type"] != "any"
{
return Err(TranslationError::InvalidRequest(
"The Messages upstream cannot require an allowed tool with this thinking mode.",
));
}
if matches!(
result
.get("thinking")
.and_then(|value| value.get("type"))
.and_then(Value::as_str),
Some("enabled" | "adaptive")
) {
// CPA 在生成推理配置后移除不相容的采样参数;原生 Messages 不经过此转换
result.shift_remove("temperature");
result.shift_remove("top_p");
}
if let Some(format) = request.get("text").and_then(|v| v.get("format"))
&& format.get("type").and_then(Value::as_str) == Some("json_schema")
{
let config = result.entry("output_config").or_insert_with(|| json!({}));
config["format"] = json!({"type":"json_schema","schema":format.get("schema").cloned().unwrap_or_else(||json!({}))});
}
Ok(result)
}
/// 共享对话、签名与工具映射,生成参数由最终目标协议独立处理
pub(crate) fn responses_to_messages_content(
request: &Map<String, Value>,
hosted_search: bool,
) -> Result<Map<String, Value>, TranslationError> {
let tools = ToolSet::from_responses(request);
let mut result = Map::new();
let mut system = Vec::new();
if let Some(instructions) = request.get("instructions").and_then(Value::as_str)
&& !instructions.is_empty()
@@ -386,38 +426,7 @@ pub fn responses_to_messages_request(
"messages".into(),
Value::Array(normalize_tool_pairing(messages)),
);
tools.write_messages_tools(
request,
&mut result,
capabilities.hosted_web_search != Some(false),
)?;
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
if request
.get("tool_choice")
.is_some_and(|c| c["type"] == "allowed_tools" && c["mode"] == "required")
&& result["tool_choice"]["type"] != "any"
{
return Err(TranslationError::InvalidRequest(
"The Messages upstream cannot require an allowed tool with this thinking mode.",
));
}
if matches!(
result
.get("thinking")
.and_then(|value| value.get("type"))
.and_then(Value::as_str),
Some("enabled" | "adaptive")
) {
// CPA 在生成推理配置后移除不相容的采样参数;原生 Messages 不经过此转换
result.shift_remove("temperature");
result.shift_remove("top_p");
}
if let Some(format) = request.get("text").and_then(|v| v.get("format"))
&& format.get("type").and_then(Value::as_str) == Some("json_schema")
{
let config = result.entry("output_config").or_insert_with(|| json!({}));
config["format"] = json!({"type":"json_schema","schema":format.get("schema").cloned().unwrap_or_else(||json!({}))});
}
tools.write_messages_tools(request, &mut result, hosted_search)?;
Ok(result)
}
@@ -3,7 +3,7 @@
use std::collections::BTreeMap;
use super::TranslationError;
use crate::openai::web_search::is_search as is_web_search;
use crate::openai::web_search;
use serde_json::{Map, Value, json};
@@ -41,7 +41,7 @@ impl<D> ToolSet<D> {
{
result.insert(child, Some(namespace), definition(child));
}
} else if !is_web_search(tool) {
} else if !web_search::is_search(tool) {
result.insert(tool, None, definition(tool));
}
}
@@ -164,21 +164,9 @@ impl<'a> ToolSet<&'a Value> {
None
};
let mut definitions = self.definitions(allowed);
for tool in request
.get("tools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|t| hosted_search && is_web_search(t))
for tool in web_search::allowed_declarations(request)
.filter(|tool| hosted_search && web_search::allows_live_access(tool))
{
// Messages 的搜索是实时联网;缓存或索引模式不能升级为实时访问
if tool
.get("external_web_access")
.is_some_and(|v| !v.is_null() && v != true && v != "live")
|| allowed.is_some_and(|choices| !choices.iter().any(|c| c["type"] == tool["type"]))
{
continue;
}
let mut search = json!({"type":"web_search_20250305","name":"web_search"});
if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) {
let filters = filters.as_object().ok_or(TranslationError::InvalidRequest(
@@ -201,7 +189,7 @@ impl<'a> ToolSet<&'a Value> {
// 转往仅支持函数的上游时,可选托管搜索可以省略,强制工具仍须可执行
let optional_search = !hosted_search
&& choice["mode"] == "auto"
&& allowed.is_some_and(|tools| tools.iter().all(is_web_search));
&& allowed.is_some_and(|tools| tools.iter().all(web_search::is_search));
if !hosted_search
&& (choice == "required"
|| matches!(choice["type"].as_str(), Some("function" | "custom")))
@@ -13,6 +13,53 @@ fn invalid() -> TranslationError {
/// 转换 Messages 请求;不支持的内容返回错误,避免静默丢失客户端输入
pub fn messages_to_genai_request(
request: &Map<String, Value>,
) -> Result<Map<String, Value>, TranslationError> {
let mut result = content_to_genai(request)?;
let mut generation = Map::new();
for (from, to) in [
("max_tokens", "maxOutputTokens"),
("temperature", "temperature"),
("top_p", "topP"),
("top_k", "topK"),
("stop_sequences", "stopSequences"),
] {
if let Some(value) = request.get(from) {
generation.insert(to.into(), value.clone());
}
}
if let Some(thinking) = request.get("thinking") {
match thinking["type"].as_str() {
Some("disabled") => {
generation.insert("thinkingConfig".into(), json!({"thinkingBudget":0}));
}
Some("enabled") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":thinking["budget_tokens"],"includeThoughts":true}),
);
}
Some("adaptive" | "auto") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":-1,"includeThoughts":true}),
);
}
_ => return Err(invalid()),
}
}
if let Some(format) = request.get("output_config").and_then(|c| c.get("format")) {
if format["type"] != "json_schema" {
return Err(invalid());
}
generation.insert("responseMimeType".into(), json!("application/json"));
generation.insert("responseSchema".into(), format["schema"].clone());
}
result.insert("generationConfig".into(), Value::Object(generation));
Ok(result)
}
pub(super) fn content_to_genai(
request: &Map<String, Value>,
) -> Result<Map<String, Value>, TranslationError> {
let mut result = Map::new();
if let Some(system) = request.get("system") {
@@ -125,46 +172,6 @@ pub fn messages_to_genai_request(
}
}
result.insert("contents".into(), json!(contents));
let mut generation = Map::new();
for (from, to) in [
("max_tokens", "maxOutputTokens"),
("temperature", "temperature"),
("top_p", "topP"),
("top_k", "topK"),
("stop_sequences", "stopSequences"),
] {
if let Some(value) = request.get(from) {
generation.insert(to.into(), value.clone());
}
}
if let Some(thinking) = request.get("thinking") {
match thinking["type"].as_str() {
Some("disabled") => {
generation.insert("thinkingConfig".into(), json!({"thinkingBudget":0}));
}
Some("enabled") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":thinking["budget_tokens"],"includeThoughts":true}),
);
}
Some("adaptive" | "auto") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":-1,"includeThoughts":true}),
);
}
_ => return Err(invalid()),
}
}
if let Some(format) = request.get("output_config").and_then(|c| c.get("format")) {
if format["type"] != "json_schema" {
return Err(invalid());
}
generation.insert("responseMimeType".into(), json!("application/json"));
generation.insert("responseSchema".into(), format["schema"].clone());
}
result.insert("generationConfig".into(), Value::Object(generation));
if let Some(tools) = request.get("tools").and_then(Value::as_array) {
let declarations = tools
.iter()
@@ -13,9 +13,11 @@ pub use response::{
pub const GENAI_PROTOCOL: &str = "genai";
mod messages;
mod responses;
mod stream;
mod tokens;
pub use messages::messages_to_genai_request;
pub use responses::responses_to_genai_request;
pub use stream::GenAiToMessagesStream;
pub use tokens::{count_tokens_request, count_tokens_to_messages};
mod grounding;
@@ -0,0 +1,65 @@
//! Responses 复用内容映射,生成参数直接转入 GenAI,避免继承 Messages 的默认值与限制
use crate::anthropic::{TranslationError, responses_to_messages_content};
use serde_json::{Map, Value, json};
/// 普通生成只映射函数工具,独立搜索由 Provider 按账号能力编排
pub fn responses_to_genai_request(
request: &Map<String, Value>,
) -> Result<Map<String, Value>, TranslationError> {
let mut generation = Map::new();
if let Some(value) = request
.get("max_output_tokens")
.filter(|value| !value.is_null())
{
let maximum =
value
.as_u64()
.filter(|value| *value > 0)
.ok_or(TranslationError::InvalidRequest(
"The max_output_tokens field must be a positive integer.",
))?;
generation.insert("maxOutputTokens".into(), json!(maximum));
}
for (from, to) in [("temperature", "temperature"), ("top_p", "topP")] {
if let Some(value) = request.get(from) {
generation.insert(to.into(), value.clone());
}
}
if let Some(thinking) = request
.get("reasoning")
.and_then(|value| value.get("effort"))
.and_then(Value::as_str)
.and_then(thinking_config)
{
generation.insert("thinkingConfig".into(), thinking);
}
if let Some(format) = request.get("text").and_then(|value| value.get("format"))
&& format["type"] == "json_schema"
{
generation.insert("responseMimeType".into(), json!("application/json"));
generation.insert(
"responseSchema".into(),
format.get("schema").cloned().unwrap_or_else(|| json!({})),
);
}
let content = responses_to_messages_content(request, false)?;
let mut result = super::messages::content_to_genai(&content)?;
result.insert("generationConfig".into(), Value::Object(generation));
Ok(result)
}
fn thinking_config(effort: &str) -> Option<Value> {
// 档位预算不受 Messages 的必填输出上限、强制工具或无思考续轮规则影响
let budget = match effort.trim().to_ascii_lowercase().as_str() {
"none" => return Some(json!({"thinkingBudget":0})),
"minimal" | "low" => 1024,
"medium" => 8192,
"high" => 24576,
"xhigh" => 32768,
"max" => 128000,
"auto" => -1,
_ => return None,
};
Some(json!({"thinkingBudget":budget,"includeThoughts":true}))
}
@@ -2,6 +2,32 @@
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!(
@@ -33,3 +59,45 @@ pub fn is_required(body: &Map<String, Value>) -> bool {
};
tools.is_some_and(|tools| !tools.is_empty() && tools.iter().all(is_search))
}
/// 只收窄搜索声明的允许范围,不把工具选择中的引用当成完整声明
pub fn allowed_declarations(body: &Map<String, Value>) -> impl Iterator<Item = &Value> {
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<String, Value>) -> Result<Option<&Value>, 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")
}
@@ -1,11 +1,8 @@
//! 验证转换路径的工具往返、多模态输入和签名来源
use gateway_protocol::{
anthropic::{
MessagesAccumulator, MessagesModelCapabilities, MessagesToResponsesStream,
responses_to_messages_request,
},
genai::{GenAiToMessagesStream, messages_to_genai_request},
anthropic::{MessagesAccumulator, MessagesToResponsesStream},
genai::{GenAiToMessagesStream, messages_to_genai_request, responses_to_genai_request},
};
use serde_json::{Value, json};
@@ -36,12 +33,7 @@ fn signed_tool_roundtrip_preserves_custom_identity_and_final_usage() {
let call_id = call["call_id"].clone();
input.push(json!({"type":"custom_tool_call_output","call_id":call_id,"output":"done"}));
let next = json!({"model":"fixture","input":input,"tools":original["tools"]});
let messages = responses_to_messages_request(
next.as_object().unwrap(),
&MessagesModelCapabilities::default(),
)
.unwrap();
let request = messages_to_genai_request(&messages).unwrap();
let request = responses_to_genai_request(next.as_object().unwrap()).unwrap();
let call = &request["contents"][0]["parts"][0];
assert_eq!(call["thoughtSignature"], "opaque-signature");
assert_eq!(call["functionCall"]["name"], "patch");
@@ -4,3 +4,4 @@ mod response;
mod tokens;
mod messages;
mod responses;
@@ -0,0 +1,112 @@
//! Responses 生成参数不继承 Messages 的默认值、推理约束和采样裁剪
use gateway_protocol::genai::responses_to_genai_request;
use serde_json::{Value, json};
#[test]
fn unspecified_generation_settings_remain_unspecified_on_tool_continuations() {
let function = json!({"type":"function","name":"lookup","parameters":{"type":"object"}});
for choice in [json!("auto"), json!("required"), function.clone()] {
let mut request = json!({"tools":[function],"tool_choice":choice,"input":[
{"type":"function_call","call_id":"c","name":"lookup","arguments":"{}"},
{"type":"function_call_output","call_id":"c","output":"value"}
]});
for maximum in [None, Some(Value::Null)] {
if let Some(maximum) = maximum {
request["max_output_tokens"] = maximum;
}
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(body["generationConfig"], json!({}));
assert_eq!(
body["contents"][1]["parts"][0]["functionResponse"]["name"],
"lookup"
);
}
}
}
#[test]
fn explicit_reasoning_and_sampling_survive_required_tools_and_small_output_limits() {
let function = json!({"type":"function","name":"lookup","parameters":{"type":"object"}});
for choice in [
json!("required"),
function.clone(),
json!({"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"lookup"}]}),
] {
let request = json!({"input":"hello","tools":[function],"tool_choice":choice,
"max_output_tokens":128,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(
body["generationConfig"],
json!({"maxOutputTokens":128,"thinkingConfig":{"thinkingBudget":24576,"includeThoughts":true},"temperature":0.3,"topP":0.8})
);
assert_eq!(body["toolConfig"]["functionCallingConfig"]["mode"], "ANY");
if choice["type"] == "function" {
assert_eq!(
body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"],
json!(["lookup"])
);
}
}
}
#[test]
fn reasoning_budgets_do_not_inherit_messages_limits() {
for (effort, budget) in [
("none", 0),
("minimal", 1024),
("low", 1024),
("medium", 8192),
("high", 24576),
("xhigh", 32768),
("max", 128000),
("auto", -1),
] {
let request = json!({"input":"hello","reasoning":{"effort":effort}});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
let thinking = &body["generationConfig"]["thinkingConfig"];
assert_eq!(thinking["thinkingBudget"], budget, "{effort}");
assert_eq!(
thinking.get("includeThoughts"),
(budget != 0).then_some(&json!(true))
);
assert!(body["generationConfig"].get("maxOutputTokens").is_none());
}
}
#[test]
fn explicit_output_limits_must_be_positive_integers() {
for maximum in [json!(0), json!(-1), json!(1.5), json!("128"), json!(true)] {
let request = json!({"input":"hello","max_output_tokens":maximum});
assert!(
responses_to_genai_request(request.as_object().unwrap()).is_err(),
"{maximum}"
);
}
for maximum in [1, 128, 100000] {
let request = json!({"input":"hello","max_output_tokens":maximum});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(body["generationConfig"]["maxOutputTokens"], maximum);
}
}
#[test]
fn content_and_json_schema_preserve_their_target_representation() {
let request = json!({"instructions":"system","input":[{"role":"user","content":[
{"type":"input_text","text":"hello"},
{"type":"input_image","image_url":"data:image/png;base64,AA=="}
]}],"text":{"format":{"type":"json_schema","name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}}}}}});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(
body["systemInstruction"]["parts"],
json!([{"text":"system"}])
);
assert_eq!(
body["contents"][0]["parts"],
json!([{"text":"hello"},{"inlineData":{"mimeType":"image/png","data":"AA=="}}])
);
assert_eq!(
body["generationConfig"],
json!({"responseMimeType":"application/json","responseSchema":request["text"]["format"]["schema"]})
);
}
@@ -4,3 +4,4 @@ mod codex;
mod events;
mod headers;
mod sse;
mod web_search;
@@ -0,0 +1,90 @@
//! 搜索路由与声明解析共用 Responses 工具选择语义
use gateway_protocol::openai::web_search::{SearchSelectionError, is_required, required_tool};
use serde_json::{Value, json};
#[test]
fn optional_or_mixed_tool_choices_do_not_require_search() {
let search = json!({"type":"web_search"});
let function = json!({"type":"function","name":"pwd"});
for choice in [
Value::Null,
json!("auto"),
json!("none"),
json!("required"),
function.clone(),
json!({"type":"allowed_tools","mode":"auto","tools":[search]}),
json!({"type":"allowed_tools","mode":"required","tools":[search,function]}),
json!({"type":"allowed_tools","mode":"required","tools":[]}),
] {
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()
));
}
#[test]
fn required_search_uses_the_original_selected_declaration() {
for kind in [
"web_search",
"web_search_preview",
"web_search_2025_08_26",
"web_search_preview_2025_03_11",
] {
let search = json!({"type":kind,"filters":{"allowed_domains":["example.org"]},"external_web_access":false});
for choice in [
json!("required"),
json!({"type":kind}),
json!({"type":"allowed_tools","mode":"required","tools":[{"type":kind}]}),
] {
let mut tools = vec![search.clone()];
if choice != "required" {
tools.push(json!({"type":"function","name":"pwd"}));
tools.push(json!({"type":if kind == "web_search" {"web_search_preview"} else {"web_search"}}));
}
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));
}
}
@@ -8,12 +8,12 @@ use gateway_core::{
operation::Operation,
};
use gateway_protocol::{
anthropic::{
ANTHROPIC_PROTOCOL, MessagesModelCapabilities, MessagesToResponsesStream,
responses_to_messages_request,
anthropic::{ANTHROPIC_PROTOCOL, MessagesToResponsesStream},
genai::{
GENAI_PROTOCOL, GenAiToMessagesStream, messages_to_genai_request,
responses_to_genai_request,
},
genai::{GENAI_PROTOCOL, GenAiToMessagesStream, messages_to_genai_request},
openai::OPENAI_PROTOCOL,
openai::{OPENAI_PROTOCOL, web_search},
};
use serde_json::{Value, json};
use std::borrow::Cow;
@@ -42,37 +42,28 @@ pub(super) fn prepare(
{
return Err(unsent(ProviderErrorKind::InvalidRequest));
}
let search = operation.requires_web_search();
let body = if search {
super::web_search::request(original)?
let search = if source == OPENAI_PROTOCOL {
web_search::required_tool(original)
.map_err(|error| ProviderError::invalid_request(error.message()).with_source(error))?
} else {
let mut messages = if source == OPENAI_PROTOCOL {
Cow::Owned(
responses_to_messages_request(
original,
&MessagesModelCapabilities {
hosted_web_search: Some(false),
..Default::default()
},
)
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?,
)
None
};
let body = if let Some(tool) = search {
super::web_search::request(original, tool)?
} else {
if source == OPENAI_PROTOCOL {
responses_to_genai_request(original)
} else {
Cow::Borrowed(original)
};
// Messages 的必填输出上限不能成为 GenAI 的隐式默认值
if source == OPENAI_PROTOCOL && !original.contains_key("max_output_tokens") {
messages.to_mut().remove("max_tokens");
messages_to_genai_request(original)
}
messages_to_genai_request(&messages)
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?
};
let model = original
.get("model")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let translator = if search {
let translator = if search.is_some() {
Translator::Search(Box::new(super::web_search::SearchResponse::new(original)))
} else {
Translator::Generate(Box::new(GenerationTranslator {
@@ -83,7 +74,7 @@ pub(super) fn prepare(
};
let mut context = payload.context().clone();
// Desktop 搜索使用完整 JSON,编码路径保留增量交付
context.insert("stream".into(), json!(!search));
context.insert("stream".into(), json!(search.is_none()));
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
let operation = operation
.replace_protocol_wire(None, context)
@@ -9,38 +9,16 @@ use gateway_core::{
use gateway_protocol::{
anthropic::MessagesToResponsesStream,
genai::{GenAiToMessagesStream, grounded_search_events},
openai::{OPENAI_PROTOCOL, web_search::is_search},
openai::{OPENAI_PROTOCOL, web_search},
};
use serde_json::{Map, Value, json};
use std::borrow::Cow;
pub(super) fn request(original: &Map<String, Value>) -> Result<Map<String, Value>, ProviderError> {
let choice = original.get("tool_choice").unwrap_or(&Value::Null);
let mut tools = original
.get("tools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|tool| {
is_search(tool)
&& (!is_search(choice) || choice["type"] == tool["type"])
&& (choice["type"] != "allowed_tools"
|| choice["tools"]
.as_array()
.is_some_and(|allowed| allowed.iter().any(|t| t["type"] == tool["type"])))
});
let tool = tools.next().ok_or_else(|| {
ProviderError::invalid_request("The selected web search tool must be declared.")
})?;
if tools.next().is_some() {
return Err(ProviderError::invalid_request(
"Select one web search declaration.",
));
}
if tool
.get("external_web_access")
.is_some_and(|v| !v.is_null() && v != true && v != "live")
{
pub(super) fn request(
original: &Map<String, Value>,
tool: &Value,
) -> Result<Map<String, Value>, ProviderError> {
if !web_search::allows_live_access(tool) {
return Err(ProviderError::invalid_request(
"Antigravity web search requires live external web access.",
));
@@ -618,7 +618,7 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
for (protocol, body) in [
(
"openai",
json!({"model":"fixture-model","input":"hello","max_output_tokens":100,"reasoning":{"effort":"none"},"text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}),
json!({"model":"fixture-model","input":"hello","max_output_tokens":100,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8,"tools":[{"type":"function","name":"pwd","parameters":{"type":"object"}}],"tool_choice":"required","text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}),
),
(
"anthropic",
@@ -669,7 +669,13 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
if protocol == "openai" {
assert_eq!(
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
0
24576
);
assert_eq!(body["request"]["generationConfig"]["temperature"], 0.3);
assert_eq!(body["request"]["generationConfig"]["topP"], 0.8);
assert_eq!(
body["request"]["toolConfig"]["functionCallingConfig"]["mode"],
"ANY"
);
assert_eq!(
body["request"]["generationConfig"]["responseSchema"],
@@ -700,6 +706,124 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
}
}
#[tokio::test]
async fn optional_search_preserves_functions_and_unspecified_output_limit() {
use gateway_core::{
engine::provider::ProviderRequest,
operation::{GenerateRequest, Operation, ProtocolPayload},
};
let upstream = MockServer::start().await;
Mock::given(path("/v1internal:streamGenerateContent"))
.and(body_partial_json(json!({"request":{"tools":[{"functionDeclarations":[{"name":"pwd"}]}]}})))
.respond_with(ResponseTemplate::new(200).set_body_raw(
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
"text/event-stream",
))
.expect(4).mount(&upstream).await;
let search = json!({"type":"web_search"});
let function = json!({"type":"function","name":"pwd","parameters":{"type":"object"}});
for choice in [
json!(null),
json!("auto"),
json!("required"),
json!({"type":"allowed_tools","mode":"required","tools":[search,function]}),
] {
let fixture = Fixture::new(&upstream.uri());
let mut body = json!({"model":"fixture-model","input":"hello","tools":[search,function],"tool_choice":choice});
if choice == "required" {
body["max_output_tokens"] = json!(null);
}
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let stream = fixture
.provider
.clone()
.execute(
ProviderRequest::new(operation, request(false).candidate().clone()),
context(frozen_profile(), CancellationToken::new()),
)
.await
.unwrap();
stream.try_collect::<Vec<_>>().await.unwrap();
released(&fixture).await;
}
for request in upstream.received_requests().await.unwrap() {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
assert!(
body["request"]["generationConfig"]
.get("maxOutputTokens")
.is_none()
);
assert!(
body["request"]["generationConfig"]
.get("thinkingConfig")
.is_none()
);
}
}
#[tokio::test]
async fn invalid_required_search_is_rejected_before_sending_and_releases_lease() {
use gateway_core::{
engine::provider::ProviderRequest,
operation::{GenerateRequest, Operation, ProtocolPayload},
};
let upstream = MockServer::start().await;
let fixture = Fixture::new(&upstream.uri());
{
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
let (_, bytes) = catalog.as_mut().unwrap();
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
value["webSearchModelIds"] = json!(["fixture-model"]);
*bytes = value.to_string().into();
}
let search = json!({"type":"web_search"});
for (tools, message) in [
(json!([]), "The selected web search tool must be declared."),
(
json!([search, search]),
"Select one web search declaration.",
),
(
json!([{"type":"web_search","external_web_access":false}]),
"Antigravity web search requires live external web access.",
),
(
json!([{"type":"web_search","external_web_access":"cached"}]),
"Antigravity web search requires live external web access.",
),
(
json!([{"type":"web_search","user_location":{"type":"approximate","country":"US"}}]),
"Antigravity cannot honor the specified web search options.",
),
] {
let body =
json!({"model":"fixture-model","input":"hello","tools":tools,"tool_choice":search});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let error = fixture
.provider
.clone()
.execute(
ProviderRequest::new(operation, request(false).candidate().clone()),
context(frozen_profile(), CancellationToken::new()),
)
.await
.err()
.expect("invalid search request");
assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert_eq!(
gateway_core::error::GatewayError::from_provider(&error).client_message(),
message
);
released(&fixture).await;
}
assert!(upstream.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
use gateway_core::{
@@ -74,7 +74,7 @@ impl CodexProvider {
.messages_model_capabilities(selected.lease.account(), &model)
.unwrap_or_default();
let mut body = responses_to_messages_request(original, &capabilities)
.map_err(|_| invalid_request())?;
.map_err(|error| invalid_request().with_source(error))?;
// Responses 的 HTTP JSON 和 SSE 共用事件输出,跨协议上游统一请求事件流
body.insert("stream".to_owned(), Value::Bool(true));
body
@@ -107,8 +107,8 @@ impl CodexProvider {
let mut source_context = generate.protocol_payload().context().clone();
retain_target_headers(source, &mut source_context, &mut headers);
let translator = translator::ResponsesResponseTranslator::new(original);
let mut translated =
messages_to_responses_request(original).map_err(|_| invalid_request())?;
let mut translated = messages_to_responses_request(original)
.map_err(|error| invalid_request().with_source(error))?;
if matches!(
selected.lease.authentication(),
CodexRuntimeAuthentication::OAuth(_)
@@ -28,11 +28,12 @@ impl NativeResponseTranslator for MessagesResponseTranslator {
event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Some(raw) = event.raw_json_body() {
let message: Value = serde_json::from_slice(raw).map_err(|_| protocol_error())?;
let message: Value =
serde_json::from_slice(raw).map_err(|error| protocol_error().with_source(error))?;
let event = self
.stream
.complete_json_event(&message)
.map_err(|_| protocol_error())?;
.map_err(|error| protocol_error().with_source(error))?;
return wire_events(OPENAI_PROTOCOL, vec![event]);
}
if !event.has_json_data() {
@@ -41,9 +42,11 @@ impl NativeResponseTranslator for MessagesResponseTranslator {
let events = self
.stream
.push(event.data())
.map_err(|_| protocol_error())?;
.map_err(|error| protocol_error().with_source(error))?;
if event.data().get("type").and_then(Value::as_str) == Some("message_stop") {
self.stream.finish().map_err(|_| protocol_error())?;
self.stream
.finish()
.map_err(|error| protocol_error().with_source(error))?;
}
wire_events(OPENAI_PROTOCOL, events)
}
@@ -73,15 +76,17 @@ impl NativeResponseTranslator for ResponsesResponseTranslator {
event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Some(raw) = event.raw_json_body() {
let response = serde_json::from_slice(raw).map_err(|_| protocol_error())?;
let response =
serde_json::from_slice(raw).map_err(|error| protocol_error().with_source(error))?;
let message = self
.stream
.complete_json(&response)
.map_err(|_| protocol_error())?;
let raw = serde_json::to_vec(&message).map_err(|_| protocol_error())?;
.map_err(|error| protocol_error().with_source(error))?;
let raw = serde_json::to_vec(&message)
.map_err(|error| protocol_error().with_source(error))?;
return Ok(vec![
ProtocolWireEvent::raw_json(ANTHROPIC_PROTOCOL, raw.into())
.map_err(|_| protocol_error())?,
.map_err(|error| protocol_error().with_source(error))?,
]);
}
if !event.has_json_data() {
@@ -90,12 +95,14 @@ impl NativeResponseTranslator for ResponsesResponseTranslator {
let events = self
.stream
.push(event.data())
.map_err(|_| protocol_error())?;
.map_err(|error| protocol_error().with_source(error))?;
if matches!(
event.data().get("type").and_then(Value::as_str),
Some("response.completed" | "response.incomplete")
) {
self.stream.finish().map_err(|_| protocol_error())?;
self.stream
.finish()
.map_err(|error| protocol_error().with_source(error))?;
}
wire_events(ANTHROPIC_PROTOCOL, events)
}
@@ -113,7 +120,7 @@ fn wire_events(
value.get("type").and_then(Value::as_str).map(str::to_owned),
value,
)
.map_err(|_| protocol_error())
.map_err(|error| protocol_error().with_source(error))
})
.collect()
}
@@ -1,6 +1,7 @@
//! Messages 原生 wire、跨协议头隔离和本地计数合同
mod affinity;
mod translator;
use super::*;
use gateway_core::event::ProviderResponseTimings;
@@ -0,0 +1,77 @@
//! 转换失败保留受限诊断原因,不改变发送状态或公共错误
use super::*;
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
use gateway_protocol::anthropic::TranslationError;
use std::error::Error as _;
#[tokio::test]
async fn response_translation_preserves_causes_in_both_directions() {
for (target, protocol, operation, message) in [
(
ApiKeyProtocol::Messages,
"anthropic",
generate_with_downstream_headers(),
"The Messages event type is missing.",
),
(
ApiKeyProtocol::Responses,
"openai",
messages_operation(true),
"The Responses event type is missing.",
),
] {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
seed(&store, &server, target).await;
let mut stream = provider(&store)
.execute(
planned_request("openai", operation),
context("req_translation_cause", CancellationToken::new()),
)
.await
.unwrap();
let wire =
ProtocolWireEvent::json(protocol, None, json!({"private":"PRIVATE_INPUT"})).unwrap();
let error = stream
.translate_native_response(ProviderEvent::wire(wire), false)
.unwrap_err();
assert_eq!(error.kind(), ProviderErrorKind::Protocol);
assert_eq!(error.send_state(), UpstreamSendState::Sent);
assert_eq!(
error.source().unwrap().downcast_ref::<TranslationError>(),
Some(&TranslationError::InvalidEvent(message))
);
assert!(error.error_details().unwrap().contains(message));
assert!(!format!("{error:?} {error}").contains(message));
assert!(!error.error_details().unwrap().contains("PRIVATE_INPUT"));
}
}
#[tokio::test]
async fn request_translation_preserves_the_unsent_validation_cause() {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
seed(&store, &server, ApiKeyProtocol::Messages).await;
let body = json!({"model":"gpt-5.4","input":"hello","tool_choice":{"type":"allowed_tools","mode":"required","tools":[]}});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let error = provider(&store)
.execute(
planned_request("openai", operation),
context("req_translation_validation", CancellationToken::new()),
)
.await
.err()
.expect("invalid allowed tools");
assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert_eq!(
error.source().unwrap().downcast_ref::<TranslationError>(),
Some(&TranslationError::InvalidRequest(
"Allowed tools must contain at least one tool."
))
);
assert!(server.received_requests().await.unwrap().is_empty());
}
+3 -1
View File
@@ -274,6 +274,8 @@ AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完
Antigravity 模型也可通过 `/v1/responses`、`/v1/chat/completions` 和 `/v1/messages` 调用,均支持 JSON 与 SSE。转换入口支持文本、内嵌图片/文档、函数工具及结果、生成参数和 JSON Schema;未知内容块返回请求错误,模型自身不支持的参数由上游校验。原生入口不经过转换器;常规生成与计数在出站时使用同一份 AGY 系统提示词配置,替换客户端系统指令,其余原生字段保持原始表达
Responses 转向 GenAI 时,输出上限、采样参数和 JSON Schema 直接映射;`max_output_tokens` 省略或为 `null` 时不补写输出上限。`reasoning.effort` 显式映射为推理预算,`none` 关闭推理,`auto` 使用动态预算,未指定时保留上游默认。生成参数不受 Messages 的默认输出上限、强制工具或无思考续轮规则影响,也不因推理设置省略采样参数;具体型号支持的预算与参数组合由上游校验
Responses 编码请求可以同时声明函数和可选的 `web_search`。AGY 向编码模型发送可用函数,保留 `tool_choice` 和 `allowed_tools` 的约束。显式选择搜索,或要求必须调用工具且只允许搜索时,网关取最后一条用户文本作为查询,向该账号目录的首个 `webSearchModelIds` 型号发送独立的实时搜索请求。账号及其授权分组须同时允许原型号与搜索型号
搜索支持 `filters.allowed_domains` 和 `filters.blocked_domains`。强制搜索遇到缓存模式、无法满足的搜索选项或缺少可用搜索型号时返回请求错误。JSON 与 SSE 均按上游实际查询与来源返回 `web_search_call` 和正文引用;传入 `include: ["web_search_call.action.sources"]` 可读取搜索来源列表
@@ -428,7 +430,7 @@ Responses 的 `allowed_tools` 只向 Messages 上游声明本轮允许的工具
强制工具与手动推理冲突时显式关闭推理;紧接着只回传工具结果且未指定 effort 时,沿用无思考模式。
adaptive 路径将普通强制选择降为 `auto`,保留串行约束。
仅设置 `parallel_tool_calls:false` 也会生成串行工具选择,`none` 不携带并行选项。
生成启用推理的配置时省略不相容的 `temperature/top_p`,同协议不执行这些转换
转向 Messages 并启用推理时省略不相容的 `temperature/top_p`,同协议不执行这些转换
服务档位按目标协议映射:Responses `default` 对应 Messages `standard_only`,`auto` 保留,无法对应的档位省略。
按 CPA 将 Responses `priority` 与 Messages `speed:fast` 双向映射;这两个字段不代表相同的服务承诺。
+3 -1
View File
@@ -512,6 +512,8 @@ Messages 与 Responses 的映射、忽略和降级规则参考 CPA,
同语义字段交给目标上游校验;结构解码或必要流状态失败按协议错误终结,不补造成功结果。
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。Core 用其判定路由,协议转换复用声明解析,Provider 负责账号可用的搜索模型和目标上游支持的选项。需要独立搜索转换时必须对应唯一声明,缺失或歧义按请求错误处理,不退回普通生成
Images 与 standalone Search 是 OpenAI Provider 自有端点:两者都不参与文本模型映射,只在 Client Key
的账号范围确实包含 Codex 账号时生成单一 OpenAI 候选。Images 的图片模型由 Provider 从正文旁路
提取,用于账号模型政策检查,并在中间件改写后复验当前租约账号;不要求图片模型进入文本目录。
@@ -578,7 +580,7 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 和 Messages 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 复用已有 Messages 转换能力,Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则
Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 复用 Messages 的内容与工具映射,生成参数直接映射到 GenAI,不继承 Messages 的默认值与模型限制;Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则
Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属