Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 58 additions & 11 deletions crates/protocols/src/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ pub struct ResponsesFunctionToolChoice {
#[serde(rename = "type")]
pub tool_type: FunctionToolChoiceTag,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
}

impl<'de> Deserialize<'de> for ResponsesFunctionToolChoice {
Expand All @@ -141,6 +143,8 @@ impl<'de> Deserialize<'de> for ResponsesFunctionToolChoice {
name: Option<String>,
#[serde(default)]
function: Option<FunctionChoice>,
#[serde(default)]
namespace: Option<String>,
}

let helper = Helper::deserialize(deserializer)?;
Expand All @@ -155,6 +159,7 @@ impl<'de> Deserialize<'de> for ResponsesFunctionToolChoice {
Ok(Self {
tool_type: helper.tool_type,
name,
namespace: helper.namespace,
})
}
}
Expand Down Expand Up @@ -312,7 +317,10 @@ impl ResponsesToolChoice {
Self::Function(payload) => ChatToolChoice::Function {
tool_type: "function".to_string(),
function: FunctionChoice {
name: payload.name.clone(),
name: match &payload.namespace {
Some(namespace) => format!("{namespace}.{}", payload.name),
None => payload.name.clone(),
},
},
},
Self::AllowedTools { mode, tools, .. } => ChatToolChoice::AllowedTools {
Expand Down Expand Up @@ -1184,6 +1192,8 @@ pub struct WebSearchPreviewTool {
#[derive(Debug, Clone, Deserialize, Serialize, Default, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WebSearchTool {
/// Whether the tool may fetch live external sources rather than cached results.
pub external_web_access: Option<bool>,
/// Optional domain allowlist applied to candidate sources.
pub filters: Option<WebSearchFilters>,
/// Search-result context token budget. Spec enum: `"default" | "unlimited"`.
Expand Down Expand Up @@ -1591,6 +1601,35 @@ pub enum StringOrContentParts {
Array(Vec<ResponseContentPart>),
}

impl StringOrContentParts {
/// Project tool output into a text-only backend without silently losing media.
pub fn to_text_only(&self) -> Result<String, String> {
match self {
Self::String(text) => Ok(text.clone()),
Self::Array(parts) => {
let mut text = String::new();
for part in parts {
match part {
ResponseContentPart::InputText { text: part }
| ResponseContentPart::OutputText { text: part, .. } => text.push_str(part),
_ => return Err(
"Multimodal function output is not supported by this text-only backend"
.to_string(),
),
}
}
Ok(text)
}
}
}
}

impl From<String> for StringOrContentParts {
fn from(text: String) -> Self {
Self::String(text)
}
}

/// Phase label for assistant messages in the Responses API.
///
/// For gpt-5.3-codex+ multi-turn conversations, preserving and resending the
Expand Down Expand Up @@ -1644,6 +1683,8 @@ pub enum ResponseInputOutputItem {
id: Option<String>,
call_id: String,
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
namespace: Option<String>,
arguments: String,
#[serde(skip_serializing_if = "Option::is_none")]
output: Option<String>,
Expand All @@ -1655,7 +1696,7 @@ pub enum ResponseInputOutputItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
call_id: String,
output: String,
output: StringOrContentParts,
#[serde(skip_serializing_if = "Option::is_none")]
status: Option<String>,
},
Expand Down Expand Up @@ -2254,6 +2295,8 @@ pub enum ResponseOutputItem {
id: Option<String>,
call_id: String,
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
namespace: Option<String>,
arguments: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
output: Option<String>,
Expand Down Expand Up @@ -3347,12 +3390,21 @@ fn validate_tool_choice_with_tools(request: &ResponsesRequest) -> Result<(), Val

// Validate tool references exist
match tool_choice {
ResponsesToolChoice::Function(_) => {
ResponsesToolChoice::Function(choice) => {
// Accessor goes through `function_name()` so we stay agnostic to
// the underlying wire shape (flat vs. legacy nested) — both are
// normalized at deserialize time.
if let Some(name) = tool_choice.function_name() {
if !function_tool_names.contains(&name) {
let found = tools.iter().any(|tool| match (tool, choice.namespace.as_deref()) {
(ResponseTool::Function(function), None) => function.function.name == name,
(ResponseTool::Namespace(namespace), Some(selected_namespace)) => {
namespace.name == selected_namespace && namespace.tools.iter().any(|member| {
matches!(member, NamespaceTool::Function(function) if function.function.name == name)
})
}
_ => false,
});
if !found {
let mut e = ValidationError::new("tool_choice_function_not_found");
e.message = Some(
format!(
Expand Down Expand Up @@ -3521,13 +3573,7 @@ fn validate_input_item(item: &ResponseInputOutputItem) -> Result<(), ValidationE
ResponseInputOutputItem::Reasoning { .. } => {
// Reasoning content can be empty - no validation needed
}
ResponseInputOutputItem::FunctionCallOutput { output, .. } => {
if output.is_empty() {
let mut e = ValidationError::new("function_output_empty");
e.message = Some("Function call output cannot be empty".into());
return Err(e);
}
}
ResponseInputOutputItem::FunctionCallOutput { .. } => {}
ResponseInputOutputItem::FunctionToolCall { .. } => {}
ResponseInputOutputItem::McpApprovalRequest { .. } => {}
ResponseInputOutputItem::McpApprovalResponse { .. } => {}
Expand Down Expand Up @@ -3961,6 +4007,7 @@ impl ResponseOutputItem {
id: Some(id),
call_id,
name,
namespace: None,
arguments,
output,
status,
Expand Down
110 changes: 110 additions & 0 deletions crates/protocols/tests/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,115 @@ use openai_protocol::{
use serde_json::json;
use validator::Validate;

#[test]
fn stateless_function_replay_preserves_namespace_and_content_part_output() {
let call = json!({
"type":"function_call", "call_id":"call_test", "name":"lookup",
"namespace":"weather", "arguments":"{}", "status":"completed"
});
let input: ResponseInputOutputItem = serde_json::from_value(call.clone()).unwrap();
let output: ResponseOutputItem = serde_json::from_value(call.clone()).unwrap();
assert_eq!(serde_json::to_value(input).unwrap(), call);
assert_eq!(serde_json::to_value(output).unwrap(), call);
for result in [
json!("sunny"),
json!([{"type":"input_text", "text":"sunny"}]),
json!(""),
json!([]),
] {
let value = json!({"type":"function_call_output", "call_id":"call_test", "output":result});
let item: ResponseInputOutputItem = serde_json::from_value(value.clone()).unwrap();
assert_eq!(serde_json::to_value(item).unwrap(), value);
let request: ResponsesRequest = serde_json::from_value(json!({
"model":"test-model", "input":[{"role":"user", "content":"weather"}, call.clone(), value], "store":false
}))
.unwrap();
request.validate().unwrap();
}
}

#[test]
fn text_only_function_output_projection_preserves_order_and_rejects_media() {
let output: StringOrContentParts = serde_json::from_value(json!([
{"type":"input_text", "text":"first"}, {"type":"input_text", "text":"second"}
]))
.unwrap();
assert_eq!(output.to_text_only().unwrap(), "firstsecond");
let value = json!([{"type":"input_image", "image_url":"data:image/png;base64,AA=="}]);
let output: StringOrContentParts = serde_json::from_value(value.clone()).unwrap();
assert_eq!(serde_json::to_value(&output).unwrap(), value);
assert!(output.to_text_only().is_err());
}

#[test]
fn namespaced_function_choice_preserves_identity_and_validates_membership() {
let tools = json!([
{"type":"namespace", "name":"weather", "description":"Weather tools", "tools":[
{"type":"function", "name":"lookup", "description":"Look up weather", "parameters":{"type":"object"}}
]},
{"type":"function", "name":"lookup", "description":"Top-level lookup", "parameters":{"type":"object"}}
]);
for selection in [
json!({"type":"function", "name":"lookup", "namespace":"weather"}),
json!({"type":"function", "function":{"name":"lookup"}, "namespace":"weather"}),
] {
let request: ResponsesRequest = serde_json::from_value(json!({
"model":"test-model", "input":"weather", "tools":tools,
"tool_choice":selection, "store":false
}))
.unwrap();
request.validate().unwrap();
let choice = request.tool_choice.as_ref().unwrap();
assert_eq!(
serde_json::to_value(choice).unwrap(),
json!({
"type":"function", "name":"lookup", "namespace":"weather"
})
);
match choice.to_chat_tool_choice() {
ChatToolChoice::Function { function, .. } => {
assert_eq!(function.name, "weather.lookup");
}
other => panic!("expected Function, got {other:?}"),
}
}
for (namespace, name) in [("missing", "lookup"), ("weather", "missing")] {
let request: ResponsesRequest = serde_json::from_value(json!({
"model":"test-model", "input":"weather", "tools":tools,
"tool_choice":{"type":"function", "name":name, "namespace":namespace}
}))
.unwrap();
assert!(request.validate().is_err());
}
let request: ResponsesRequest = serde_json::from_value(json!({
"model":"test-model", "input":"weather", "tools":[tools[0].clone()],
"tool_choice":{"type":"function", "name":"lookup"}
}))
.unwrap();
assert!(
request.validate().is_err(),
"a namespace member must not match an unqualified selection"
);
}

#[test]
fn web_search_external_access_round_trips_explicit_false() {
for enabled in [true, false] {
let value = json!({"type":"web_search", "external_web_access":enabled});
let tool: ResponseTool = serde_json::from_value(value.clone()).unwrap();
assert_eq!(serde_json::to_value(tool).unwrap(), value);
}
let tool: ResponseTool = serde_json::from_value(json!({"type":"web_search"})).unwrap();
assert_eq!(
serde_json::to_value(tool).unwrap(),
json!({"type":"web_search"})
);
assert!(serde_json::from_value::<ResponseTool>(
json!({"type":"web_search", "external_web_access":"false"})
)
.is_err());
}

#[test]
fn summary_text_content_round_trips_spec_shape() {
// Spec: `summary: array of SummaryTextContent { text, type: "summary_text" }`.
Expand Down Expand Up @@ -1102,6 +1211,7 @@ fn responses_tool_choice_to_chat_projection() {
let fn_choice = ResponsesToolChoice::Function(ResponsesFunctionToolChoice {
tool_type: FunctionToolChoiceTag::Function,
name: "get_weather".to_string(),
namespace: None,
});
match fn_choice.to_chat_tool_choice() {
ChatToolChoice::Function {
Expand Down
4 changes: 3 additions & 1 deletion model_gateway/benches/routing_allocation_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ fn extract_text_for_routing_old(req: &ResponsesRequest) -> String {
ResponseInputOutputItem::FunctionToolCall { arguments, .. } => {
Some(arguments.clone())
}
ResponseInputOutputItem::FunctionCallOutput { output, .. } => Some(output.clone()),
ResponseInputOutputItem::FunctionCallOutput { output, .. } => {
output.to_text_only().ok()
}
ResponseInputOutputItem::McpApprovalRequest { .. } => None,
ResponseInputOutputItem::McpApprovalResponse { .. } => None,
ResponseInputOutputItem::ImageGenerationCall { .. } => None,
Expand Down
13 changes: 11 additions & 2 deletions model_gateway/src/routers/grpc/harmony/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -742,10 +742,15 @@ impl HarmonyBuilder {
// Function tool call (with optional output)
ResponseInputOutputItem::FunctionToolCall {
name,
namespace,
arguments,
output,
..
} => {
let name = match namespace {
Some(namespace) => format!("{namespace}.{name}"),
None => name.clone(),
};
// If there's an output, this represents the tool result
// Otherwise, it's the tool call itself
if let Some(output_str) = output {
Expand Down Expand Up @@ -807,8 +812,12 @@ impl HarmonyBuilder {
ResponseInputOutputItem::FunctionToolCall {
call_id: item_call_id,
name,
namespace,
..
} if item_call_id == call_id => Some(name.clone()),
} if item_call_id == call_id => Some(match namespace {
Some(namespace) => format!("{namespace}.{name}"),
None => name.clone(),
}),
_ => None,
})
.ok_or_else(|| format!("No function call found for call_id: {call_id}"))?;
Expand All @@ -823,7 +832,7 @@ impl HarmonyBuilder {
},
recipient: Some("assistant".to_string()),
content: vec![Content::Text(TextContent {
text: output.clone(),
text: output.to_text_only()?,
})],
channel: None,
content_type: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ pub(super) fn build_next_request_with_tools(
id: Some(tool_call.id.clone()),
call_id: tool_call.id.clone(),
name: tool_call.function.name.clone(),
namespace: None,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
arguments: tool_call
.function
.arguments
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ fn build_tool_response(
id: Some(tool_call.id.clone()),
call_id: tool_call.id.clone(),
name: tool_call.function.name.clone(),
namespace: None,
arguments: tool_call.function.arguments.clone().unwrap_or_default(),
output: Some(output_str),
status: if result.is_error {
Expand All @@ -494,6 +495,7 @@ fn build_tool_response(
id: Some(tool_call.id),
call_id,
name: tool_call.function.name,
namespace: None,
arguments,
output: None, // No output = needs execution
status: "completed".to_string(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ impl ToolLoopState {
id: Some(id),
call_id,
name: tool_name,
namespace: None,
arguments: args_json_str,
output: Some(output_str),
status: Some("completed".to_string()),
Expand Down
Loading
Loading