fix(protocol): preserve tool semantics across Chat and Codex (#844)

Support named independent tool outputs and flatten custom grammar formats.
Adapt Codex search aliases, long call IDs and tool names while preserving
history pairing and restoring client-visible names in JSON and SSE.

Refs #843

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-12-04 14:13:31 +08:00
committed by GitHub
co-authored by Zyy Codex
parent 5ed8b626d7
commit dd793a84ab
15 changed files with 612 additions and 49 deletions
@@ -262,7 +262,8 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
{"role":"developer","content":"brief"},
{"role":"system","content":null},
{"role":"assistant","tool_calls":[]},
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]);
let response = fixture.post(request.clone()).await;
assert_eq!(response.status(), StatusCode::OK);
@@ -59,11 +59,13 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
}
}
if role == "tool" {
string(
message.get("tool_call_id"),
&format!("{path}.tool_call_id"),
false,
)?;
// Responses 的独立工具输出通过名称标识,不依赖前序调用
let field = if message.get("tool_call_id").is_none_or(Value::is_null) {
"name"
} else {
"tool_call_id"
};
string(message.get(field), &format!("{path}.{field}"), false)?;
} else if message
.get("tool_call_id")
.is_some_and(|v| !v.is_null() && v != "")
@@ -166,12 +166,7 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
let mut message = object(value, &path)?;
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
if role == "tool" {
let call_id = required_string(
&mut message,
"tool_call_id",
&format!("{path}.tool_call_id"),
false,
)?;
let call_id = optional(&mut message, "tool_call_id");
let content_path = format!("{path}.content");
let content = required(&mut message, "content", &content_path)?;
let output = if content.is_string() {
@@ -179,15 +174,24 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
} else {
content_parts(content, &role, &content_path, false)?.into()
};
let kind = if custom_calls.contains(&call_id) {
let kind = if call_id
.as_ref()
.and_then(Value::as_str)
.is_some_and(|id| custom_calls.contains(id))
{
"custom_tool_call_output"
} else {
"function_call_output"
};
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
string(&name, &format!("{path}.name"), true)?;
item["name"] = name;
let mut item = json!({"type": kind, "output": output});
if let Some(call_id) = call_id {
item["call_id"] = call_id;
}
for field in ["name", "namespace"] {
if let Some(value) = optional(&mut message, field).filter(|value| value != "") {
string(&value, &format!("{path}.{field}"), true)?;
item[field] = value;
}
}
input.push(item);
continue;
@@ -377,12 +381,13 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.into_iter()
.enumerate()
.map(|(index, value)| {
let path = format!("tools[{index}]");
let mut path = format!("tools[{index}]");
let mut tool = object(value, &path)?;
let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?;
if matches!(kind.as_str(), "function" | "custom") {
if let Some(nested) = optional(&mut tool, &kind) {
tool = object(nested, &format!("{path}.{kind}"))?;
path = format!("{path}.{kind}");
tool = object(nested, &path)?;
}
if tool.get("description") == Some(&Value::Null) {
tool.remove("description");
@@ -395,6 +400,14 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
tool.insert("strict".into(), false.into());
}
} else if let Some(format) = tool.get_mut("format").and_then(Value::as_object_mut)
&& format.get("type").and_then(Value::as_str) == Some("grammar")
&& let Some(grammar) = optional(format, "grammar")
{
// Chat 将语法嵌套在 grammar,Responses 使用同层的 syntax 和 definition
let grammar = object(grammar, &format!("{path}.format.grammar"))?;
format.extend(grammar);
format.insert("type".into(), "grammar".into());
}
}
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
@@ -63,14 +63,48 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
#[test]
fn invalid_tool_history_reports_source_path() {
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]});
assert_eq!(
parse_request(&serde_json::to_vec(&request).unwrap())
.err()
for (identity, parameter) in [
(json!({}), "messages[0].name"),
(json!({"name":null}), "messages[0].name"),
(json!({"name":" "}), "messages[0].name"),
(json!({"name":17}), "messages[0].name"),
(
json!({"name":"notifications","tool_call_id":""}),
"messages[0].tool_call_id",
),
(
json!({"name":"notifications","tool_call_id":17}),
"messages[0].tool_call_id",
),
] {
let mut message = json!({"role":"tool","content":"ok"});
message
.as_object_mut()
.unwrap()
.parameter(),
Some("messages[0].tool_call_id")
);
.extend(identity.as_object().unwrap().clone());
let request = json!({"model":"m","messages":[message]});
let error = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap_err();
assert_eq!(error.parameter(), Some(parameter));
}
}
#[test]
fn named_tool_outputs_preserve_the_original_request_and_target_requirements() {
let request = json!({"model":"m","messages":[
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]});
let parsed = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap();
assert_eq!(&parsed, request.as_object().unwrap());
assert!(responses::convert_request(&parsed).is_ok());
for result in [
messages::convert_request(&parsed, &Default::default()),
genai::convert_request(&parsed),
] {
assert_eq!(
result.unwrap_err().parameter(),
Some("messages[0].tool_call_id")
);
}
}
#[test]
@@ -472,11 +506,14 @@ fn all_targets_apply_the_same_common_request_validation() {
#[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),
for (format, expected) in [
(json!(null), json!(null)),
(json!({"type":"text"}), json!({"type":"text"})),
(
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
json!({"type":"grammar","syntax":"lark","definition":"PRIVATE_GRAMMAR"}),
),
(json!(17), json!(17)),
] {
let mut body = super::request();
body.insert(
@@ -484,7 +521,7 @@ fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
json!([{"type":"custom","custom":{"name":"run","format":format}}]),
);
let responses = responses::convert_request(&body).unwrap();
assert_eq!(responses["tools"][0]["format"], format);
assert_eq!(responses["tools"][0]["format"], expected);
for result in [
messages::convert_request(&body, &Default::default()),
genai::convert_request(&body),
@@ -53,6 +53,31 @@ fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
assert!(converted.get("previous_response_id").is_none());
}
#[test]
fn named_tool_outputs_preserve_unpaired_identity_and_order() {
for call_id in [None, Some(Value::Null)] {
let mut notice = json!({"role":"tool","name":"lookup","namespace":"agent","content":[{"type":"text","text":"independent notice"}]});
if let Some(call_id) = call_id {
notice["tool_call_id"] = call_id;
}
let converted = convert(json!({"model":"model-a","messages":[
{"role":"assistant","tool_calls":[{"id":"call_lookup","type":"custom","custom":{"name":"lookup","input":"query"}}]},
notice,
{"role":"tool","tool_call_id":"call_lookup","content":"matched result"},
{"role":"tool","name":"notifications","content":"another notice"}
]}));
assert_eq!(
converted["input"],
json!([
{"type":"custom_tool_call","call_id":"call_lookup","name":"lookup","input":"query"},
{"type":"function_call_output","name":"lookup","namespace":"agent","output":[{"type":"input_text","text":"independent notice"}]},
{"type":"custom_tool_call_output","call_id":"call_lookup","output":"matched result"},
{"type":"function_call_output","name":"notifications","output":"another notice"}
])
);
}
}
#[test]
fn web_search_options_require_a_hosted_search_and_flatten_location() {
for (options, expected) in [
@@ -278,7 +303,7 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
]}));
assert_eq!(
converted["tools"][0],
json!({"type":"custom", "name":"patch", "format":schema})
json!({"type":"custom", "name":"patch", "format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}})
);
assert_eq!(
converted["tool_choice"],
@@ -293,6 +318,40 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
assert_eq!(converted["input"][5]["type"], "function_call_output");
}
#[test]
fn custom_grammar_formats_keep_their_constraints_and_source_paths() {
for nested in [false, true] {
for syntax in ["lark", "regex"] {
let format =
json!({"type":"grammar","syntax":syntax,"definition":"OK","future_field":true});
let definition = json!({"name":"probe","format":format});
let tool = if nested {
json!({"type":"custom","custom":definition})
} else {
json!({"type":"custom","name":"probe","format":format})
};
let mut body =
json!({"model":"m","messages":[{"role":"user","content":"hello"}],"tools":[tool]});
assert_eq!(convert(body.clone())["tools"][0]["format"], format);
let declaration = if nested {
&mut body["tools"][0]["custom"]
} else {
&mut body["tools"][0]
};
declaration["format"] = json!({"type":"grammar","grammar":false});
let error = convert_request(body.as_object().unwrap()).unwrap_err();
assert_eq!(
error.parameter(),
Some(if nested {
"tools[0].custom.format.grammar"
} else {
"tools[0].format.grammar"
})
);
}
}
}
#[test]
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
for file in [
@@ -1,9 +1,147 @@
//! Chat 转换的目标档位与 fast 协议头适配
//! Chat 转换的目标档位、工具标识与 fast 协议头适配
use std::collections::{HashMap, HashSet};
use bytes::Bytes;
use gateway_core::engine::middleware::MiddlewareHeader;
use reqwest::header::HeaderMap;
use serde_json::{Map, Value};
use sha2::{Digest as _, Sha256};
/// 名称映射只属于本次 Chat 响应,历史调用 ID 在出站副本中保持成对关联
pub(crate) fn normalize_translated_codex_tools(
body: &mut Map<String, Value>,
) -> HashMap<String, String> {
let mut fields = Vec::new();
for (field, value) in body.iter_mut() {
match field.as_str() {
"tools" | "input" => {
if let Some(items) = value.as_array_mut() {
for item in items {
collect_tool_names(item, &mut fields);
}
}
}
"tool_choice" => collect_tool_names(value, &mut fields),
_ => {}
}
}
// 先预留所有原名,避免别名抢占后面声明的合法名称
let mut used = fields
.iter()
.filter_map(|value| value.as_str())
.map(str::to_owned)
.collect();
let mut names = HashMap::new();
for field in fields {
let Some(name) = field.as_str() else { continue };
if name.is_empty()
|| name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
continue;
}
let alias = names.entry(name.to_owned()).or_insert_with(|| {
let base: String = name
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-') {
ch
} else {
'_'
}
})
.collect();
unique_tool_alias(&base, &mut used)
});
*field = Value::String(alias.clone());
}
if let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) {
let mut used = input
.iter()
.filter_map(|item| item.get("call_id").and_then(Value::as_str))
.map(str::to_owned)
.collect();
let mut ids = HashMap::new();
for item in input.iter().filter(|item| {
matches!(
item.get("type").and_then(Value::as_str),
Some("function_call" | "custom_tool_call")
)
}) {
let Some(id) = item
.get("call_id")
.and_then(Value::as_str)
.filter(|id| id.chars().count() > 64)
else {
continue;
};
ids.entry(id.to_owned()).or_insert_with(|| {
let digest = hex::encode(Sha256::digest(id.as_bytes()));
unique_tool_alias(&format!("call_{digest}"), &mut used)
});
}
for item in input {
if matches!(
item.get("type").and_then(Value::as_str),
Some(
"function_call"
| "custom_tool_call"
| "function_call_output"
| "custom_tool_call_output"
)
) && let Some(alias) = item
.get("call_id")
.and_then(Value::as_str)
.and_then(|id| ids.get(id))
{
item["call_id"] = alias.clone().into();
}
}
}
names
.into_iter()
.map(|(name, alias)| (alias, name))
.collect()
}
fn collect_tool_names<'a>(tool: &'a mut Value, names: &mut Vec<&'a mut Value>) {
match tool.get("type").and_then(Value::as_str) {
Some(
"function"
| "custom"
| "function_call"
| "custom_tool_call"
| "function_call_output"
| "custom_tool_call_output",
) => {
if let Some(name) = tool.get_mut("name") {
names.push(name);
}
}
Some("namespace" | "allowed_tools" | "additional_tools" | "tool_search_output") => {
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
for tool in tools {
collect_tool_names(tool, names);
}
}
}
_ => {}
}
}
fn unique_tool_alias(base: &str, used: &mut HashSet<String>) -> String {
// 调用方只传入 ASCII 名称或十六进制摘要,可按字节截取 Codex 标识上限
let mut candidate = base[..base.len().min(64)].to_owned();
let mut index = 0;
while !used.insert(candidate.clone()) {
index += 1;
let suffix = format!("_{index}");
candidate = format!("{}{suffix}", &base[..base.len().min(64 - suffix.len())]);
}
candidate
}
pub(crate) fn normalize_translated_codex_service_tier(body: &mut Map<String, Value>) {
// 转换生成的默认档位沿用 Codex 客户端的省略表达,原生 Responses 保留调用方声明
@@ -10,7 +10,10 @@ 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 chat::{
add_translated_fast_beta, normalize_translated_codex_service_tier,
normalize_translated_codex_tools,
};
pub(crate) use headers::is_non_codex_request_header;
pub(crate) use request::normalize_codex_request_body;
pub(crate) use search_tools::declares_hosted_search;
@@ -8,6 +8,7 @@ use serde_json::{Map, Value, json};
/// 只处理已验证被拒绝的字段,不根据客户端品牌推断整份历史是否合法
pub(super) fn normalize_non_codex_request_body(body: &mut Map<String, Value>) {
normalize_codex_oauth_options(body);
super::search_tools::normalize_search_tool_aliases(body);
let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) else {
return;
};
@@ -1,7 +1,39 @@
//! 识别普通与 Responses Lite 请求中的托管搜索声明,不改写工具配置
//! 识别托管搜索声明并适配 Codex 的搜索工具名称
use serde_json::{Map, Value};
pub(super) fn normalize_search_tool_aliases(body: &mut Map<String, Value>) {
for (field, value) in body {
match field.as_str() {
"tools" | "input" => {
if let Some(items) = value.as_array_mut() {
for item in items {
normalize_search_tool(item);
}
}
}
"tool_choice" => normalize_search_tool(value),
_ => {}
}
}
}
fn normalize_search_tool(tool: &mut Value) {
match tool.get("type").and_then(Value::as_str) {
Some("web_search_preview" | "web_search_preview_2025_03_11") => {
tool["type"] = "web_search".into();
}
Some("allowed_tools" | "additional_tools" | "tool_search_output" | "namespace") => {
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
for tool in tools {
normalize_search_tool(tool);
}
}
}
_ => {}
}
}
pub(crate) fn declares_hosted_search(body: &Map<String, Value>) -> bool {
body.get("tools")
.and_then(Value::as_array)
@@ -38,7 +38,7 @@ impl CodexProvider {
};
let mut source_context = generate.protocol_payload().context().clone();
let target = selected.lease.authentication().api_protocol();
let translator = response::ChatResponseTranslator::new(target, identity, original);
let mut translator = response::ChatResponseTranslator::new(target, identity, original);
match target {
ApiKeyProtocol::Messages => {
let capabilities = self
@@ -82,6 +82,8 @@ impl CodexProvider {
CodexRuntimeAuthentication::OAuth(_)
) {
crate::compat::normalize_translated_codex_service_tier(&mut body);
translator.tool_names =
crate::compat::normalize_translated_codex_tools(&mut body);
}
let body = serde_json::to_vec(&body).map_err(|_| request_error())?;
let operation = operation
@@ -1,5 +1,7 @@
//! 单次响应直接映射为 Chat wire,原生观测与资源释放归现有执行链
use std::collections::HashMap;
use super::*;
use gateway_core::engine::provider::NativeResponseTranslator;
use gateway_protocol::{
@@ -20,6 +22,7 @@ pub(super) struct ChatResponseTranslator {
complete_json: bool,
streaming: bool,
include_usage: bool,
pub(super) tool_names: HashMap<String, String>,
}
impl ChatResponseTranslator {
@@ -54,6 +57,7 @@ impl ChatResponseTranslator {
complete_json: false,
streaming: request.get("stream").and_then(Value::as_bool) == Some(true),
include_usage,
tool_names: Default::default(),
}
}
}
@@ -79,7 +83,7 @@ impl NativeResponseTranslator for ChatResponseTranslator {
}
if let Some(raw) = event.raw_json_body() {
let body = serde_json::from_slice(raw).map_err(|_| response_error())?;
let response = match self.encoder {
let mut response = match self.encoder {
Encoder::Responses(_) => responses::project_response(&body, &self.identity),
Encoder::Messages(_) => {
messages::project_response_with_request(&body, &self.identity, &self.request)
@@ -94,8 +98,10 @@ impl NativeResponseTranslator for ChatResponseTranslator {
self.include_usage,
)
.map_err(map_error)?,
&self.tool_names,
);
}
restore_tool_names(&mut response, &self.tool_names);
return ProtocolWireEvent::raw_json(
CHAT_PROTOCOL,
serde_json::to_vec(&response)
@@ -113,7 +119,7 @@ impl NativeResponseTranslator for ChatResponseTranslator {
Encoder::Messages(encoder) => encoder.push_event(event.event_type(), event.data()),
}
.map_err(map_error)?;
wire_events(chunks)
wire_events(chunks, &self.tool_names)
}
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
@@ -125,19 +131,52 @@ impl NativeResponseTranslator for ChatResponseTranslator {
Encoder::Messages(encoder) => encoder.finish(),
}
.map_err(map_error)?;
wire_events(chunks)
wire_events(chunks, &self.tool_names)
}
}
fn wire_events(chunks: Vec<Value>) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
fn wire_events(
chunks: Vec<Value>,
names: &HashMap<String, String>,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
chunks
.into_iter()
.map(|chunk| {
.map(|mut chunk| {
restore_tool_names(&mut chunk, names);
ProtocolWireEvent::json(CHAT_PROTOCOL, None, chunk).map_err(|_| response_error())
})
.collect()
}
fn restore_tool_names(response: &mut Value, names: &HashMap<String, String>) {
if names.is_empty() {
return;
}
let Some(choices) = response.get_mut("choices").and_then(Value::as_array_mut) else {
return;
};
for choice in choices {
for field in ["message", "delta"] {
let Some(calls) = choice
.get_mut(field)
.and_then(|message| message.get_mut("tool_calls"))
.and_then(Value::as_array_mut)
else {
continue;
};
for call in calls {
for kind in ["function", "custom"] {
if let Some(name) = call.get_mut(kind).and_then(|tool| tool.get_mut("name"))
&& let Some(original) = name.as_str().and_then(|name| names.get(name))
{
*name = original.clone().into();
}
}
}
}
}
}
fn map_error(error: ChatError) -> ProviderError {
response_error().with_source(error)
}
@@ -0,0 +1,207 @@
//! 验证 Chat 工具别名经实际出站、流式与 JSON 响应保持名称和调用关联
use super::*;
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
use gateway_protocol::chat_completions::ChatAccumulator;
use sha2::{Digest as _, Sha256};
#[tokio::test]
async fn chat_tool_aliases_preserve_pairing_names_and_account_boundaries() {
let long_id = format!("call_{}", "x".repeat(80));
let mut collision_id = format!("call_{}", hex::encode(Sha256::digest(long_id.as_bytes())));
collision_id.truncate(64);
let long_custom_id = "调用".repeat(40);
let long_name = format!("tool_{}", "x".repeat(80));
let arguments = json!({"tool_name":"mcp.server/tool","call_id":long_id}).to_string();
let schema = json!({"type":"object","properties":{"mcp.server/tool":{"type":"string"}}});
for api_key in [false, true] {
for streaming in [false, true] {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
if api_key {
store
.seed_api_key(
"acct_provider_contract",
server.uri(),
provider_openai::credential::ResponsesTransport::Http,
)
.await;
} else {
create_account(&store, "acct_provider_contract").await;
}
Mock::given(method("POST"))
.and(path(if api_key { "/responses" } else { "/codex/responses" }))
.respond_with(|request: &wiremock::Request| {
let body = captured_request_body(request);
let output = json!([
{"type":"function_call","id":"fc_new","call_id":"call_new","name":body["tools"][0]["name"],"arguments":"{}","status":"completed"},
{"type":"custom_tool_call","id":"ctc_new","call_id":"custom_new","name":body["tools"][2]["name"],"input":"raw input","status":"completed"}
]);
let mut events = vec![json!({"type":"response.created","response":{"id":"r_tools","model":"gpt-5.4","status":"in_progress"}})];
for (index, item) in output.as_array().unwrap().iter().enumerate() {
events.push(json!({"type":"response.output_item.added","output_index":index,"item":item}));
events.push(json!({"type":"response.output_item.done","output_index":index,"item":item}));
}
events.push(json!({"type":"response.completed","response":{
"id":"r_tools","model":"gpt-5.4","status":"completed","output":output,
"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
}}));
let sse = events.iter().map(|event| format!("data: {event}\n\n")).collect::<String>();
ResponseTemplate::new(200).set_body_raw(sse, "text/event-stream")
})
.expect(1)
.mount(&server).await;
let body = json!({
"model":"gpt-5.4","stream":streaming,
"tools":[
{"type":"function","function":{"name":"mcp.server/tool","parameters":schema}},
{"type":"function","function":{"name":"mcp_server_tool"}},
{"type":"custom","custom":{"name":"mcp/server/tool"}},
{"type":"function","function":{"name":long_name}}
],
"tool_choice":{"type":"allowed_tools","allowed_tools":{"mode":"auto","tools":[
{"type":"function","function":{"name":"mcp.server/tool"}},
{"type":"custom","custom":{"name":"mcp/server/tool"}}
]}},
"messages":[
{"role":"assistant","tool_calls":[
{"type":"function","id":long_id,"function":{"name":"mcp.server/tool","arguments":arguments}},
{"type":"function","id":collision_id,"function":{"name":"mcp_server_tool","arguments":"{}"}},
{"type":"custom","id":long_custom_id,"custom":{"name":"mcp/server/tool","input":"raw history"}}
]},
{"role":"tool","tool_call_id":long_id,"content":"first"},
{"role":"tool","tool_call_id":collision_id,"content":"second"},
{"role":"tool","tool_call_id":long_custom_id,"content":"third"},
{"role":"tool","name":"mcp.server/tool","namespace":"agent","content":"independent"},
{"role":"user","content":"continue"}
]
});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
.unwrap()
.with_context(Map::from_iter([("use_websocket".into(), json!(false))])),
));
let mut stream = provider_with_base_url(&store, server.uri())
.execute(
planned_request("openai", operation),
context("req_chat_tools", CancellationToken::new()),
)
.await
.unwrap();
let mut accumulator = ChatAccumulator::default();
while let Some(event) = stream.next().await {
let event = event.unwrap();
let terminal = event
.canonical_facts()
.iter()
.any(|fact| matches!(fact, GatewayEvent::Completed(_)));
for event in stream.translate_native_response(event, terminal).unwrap() {
if let Some(wire) = event.wire_event() {
accumulator.push(wire.data()).unwrap();
}
}
}
let result = accumulator.finish().unwrap();
assert_eq!(
result["choices"][0]["message"]["tool_calls"][0]["function"]["name"],
"mcp.server/tool"
);
assert_eq!(
result["choices"][0]["message"]["tool_calls"][1]["custom"]["name"],
"mcp/server/tool"
);
assert_eq!(
result["choices"][0]["message"]["tool_calls"][1]["custom"]["input"],
"raw input"
);
let requests = server.received_requests().await.unwrap();
let sent = captured_request_body(&requests[0]);
assert_eq!(sent["tools"][0]["parameters"], schema);
assert_eq!(sent["input"][0]["arguments"], arguments);
assert_eq!(sent["input"][6]["namespace"], "agent");
assert!(sent["input"][6].get("call_id").is_none());
let ids = [&long_id, &collision_id, &long_custom_id];
let mut distinct_ids = BTreeSet::new();
let mut distinct_names = BTreeSet::new();
for (index, original_id) in ids.into_iter().enumerate() {
let id = sent["input"][index]["call_id"].as_str().unwrap();
assert_eq!(id, sent["input"][index + 3]["call_id"]);
assert!(distinct_ids.insert(id));
let name = sent["tools"][index]["name"].as_str().unwrap();
assert_eq!(name, sent["input"][index]["name"]);
assert!(distinct_names.insert(name));
if api_key || index == 1 {
assert_eq!(id, original_id);
} else {
assert!(id.len() <= 64);
assert_ne!(id, original_id);
}
if !api_key {
assert!(name.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')));
}
}
assert_eq!(sent["input"][6]["name"], sent["tools"][0]["name"]);
assert_eq!(
sent["tool_choice"]["tools"][0]["name"],
sent["tools"][0]["name"]
);
assert_eq!(
sent["tool_choice"]["tools"][1]["name"],
sent["tools"][2]["name"]
);
assert_eq!(sent["tools"][1]["name"], "mcp_server_tool");
assert_eq!(sent["tools"][3]["name"], long_name);
server.verify().await;
}
}
}
#[tokio::test]
async fn complete_json_restores_oauth_tool_names_for_each_chat_delivery() {
for streaming in [false, true] {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_provider_contract").await;
let request = json!({"model":"gpt-5.4","stream":streaming,"messages":[{"role":"user","content":"hello"}],
"tools":[{"type":"function","function":{"name":"工具.lookup"}}]});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("chat_completions", request.as_object().unwrap().clone())
.unwrap(),
));
let mut stream = provider_with_base_url(&store, server.uri())
.execute(
planned_request("openai", operation),
context("req_tool_json", CancellationToken::new()),
)
.await
.unwrap();
let response = json!({"id":"r","object":"response","model":"gpt-5.4","status":"completed",
"output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"___lookup","arguments":"{}"}],
"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}});
let wire =
ProtocolWireEvent::raw_json("openai", serde_json::to_vec(&response).unwrap().into())
.unwrap();
let events = stream
.translate_native_response(ProviderEvent::wire(wire), true)
.unwrap();
let mut accumulator = ChatAccumulator::default();
for wire in events.iter().filter_map(|event| event.wire_event()) {
if let Some(raw) = wire.raw_json_body() {
let result: Value = serde_json::from_slice(raw).unwrap();
assert_eq!(
result["choices"][0]["message"]["tool_calls"][0]["function"]["name"],
"工具.lookup"
);
} else {
accumulator.push(wire.data()).unwrap();
}
}
if streaming {
let result = accumulator.finish().unwrap();
assert_eq!(
result["choices"][0]["message"]["tool_calls"][0]["function"]["name"],
"工具.lookup"
);
}
}
}
@@ -5,6 +5,7 @@ mod account_isolation;
mod cache_preference;
mod capacity;
mod catalog_startup;
mod chat_tools;
mod cookies;
mod correlation;
mod error_details;
@@ -112,8 +112,13 @@ async fn search_history_preserves_existing_tools_and_explicit_choices() {
}
#[tokio::test]
async fn search_history_keeps_existing_search_declarations_in_all_supported_locations() {
for kind in ["web_search", "web_search_preview"] {
async fn search_history_preserves_options_and_adapts_known_search_aliases() {
for (kind, codex_kind) in [
("web_search", "web_search"),
("web_search_preview", "web_search"),
("web_search_preview_2025_03_11", "web_search"),
("web_search_preview_future", "web_search_preview_future"),
] {
for location in ["top", "additional_tools", "tool_search_output"] {
let mut original = search_request();
let tool = json!({"type":kind,"external_web_access":true,"search_context_size":"high"});
@@ -127,8 +132,25 @@ async fn search_history_keeps_existing_search_declarations_in_all_supported_loca
}),
);
}
let actual = capture_downstream_request(original.clone(), false, false, true).await;
assert_request_fields(&actual, &original);
original["tool_choice"] =
json!({"type":"allowed_tools","mode":"auto","tools":[{"type":kind}]});
for api_key in [false, true] {
for websocket in [false, true] {
let mut expected = original.clone();
if !api_key {
if location == "top" {
expected["tools"][0]["type"] = codex_kind.into();
} else {
expected["input"][0]["tools"][0]["type"] = codex_kind.into();
}
expected["tool_choice"]["tools"][0]["type"] = codex_kind.into();
}
let actual =
capture_downstream_request(original.clone(), api_key, websocket, true)
.await;
assert_request_fields(&actual, &expected);
}
}
}
}
}
+9 -3
View File
@@ -336,9 +336,9 @@ print(completion.choices[0].message.content)
| `file` 内容块 | `file.file_id`、`file.file_data`、`file.file_url` 至少提供一种,保留可选 `filename`;URL 和非 PDF 文件为网关的 Responses 扩展,实际支持由上游判断 |
| `input_audio` 内容块 | Chat 的 `data` 和 `format` 转为 Responses `audio_url` data URL;原生音频引用与 `input_text`、`input_image`、`input_file` 内容块也可携带 |
| `messages[].refusal`、assistant 的 `refusal` 内容块 | 保留 assistant 拒绝历史,各角色消息的 `refusal: ""` 按缺省处理 |
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果,保留 ID、参数或输入字符串。空调用列表按缺省处理。tool 必须携带调用 ID 和结果,其他角色忽略空 ID。custom 结果须携带前序调用历史 |
| `messages[].name` | Responses 将 tool 消息的非空字符串名称随结果携带。Messages 和 GenAI 通过调用 ID 匹配历史。其他角色的名称作为辅助信息忽略 |
| `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象。function 的 `parameters: null` 按省略处理,`strict` 省略或为 `null` 时使用 `false` |
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果,保留 ID、参数或输入字符串。空调用列表按缺省处理。tool 必须携带结果;Responses 目标允许调用 ID 缺省或为 `null` 的独立工具输出,此时必须提供非空 `name`,不推断配对或丢弃内容。显式空 ID 仍返回 `400`,其他角色忽略空 ID。custom 结果须携带前序调用历史 |
| `messages[].name`、`messages[].namespace` | Responses 将 tool 消息的非空字符串名称和命名空间随结果携带。Messages 和 GenAI 仍要求调用 ID 并匹配历史,不支持无 ID 的独立输出。其他角色的名称和命名空间作为辅助信息忽略 |
| `tools` | 展开 function/custom 定义,保留 schema 及原生工具对象。custom 的 `format.grammar` 展开为 Responses 的 `format.syntax` 和 `format.definition`。function 的 `parameters: null` 按省略处理,`strict` 省略或为 `null` 时使用 `false` |
| `tool_choice`、`parallel_tool_calls` | 展开指定 function/custom 和 `allowed_tools` 选择;原生选择与并行布尔值交给上游 |
| `web_search_options` | `{}` 即要求上游执行 `web_search`;支持 `search_context_size` 与 `user_location.approximate` |
| `response_format` | 非 `null` 时优先于 `text.format`,保留 JSON Schema;未知格式交给 Responses 上游 |
@@ -355,6 +355,11 @@ print(completion.choices[0].message.content)
`seed`、`frequency_penalty`、`presence_penalty`、`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
消息的 `reasoning_content` 和 `reasoning` 作为辅助历史忽略,不转为用户正文
Chat 发往 Codex/OAuth 时,包含 `[A-Za-z0-9_-]` 以外字符的工具名称转换为无冲突别名,
工具声明、选择和历史使用同一映射,JSON 与 SSE 响应还原客户端名称。
历史调用 ID 超过 64 字符时,调用和对应结果使用同一短 ID;名称与 ID 映射仅限当前请求,
工具参数和结果正文保持原值
`n`、`store`、`background`、`modalities` 和 `functions` 可省略或为 `null`。非空值仅接受 `n: 1`、`store: false`、`background: false`、`modalities: ["text"]` 和 `functions: []`。
网关拒绝 `function_call`、`function` 消息角色、音频输出和无法映射的内容类型。
入口不接收 `input`、`previous_response_id` 或 `conversation`;需要服务端续接时使用 `/v1/responses`
@@ -612,6 +617,7 @@ WS 握手的轮次元数据头只随首次请求转发,后续帧在正文中
| `top_p`、`frequency_penalty`、`presence_penalty`、`chat_template_kwargs`、`user`、`metadata`、`safety_identifier` | 省略;采样参数取默认值时也省略 |
| `stream_options.include_usage` | 省略该成员,保留其他流式选项 |
| `truncation`、`stop_sequences`、`prompt_cache_options` | 分别仅在值为 `"disabled"`、`[]`、`{}` 时省略;显式策略交给上游校验 |
| 搜索工具声明与 `tool_choice` | `web_search_preview`、`web_search_preview_2025_03_11` 映射为 `web_search`,保留搜索选项;同样适用于 `additional_tools`、`tool_search_output` 和 `allowed_tools` 中的声明 |
选定 Codex/OAuth 上游后,HTTP 和 WebSocket 按相同规则处理 `input` 中的回放条目,适用于所有 User-Agent。API Key 上游保留这些历史字段