mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-03 08:01:10 +00:00
fix(protocol): handle empty Chat history and nullable request fields
Treat explicit null text as empty in Chat content blocks and preserve user input, tool results, and cache breakpoints during conversion. Resolve nullable format and reasoning controls consistently with routing, and forward stop sequences to Messages and GenAI. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -256,12 +256,20 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
let mut request = chat_request(false);
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
request["messages"] = json!([
|
||||
{"role":"developer","content":"brief"},
|
||||
{"role":"system","content":null},
|
||||
{"role":"assistant","tool_calls":[]},
|
||||
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
|
||||
]);
|
||||
let response = fixture.post(request.clone()).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||
assert_eq!(observed.as_slice(), [request]);
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
validate_request(chat)?;
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(parts(instructions, "instructions", true)?);
|
||||
system.extend(parts(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
system.extend(parts(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
let mut text = Vec::new();
|
||||
let mut media = Vec::new();
|
||||
for part in parts(&message["content"], &format!("{path}.content"), false)? {
|
||||
for part in parts(&message["content"], &format!("{path}.content"), role)? {
|
||||
if let Some(value) = part.get("text").and_then(Value::as_str) {
|
||||
text.push(value.to_owned());
|
||||
} else {
|
||||
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
vec![response]
|
||||
} else {
|
||||
let mut content = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
parts(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
content.push(json!({"text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
}
|
||||
content
|
||||
};
|
||||
if role == "assistant" && content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append(
|
||||
&mut contents,
|
||||
if role == "assistant" { "model" } else { "user" },
|
||||
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
generation.insert("stopSequences".into(), stops);
|
||||
}
|
||||
if let Some(effort) = reasoning_effort(chat) {
|
||||
let budget: i64 = match effort.as_str() {
|
||||
Some("none") => 0,
|
||||
Some("minimal" | "low") => 1024,
|
||||
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(format) = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"text":text})]);
|
||||
}
|
||||
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
.map(|(index, part)| {
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?}))
|
||||
Ok(json!({"text":block_text(part.get("text"), &path)?}))
|
||||
}
|
||||
"refusal" if !system => Ok(
|
||||
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
|
||||
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
|
||||
let parameters = if kind == "custom" {
|
||||
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
definition
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(definition, &path)?
|
||||
};
|
||||
if !parameters.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
|
||||
if let Some(value) = definition.get("description") {
|
||||
if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
|
||||
declaration["description"] = value.clone();
|
||||
}
|
||||
declarations.push(declaration);
|
||||
|
||||
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
|
||||
use crate::chat_completions::{
|
||||
ChatError, custom_tool_schema,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
request::{
|
||||
block_text, empty_history_content, empty_history_part, function_parameters,
|
||||
reasoning_effort, response_format, stop_sequences, string,
|
||||
},
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -37,6 +40,9 @@ pub fn convert_request(
|
||||
result.insert(field.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(stops) = stop_sequences(chat)? {
|
||||
result.insert("stop_sequences".into(), stops);
|
||||
}
|
||||
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
|
||||
match tier {
|
||||
"priority" => {
|
||||
@@ -53,7 +59,7 @@ pub fn convert_request(
|
||||
}
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(content(instructions, "instructions", true)?);
|
||||
system.extend(content(instructions, "instructions", "system")?);
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
@@ -70,7 +76,7 @@ pub fn convert_request(
|
||||
system.extend(content(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
role,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
@@ -84,15 +90,15 @@ pub fn convert_request(
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
vec![
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}),
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
|
||||
]
|
||||
} else {
|
||||
let mut blocks = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
content(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
|
||||
if let Some(refusal) = message
|
||||
.get("refusal")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
blocks.push(json!({"type":"text","text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
@@ -130,6 +136,9 @@ pub fn convert_request(
|
||||
}
|
||||
blocks
|
||||
};
|
||||
if role == "assistant" && blocks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
append_message(
|
||||
&mut messages,
|
||||
if role == "assistant" {
|
||||
@@ -148,10 +157,7 @@ pub fn convert_request(
|
||||
}
|
||||
result.insert("messages".into(), messages.into());
|
||||
tools(chat, &mut result, capabilities)?;
|
||||
let format = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
|
||||
if let Some(format) = format.filter(|v| !v.is_null()) {
|
||||
if let Some(format) = response_format(chat) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
let schema = format
|
||||
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
|
||||
if empty_history_content(role, value) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let system = matches!(role, "system" | "developer");
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"type":"text","text":text})]);
|
||||
}
|
||||
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
let block = match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?})
|
||||
json!({"type":"text","text":block_text(part.get("text"), &path)?})
|
||||
}
|
||||
"refusal" if !system => {
|
||||
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
|
||||
@@ -295,17 +306,11 @@ fn tools(
|
||||
let schema = if kind == "custom" {
|
||||
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
|
||||
} else {
|
||||
declaration
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
function_parameters(declaration, &path)?
|
||||
};
|
||||
if !schema.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut target = json!({"name":name,"input_schema":schema});
|
||||
for field in ["description", "strict", "cache_control"] {
|
||||
if let Some(value) = declaration.get(field) {
|
||||
if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
|
||||
target[field] = value.clone();
|
||||
}
|
||||
}
|
||||
@@ -393,11 +398,7 @@ fn reasoning(
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
max_tokens: u64,
|
||||
) -> Result<(), ChatError> {
|
||||
let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
else {
|
||||
let Some(effort) = reasoning_effort(chat) else {
|
||||
return Ok(());
|
||||
};
|
||||
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
|
||||
|
||||
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
field: "messages".into(),
|
||||
expected: "an array",
|
||||
})?;
|
||||
if messages.is_empty() {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
let mut has_message = false;
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
let path = format!("messages[{index}]");
|
||||
let message = message.as_object().ok_or_else(|| invalid(&path))?;
|
||||
@@ -42,43 +38,51 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
|
||||
return Err(unsupported(&format!("{path}.role")));
|
||||
}
|
||||
for (field, allowed) in [
|
||||
("tool_calls", "assistant"),
|
||||
("refusal", "assistant"),
|
||||
("tool_call_id", "tool"),
|
||||
] {
|
||||
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(invalid(&format!("{path}.{field}")));
|
||||
let calls = match message.get("tool_calls") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(Value::Array(calls)) => calls.as_slice(),
|
||||
_ => return Err(invalid(&format!("{path}.tool_calls"))),
|
||||
};
|
||||
if role != "assistant" && !calls.is_empty() {
|
||||
return Err(invalid(&format!("{path}.tool_calls")));
|
||||
}
|
||||
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
|
||||
if let Some(value) = refusal {
|
||||
if role != "assistant" {
|
||||
return Err(invalid(&format!("{path}.refusal")));
|
||||
}
|
||||
string(Some(value), &format!("{path}.refusal"), true)?;
|
||||
}
|
||||
for field in ["function_call", "audio"] {
|
||||
if message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
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"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
} else if message
|
||||
.get("tool_call_id")
|
||||
.is_some_and(|v| !v.is_null() && v != "")
|
||||
{
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
if let Some(content) = message.get("content").filter(|v| !v.is_null()) {
|
||||
let content = message.get("content").unwrap_or(&Value::Null);
|
||||
if !empty_history_content(role, content) {
|
||||
if !content.is_string() && !content.is_array() {
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
has_message = true;
|
||||
if let Some(parts) = content.as_array() {
|
||||
for (part_index, part) in parts.iter().enumerate() {
|
||||
let part_path = format!("{path}.content[{part_index}]");
|
||||
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
string(part.get("text"), &format!("{part_path}.text"), true)?;
|
||||
block_text(part.get("text"), &part_path)?;
|
||||
}
|
||||
"image_url" | "file" | "input_audio" | "input_image" | "input_file"
|
||||
if matches!(role, "user" | "tool") => {}
|
||||
@@ -89,45 +93,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if role != "assistant"
|
||||
|| (!message
|
||||
.get("tool_calls")
|
||||
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
|
||||
&& !message.get("refusal").is_some_and(Value::is_string))
|
||||
{
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||
for (call_index, call) in calls
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
has_message |= refusal.is_some() || !calls.is_empty();
|
||||
for (call_index, call) in calls.iter().enumerate() {
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let data_field = if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
};
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get(data_field)),
|
||||
&format!("{call_path}.{kind}.{data_field}"),
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if !has_message {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
|
||||
let valid = match field.as_str() {
|
||||
"n" => value.as_u64() == Some(1),
|
||||
@@ -150,7 +146,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
}
|
||||
}
|
||||
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
|
||||
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() {
|
||||
if !options.is_object() {
|
||||
return Err(invalid("stream_options"));
|
||||
}
|
||||
for field in ["include_usage", "include_obfuscation"] {
|
||||
@@ -161,13 +157,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
return Err(invalid(&format!("stream_options.{field}")));
|
||||
}
|
||||
}
|
||||
if options.get("include_obfuscation") == Some(&Value::Bool(true)) {
|
||||
if body.get("stream") == Some(&Value::Bool(true))
|
||||
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
|
||||
{
|
||||
return Err(unsupported("stream_options.include_obfuscation"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
|
||||
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
|
||||
can_omit_empty_text(role)
|
||||
&& (content.is_null()
|
||||
|| content == ""
|
||||
|| content
|
||||
.as_array()
|
||||
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
|
||||
}
|
||||
|
||||
fn can_omit_empty_text(role: &str) -> bool {
|
||||
matches!(role, "system" | "developer" | "assistant")
|
||||
}
|
||||
|
||||
fn plain_empty_text(part: &Value) -> bool {
|
||||
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
|
||||
part.get("text")
|
||||
.is_some_and(|text| text.is_null() || text == "")
|
||||
&& matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("text" | "input_text" | "output_text")
|
||||
)
|
||||
&& part.as_object().is_some_and(|fields| {
|
||||
fields
|
||||
.iter()
|
||||
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
|
||||
can_omit_empty_text(role) && plain_empty_text(part)
|
||||
}
|
||||
|
||||
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
|
||||
pub(super) fn block_text<'a>(
|
||||
value: Option<&'a Value>,
|
||||
part_path: &str,
|
||||
) -> Result<&'a str, ChatError> {
|
||||
match value {
|
||||
Some(Value::Null) => Ok(""),
|
||||
value => string(value, &format!("{part_path}.text"), true),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("response_format")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
|
||||
}
|
||||
|
||||
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
|
||||
body.get("reasoning_effort")
|
||||
.filter(|v| !v.is_null())
|
||||
.or_else(|| {
|
||||
body.get("reasoning")?
|
||||
.get("effort")
|
||||
.filter(|v| !v.is_null())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
|
||||
match body.get("stop") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(text)) => Ok(Some(json!([text]))),
|
||||
Some(Value::Array(values)) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
if !value.is_string() {
|
||||
return Err(invalid(&format!("stop[{index}]")));
|
||||
}
|
||||
}
|
||||
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
|
||||
}
|
||||
_ => Err(invalid("stop")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
|
||||
match function.get("parameters") {
|
||||
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
|
||||
Some(schema) if schema.is_object() => Ok(schema.clone()),
|
||||
_ => Err(invalid(&format!("{path}.function.parameters"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn string<'a>(
|
||||
value: Option<&'a Value>,
|
||||
path: &str,
|
||||
@@ -222,28 +304,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
|
||||
.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
|
||||
.get("response_format")
|
||||
json_schema: response_format(body)
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema")
|
||||
|| body
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema"),
|
||||
== Some("json_schema"),
|
||||
..RequestFacts::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
|
||||
body.get("reasoning_effort")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| {
|
||||
body.get("reasoning")
|
||||
.and_then(|value| value.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
reasoning_effort(body).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
|
||||
|
||||
@@ -4,7 +4,11 @@ use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request};
|
||||
use crate::chat_completions::{
|
||||
ChatError as RequestDecodeError,
|
||||
request::{block_text, empty_history_content, empty_history_part},
|
||||
validate_request,
|
||||
};
|
||||
|
||||
/// 将已验证的 Chat 正文直接转换为 Responses 请求
|
||||
pub fn convert_request(
|
||||
@@ -161,7 +165,6 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let path = format!("messages[{index}]");
|
||||
let mut message = object(value, &path)?;
|
||||
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
|
||||
let name = optional(&mut message, "name").filter(|name| name != "");
|
||||
if role == "tool" {
|
||||
let call_id = required_string(
|
||||
&mut message,
|
||||
@@ -182,7 +185,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
"function_call_output"
|
||||
};
|
||||
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
|
||||
if let Some(name) = name {
|
||||
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
|
||||
string(&name, &format!("{path}.name"), true)?;
|
||||
item["name"] = name;
|
||||
}
|
||||
input.push(item);
|
||||
@@ -193,8 +197,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
.map(|value| tool_calls(value, &format!("{path}.tool_calls")))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let refusal = optional(&mut message, "refusal");
|
||||
let content = optional(&mut message, "content");
|
||||
let refusal = optional(&mut message, "refusal").filter(|v| v != "");
|
||||
let content =
|
||||
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
|
||||
let is_assistant = role == "assistant";
|
||||
let mut parts = content
|
||||
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
|
||||
@@ -233,20 +238,23 @@ fn content_parts(
|
||||
is_assistant: bool,
|
||||
) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
let parts = match value {
|
||||
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]),
|
||||
Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
|
||||
Value::Array(parts) => parts,
|
||||
_ => return Err(invalid_type(path, "a string or an array")),
|
||||
};
|
||||
let mut result = Vec::with_capacity(parts.len());
|
||||
for (index, value) in parts.into_iter().enumerate() {
|
||||
for (index, value) in parts
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| !empty_history_part(role, part))
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let mut part = object(value, &path)?;
|
||||
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
|
||||
let mut converted = match kind.as_str() {
|
||||
"text" | "input_text" | "output_text" => text_part(
|
||||
required_string(&mut part, "text", &format!("{path}.text"), true)?,
|
||||
is_assistant,
|
||||
),
|
||||
"text" | "input_text" | "output_text" => {
|
||||
text_part(block_text(part.get("text"), &path)?, is_assistant)
|
||||
}
|
||||
"image_url" if matches!(role, "user" | "tool") => image_part(
|
||||
required(&mut part, "image_url", &format!("{path}.image_url"))?,
|
||||
&format!("{path}.image_url"),
|
||||
@@ -278,7 +286,7 @@ fn content_parts(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn text_part(text: String, is_assistant: bool) -> Value {
|
||||
fn text_part(text: &str, is_assistant: bool) -> Value {
|
||||
if is_assistant {
|
||||
json!({"type": "output_text", "text": text, "annotations": []})
|
||||
} else {
|
||||
@@ -376,9 +384,17 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
|
||||
if let Some(nested) = optional(&mut tool, &kind) {
|
||||
tool = object(nested, &format!("{path}.{kind}"))?;
|
||||
}
|
||||
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
if tool.get("description") == Some(&Value::Null) {
|
||||
tool.remove("description");
|
||||
}
|
||||
if kind == "function" {
|
||||
if tool.get("parameters") == Some(&Value::Null) {
|
||||
tool.remove("parameters");
|
||||
}
|
||||
if tool.get("strict").is_none_or(Value::is_null) {
|
||||
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
|
||||
tool.insert("strict".into(), false.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
|
||||
|
||||
@@ -4,7 +4,15 @@ use gateway_protocol::{
|
||||
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
|
||||
request::{request_facts, request_observation},
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
|
||||
[
|
||||
responses::convert_request(body),
|
||||
messages::convert_request(body, &Default::default()),
|
||||
genai::convert_request(body),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_retains_original_protocol_and_usage_preference() {
|
||||
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("previous_response_id", json!("resp_previous")),
|
||||
("stream_options", json!({"include_usage":true})),
|
||||
("stream_options", json!(true)),
|
||||
] {
|
||||
let mut request = super::request();
|
||||
request.insert(field.into(), value);
|
||||
@@ -104,9 +112,320 @@ fn capability_facts_only_read_protocol_declarations() {
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_is_omitted_only_when_converting() {
|
||||
let mut baseline = super::request();
|
||||
baseline["messages"] = json!([
|
||||
{"role":"developer","content":"Keep replies short."},
|
||||
{"role":"user","content":"hello"}
|
||||
]);
|
||||
let expected = target_requests(&baseline).map(Result::unwrap);
|
||||
for role in ["system", "developer", "assistant"] {
|
||||
for content in [
|
||||
None,
|
||||
Some(Value::Null),
|
||||
Some(json!("")),
|
||||
Some(json!([])),
|
||||
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
|
||||
Some(json!([{"type":"input_text","text":null}])),
|
||||
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
|
||||
] {
|
||||
let mut placeholder =
|
||||
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
|
||||
if let Some(content) = content {
|
||||
placeholder["content"] = content;
|
||||
}
|
||||
let mut body = baseline.clone();
|
||||
body["messages"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.insert(1, placeholder.clone());
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
assert_eq!(parsed, body);
|
||||
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
|
||||
|
||||
body["messages"] = json!([placeholder]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
|
||||
let mut body = super::request();
|
||||
body["messages"] = json!([
|
||||
{"role":"user","content":"hello"},
|
||||
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c","content":""},
|
||||
{"role":"assistant","refusal":"declined"}
|
||||
]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[0]["input"][1]["call_id"], "c");
|
||||
assert_eq!(expected[0]["input"][2]["output"], "");
|
||||
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
|
||||
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
|
||||
assert_eq!(
|
||||
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
|
||||
"c"
|
||||
);
|
||||
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
|
||||
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
|
||||
for content in [
|
||||
Value::Null,
|
||||
json!(""),
|
||||
json!([]),
|
||||
json!([{"type":"text","text":""}]),
|
||||
json!([{"type":"output_text","text":null}]),
|
||||
] {
|
||||
body["messages"][1]["content"] = content.clone();
|
||||
body["messages"][3]["content"] = content;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
body["messages"][2]["content"] =
|
||||
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(
|
||||
messages["messages"][2]["content"][0]["content"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
|
||||
"\nx\n"
|
||||
);
|
||||
body["messages"][2]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(
|
||||
target_requests(&body).map(Result::unwrap),
|
||||
[responses, messages, genai]
|
||||
);
|
||||
body["messages"][2]["content"] = json!("");
|
||||
body["messages"][2]["name"] = json!(17);
|
||||
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
|
||||
let [responses, messages, genai] = target_requests(&parsed);
|
||||
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
|
||||
assert_eq!(messages.unwrap(), expected[1]);
|
||||
assert_eq!(genai.unwrap(), expected[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
|
||||
let mut body = super::request();
|
||||
let blank = json!({"type":"input_text","text":""});
|
||||
let space = json!({"type":"text","text":" "});
|
||||
for role in ["system", "developer", "assistant", "user"] {
|
||||
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"] = json!([blank, space, blank]);
|
||||
let actual = target_requests(&body).map(Result::unwrap);
|
||||
body["messages"][0]["content"][0]["text"] = Value::Null;
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
|
||||
if role == "user" {
|
||||
assert_eq!(
|
||||
actual[0]["input"][0]["content"].as_array().unwrap().len(),
|
||||
3
|
||||
);
|
||||
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
|
||||
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
|
||||
} else {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
|
||||
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
|
||||
let converted = responses::convert_request(&body).unwrap();
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"],
|
||||
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
|
||||
);
|
||||
body["messages"][0]["role"] = json!("assistant");
|
||||
assert_eq!(
|
||||
responses::convert_request(&body).unwrap_err().parameter(),
|
||||
Some("messages[0].content[1].prompt_cache_breakpoint")
|
||||
);
|
||||
for (part, code) in [
|
||||
(json!({"type":"text"}), "missing_required_parameter"),
|
||||
(json!({"type":"text","text":17}), "invalid_type"),
|
||||
(json!({"type":"text","text":{}}), "invalid_type"),
|
||||
] {
|
||||
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
|
||||
assert_eq!(error.code(), code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_chat_controls_fall_back_to_native_format_and_effort() {
|
||||
let mut body = super::request();
|
||||
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
|
||||
body.insert(
|
||||
"text".into(),
|
||||
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
|
||||
);
|
||||
body.insert("reasoning".into(), json!({"effort":"low"}));
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["responseJsonSchema"],
|
||||
schema
|
||||
);
|
||||
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
|
||||
assert_eq!(
|
||||
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
1024
|
||||
);
|
||||
body.insert("response_format".into(), Value::Null);
|
||||
body.insert("reasoning_effort".into(), Value::Null);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
|
||||
body["response_format"] = json!({"type":"text"});
|
||||
body["reasoning_effort"] = json!("none");
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
|
||||
assert_eq!(responses["text"]["format"]["type"], "text");
|
||||
assert!(messages.get("output_config").is_none());
|
||||
assert!(
|
||||
genai["generationConfig"]
|
||||
.get("responseJsonSchema")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(messages["thinking"]["type"], "disabled");
|
||||
assert_eq!(
|
||||
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
0
|
||||
);
|
||||
body["reasoning_effort"] = json!(5);
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(error.parameter(), Some("reasoning_effort"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_function_parameters_follow_each_targets_default() {
|
||||
let mut body = super::request();
|
||||
body.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"function","function":{"name":"clock"}}]),
|
||||
);
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
assert!(expected[0]["tools"][0].get("parameters").is_none());
|
||||
let default_schema = json!({"type":"object","properties":{}});
|
||||
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
|
||||
assert_eq!(
|
||||
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
default_schema
|
||||
);
|
||||
body["tools"][0]["function"] =
|
||||
json!({"name":"clock","parameters":null,"description":null,"strict":null});
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
|
||||
let schema =
|
||||
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
|
||||
body["tools"][0]["function"]["parameters"] = schema.clone();
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses["tools"][0]["parameters"], schema);
|
||||
assert_eq!(messages["tools"][0]["input_schema"], schema);
|
||||
assert_eq!(
|
||||
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
|
||||
schema
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
|
||||
let mut body = super::request();
|
||||
let baseline = target_requests(&body).map(Result::unwrap);
|
||||
for stop in [Value::Null, json!([])] {
|
||||
body.insert("stop".into(), stop);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
|
||||
}
|
||||
for (stop, expected) in [
|
||||
(json!(" END"), json!([" END"])),
|
||||
(json!([" END", "\n"]), json!([" END", "\n"])),
|
||||
] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
|
||||
assert_eq!(responses, baseline[0]);
|
||||
assert_eq!(messages["stop_sequences"], expected);
|
||||
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
|
||||
}
|
||||
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
|
||||
body["stop"] = stop;
|
||||
let [responses, messages, genai] = target_requests(&body);
|
||||
assert_eq!(responses.unwrap(), baseline[0]);
|
||||
for result in [messages, genai] {
|
||||
assert_eq!(result.unwrap_err().parameter(), Some(param));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_options_affect_only_streaming_delivery() {
|
||||
for stream in [None, Some(false), Some(true)] {
|
||||
let mut body = super::request();
|
||||
if let Some(stream) = stream {
|
||||
body.insert("stream".into(), json!(stream));
|
||||
}
|
||||
let expected = target_requests(&body).map(Result::unwrap);
|
||||
body.insert(
|
||||
"stream_options".into(),
|
||||
json!({"include_usage":true, "include_obfuscation":false}),
|
||||
);
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
body["stream_options"]["include_obfuscation"] = json!(true);
|
||||
if stream == Some(true) {
|
||||
for error in target_requests(&body).map(Result::unwrap_err) {
|
||||
assert_eq!(
|
||||
error.parameter(),
|
||||
Some("stream_options.include_obfuscation")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_targets_apply_the_same_common_request_validation() {
|
||||
for (field, value, parameter) in [
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
|
||||
"messages",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
|
||||
"messages[1].audio",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":42}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null},{"role":"user","content":null}]),
|
||||
"messages[1].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"tool","tool_call_id":"c","content":null}]),
|
||||
"messages[0].content",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"assistant","content":"ok","refusal":17}]),
|
||||
@@ -114,13 +433,18 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","name":17}]),
|
||||
"messages[0].name",
|
||||
json!([{"role":"assistant","tool_calls":{}}]),
|
||||
"messages[0].tool_calls",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","tool_calls":[]}]),
|
||||
"messages[0].tool_calls",
|
||||
json!([{"role":"developer","tool_call_id":"c"}]),
|
||||
"messages[0].tool_call_id",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
json!([{"role":"user","content":"ok","refusal":"declined"}]),
|
||||
"messages[0].refusal",
|
||||
),
|
||||
(
|
||||
"messages",
|
||||
@@ -130,8 +454,8 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
("n", json!(2), "n"),
|
||||
(
|
||||
"stream_options",
|
||||
json!({"include_usage":true}),
|
||||
"stream_options",
|
||||
json!({"include_usage":1}),
|
||||
"stream_options.include_usage",
|
||||
),
|
||||
] {
|
||||
let mut body = super::request();
|
||||
@@ -140,11 +464,7 @@ fn all_targets_apply_the_same_common_request_validation() {
|
||||
.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),
|
||||
] {
|
||||
for result in target_requests(&body) {
|
||||
assert_eq!(result.unwrap_err(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,6 +775,7 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
|
||||
body["stop"] = json!(["END", " STOP"]);
|
||||
body["messages"].as_array_mut().unwrap().insert(
|
||||
0,
|
||||
json!({"role":"system","content":"Preserve the caller's project rules."}),
|
||||
@@ -877,6 +878,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}])
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["stopSequences"],
|
||||
json!(["END", " STOP"])
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
24576
|
||||
|
||||
@@ -61,7 +61,7 @@ fn chat_operation(stream: bool) -> Operation {
|
||||
unreachable!()
|
||||
};
|
||||
let mut body = json!({"model":"gpt-5.4", "stream":stream,
|
||||
"reasoning_effort":"xhigh",
|
||||
"reasoning_effort":"xhigh", "stop":"END",
|
||||
"messages":[{"role":"user","content":"hello"}]});
|
||||
if stream {
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
@@ -293,13 +293,15 @@ async fn chat_reaches_each_selected_protocol_with_target_header_boundaries() {
|
||||
}
|
||||
assert!(terminal_seen);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let headers = &requests
|
||||
let request = requests
|
||||
.iter()
|
||||
.find(|request| request.method == "POST")
|
||||
.unwrap()
|
||||
.headers;
|
||||
.unwrap();
|
||||
let headers = &request.headers;
|
||||
let body: Value = serde_json::from_slice(&request.body).unwrap();
|
||||
assert_eq!(headers.get("x-business-extension").unwrap(), "keep");
|
||||
if target == ApiKeyProtocol::Messages {
|
||||
assert_eq!(body["stop_sequences"], json!(["END"]));
|
||||
for name in [
|
||||
"session-id",
|
||||
"thread-id",
|
||||
@@ -309,7 +311,7 @@ async fn chat_reaches_each_selected_protocol_with_target_header_boundaries() {
|
||||
assert!(!headers.contains_key(name));
|
||||
}
|
||||
} else {
|
||||
let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
|
||||
assert!(body.get("stop_sequences").is_none() && body.get("stop").is_none());
|
||||
assert_eq!(body["reasoning"]["effort"], "xhigh");
|
||||
assert!(body.get("max_output_tokens").is_none());
|
||||
for name in [
|
||||
|
||||
+14
-13
@@ -328,18 +328,19 @@ print(completion.choices[0].message.content)
|
||||
| 字段 | 支持与映射 |
|
||||
| --- | --- |
|
||||
| `messages[].role` | `system`、`developer`、`user`、`assistant`、`tool`,保持顺序;assistant 文本历史转为 `output_text` |
|
||||
| `messages[].content` | 字符串或内容块数组;user 和 tool 可包含图片、文件与音频,assistant 支持文本与拒绝内容 |
|
||||
| `messages[].content` | 字符串或内容块数组。所有角色的 `text`、`input_text`、`output_text` 块均将显式 `"text": null` 按空字符串处理。缺少 `text` 或传入其他非字符串值时返回 `400`。user 和 tool 可包含图片、文件与音频,assistant 支持文本与拒绝内容 |
|
||||
| `system`、`developer`、`assistant` 的空正文 | 正文缺省、为 `null` 或 `""` 时省略。数组中移除没有附加信息的空文本块,保留空白字符和带缓存断点的块。数组为空时仍转换 assistant 的工具调用和拒绝内容。全部消息均为空占位时返回 `400` |
|
||||
| `image_url` 内容块 | HTTP(S) URL 或非空 `data:image/...;base64,...`,保留 `detail`,网关不代取图片 |
|
||||
| `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 同时有工具调用或拒绝内容时,`content` 可省略或为 `null` |
|
||||
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果;保留 ID、参数或输入字符串,不解析或执行工具;custom 结果须携带前序调用历史 |
|
||||
| `messages[].name` | tool 消息的工具名随结果携带;其他角色的名称作为辅助信息忽略 |
|
||||
| `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象;function 的 `strict` 省略或 `null` 时使用 `false` |
|
||||
| `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` |
|
||||
| `tool_choice`、`parallel_tool_calls` | 展开指定 function/custom 和 `allowed_tools` 选择;原生选择与并行布尔值交给上游 |
|
||||
| `web_search_options` | `{}` 即要求上游执行 `web_search`;支持 `search_context_size` 与 `user_location.approximate` |
|
||||
| `response_format` | 映射到 `text.format`,保留 JSON Schema;未知格式交给上游 |
|
||||
| `reasoning_effort`、`verbosity` | 覆盖 `reasoning.effort`、`text.verbosity`,不固定枚举档位 |
|
||||
| `response_format` | 非 `null` 时优先于 `text.format`,保留 JSON Schema;未知格式交给 Responses 上游 |
|
||||
| `reasoning_effort`、`verbosity` | 非 `null` 时分别覆盖 `reasoning.effort`、`text.verbosity`,取值范围由 Responses 上游决定 |
|
||||
| `max_completion_tokens`、`max_tokens`、`max_output_tokens` | 映射到 `max_output_tokens`,按本行从左到右的顺序优先 |
|
||||
| `temperature`、`top_p` | 原值进入 Provider;是否生效见下文正文兼容规则 |
|
||||
| `user`、`safety_identifier`、`service_tier`、`prompt_cache_key`、`prompt_cache_retention` | 同语义字段保留原值 |
|
||||
@@ -348,8 +349,8 @@ print(completion.choices[0].message.content)
|
||||
| `logprobs`、`top_logprobs` | `logprobs: true` 请求输出文本 logprobs,并携带 `top_logprobs`;返回值位于 Chat 的 `choices[].logprobs` |
|
||||
| 内容块的 `prompt_cache_breakpoint` | 对象原样携带;assistant 输出消息不支持此选项 |
|
||||
|
||||
可选映射参数为 `null` 时按未提供处理。`stop`、`seed`、`frequency_penalty`、`presence_penalty`、
|
||||
`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
|
||||
可选映射参数为 `null` 时按未提供处理。`stop` 的字符串或字符串数组在 Messages 中映射为 `stop_sequences`,在 GenAI 中映射为 `generationConfig.stopSequences`。空数组按省略处理,Responses 忽略此参数。
|
||||
`seed`、`frequency_penalty`、`presence_penalty`、`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
|
||||
消息的 `reasoning_content` 和 `reasoning` 作为辅助历史忽略,不转为用户正文
|
||||
|
||||
`n`、`store`、`background`、`modalities` 和 `functions` 可省略或为 `null`。非空值仅接受 `n: 1`、`store: false`、`background: false`、`modalities: ["text"]` 和 `functions: []`。
|
||||
@@ -364,7 +365,7 @@ Messages 目标直接生成 `system`、`messages`、`tool_use`/`tool_result`
|
||||
`service_tier: priority` 映射为 `speed: fast` 并补充目标 beta,`default` 映射为 `standard_only`;不代表两种上游有相同的服务承诺
|
||||
|
||||
GenAI 目标直接生成 `systemInstruction`、`contents`、`functionCall`/`functionResponse` 和 `generationConfig`。
|
||||
两个目标都校验工具调用与结果的配对;custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。
|
||||
两个目标都校验工具调用与结果的配对。函数省略参数定义时使用空对象 schema。custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。
|
||||
Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.type: text`;grammar 等受约束格式返回 `400`,`param` 指向原始格式字段。
|
||||
多模态字段按目标能力映射,不支持的内容或声明返回字段错误,不转成另一平台协议重试
|
||||
|
||||
@@ -380,9 +381,9 @@ Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.ty
|
||||
索引对应合并后的消息正文。流式结果保留正文中的行内链接,并在结束前通过 `delta.annotations` 交付结构化引用,
|
||||
索引对应实际交付的合并正文
|
||||
|
||||
`stream_options` 仅在 `stream: true` 时可提供,
|
||||
`include_usage: true` 在完整上游用量可用时于结束前追加 `choices: []` 的用量块,其余块的 `usage` 为 `null`。
|
||||
未提供完整用量时不补造 Token 数;缺省不启用流长度混淆,`include_obfuscation: true` 不受支持,`false` 可接受
|
||||
`stream_options` 仅在 `stream: true` 时生效,非流式请求也可携带该对象。
|
||||
流式请求设置 `include_usage: true` 时,网关在完整上游用量可用时于结束前追加 `choices: []` 的用量块,其余块的 `usage` 为 `null`。
|
||||
未提供完整用量时不补造 Token 数。流式请求支持省略 `include_obfuscation` 或设为 `false`,设为 `true` 时返回 `400`
|
||||
|
||||
响应对象的额外普通属性、非必要事件不影响已有内容映射;无法表达的业务输出、缺少必要终态或终态冲突会失败,
|
||||
不补造成功终态。SSE 已开始后通过 `data: {"error": ...}` 交付错误,再以 `[DONE]` 结束,
|
||||
|
||||
Reference in New Issue
Block a user