feat: 优化工具调用内容格式,简化空参数处理并改进参数输出格式

This commit is contained in:
ooodc 2026-04-27 17:15:52 +08:00
parent 5b13748106
commit 4e1b831948

View File

@ -468,21 +468,10 @@ impl OutboundMessage {
}
pub(crate) fn format_tool_call_content(tool_name: &str, tool_arguments: &serde_json::Value) -> String {
let mut lines = vec![format!("### {}", tool_name)];
match tool_arguments {
serde_json::Value::Object(map) if !map.is_empty() => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
for (key, value) in entries {
lines.push(format!("- {}: {}", key, format_tool_argument_value(value)));
}
}
serde_json::Value::Object(_) => {}
other => lines.push(format!("- args: {}", format_tool_argument_value(other))),
serde_json::Value::Object(map) if map.is_empty() => tool_name.to_string(),
other => format!("{}\nargs: {}", tool_name, format_tool_arguments_json(other)),
}
lines.join("\n")
}
fn format_tool_result_content(tool_name: &str, content: &str) -> String {
@ -497,6 +486,28 @@ fn format_tool_argument_value(value: &serde_json::Value) -> String {
}
}
fn format_tool_arguments_json(value: &serde_json::Value) -> String {
match value {
serde_json::Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
let body = entries
.into_iter()
.map(|(key, value)| {
format!(
"{}:{}",
serde_json::to_string(key).unwrap_or_else(|_| format!("\"{}\"", key)),
serde_json::to_string(value).unwrap_or_else(|_| value.to_string()),
)
})
.collect::<Vec<_>>()
.join(",");
format!("{{{}}}", body)
}
other => format_tool_argument_value(other),
}
}
// ============================================================================
// Helpers
// ============================================================================
@ -545,9 +556,9 @@ mod tests {
assert_eq!(outbound[0].event_kind, OutboundEventKind::ToolCall);
assert_eq!(outbound[0].tool_name.as_deref(), Some("calculator"));
assert_eq!(outbound[0].tool_arguments.as_ref().unwrap()["expression"], "1 + 1");
assert_eq!(outbound[0].content, "### calculator\n- expression: 1 + 1");
assert_eq!(outbound[0].content, "calculator\nargs: {\"expression\":\"1 + 1\"}");
assert_eq!(outbound[1].tool_name.as_deref(), Some("file_read"));
assert_eq!(outbound[1].content, "### file_read\n- path: README.md");
assert_eq!(outbound[1].content, "file_read\nargs: {\"path\":\"README.md\"}");
}
#[test]