Skip to content
Merged
Changes from all commits
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
40 changes: 37 additions & 3 deletions src/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -746,10 +746,14 @@ fn xml_partial(r: &str, tools: &[Json]) -> Option<(String, String)> {
continue;
}
if props.get(k).get("type").as_str() == Some("string") {
// The value so far, less a tail that could still be the `\n</parameter>` that ends it.
// Hold back a tail that could still be the closing tag, with or without its preceding newline.
let v = x.strip_prefix('\n').unwrap_or(x);
let end = "\n</parameter>";
let hold = (1..=end.len().min(v.len())).rev().find(|&n| v.ends_with(&end[..n])).unwrap_or(0);
let mut hold = 0;
for end in ["\n</parameter>", "</parameter>"] {
if let Some(n) = (1..=end.len().min(v.len())).rev().find(|&n| v.ends_with(&end[..n])) {
hold = hold.max(n);
}
}
let q = key(&v[..v.len() - hold]);
s += &format!("{sep}{}: {}", key(k), &q[..q.len() - 1]);
}
Expand Down Expand Up @@ -890,6 +894,36 @@ mod think_tests {
assert_eq!(Template::Xml.partial_calls(text, &tools), done);
assert!(Template::Xml.partial_calls("<tool_call>\n<function=other>\n<parameter=a>\nx", &tools).is_empty());
}
/// Issue 247: an empty string parameter has no value newline before its closing tag.
#[test]
fn partial_empty_string_parameter_does_not_leak_closing_tag() {
let tools: Vec<Json> = serde_json::from_str(r#"[{"type":"function","function":{"name":"edit","parameters":{"properties":
{"file_path":{"type":"string"},"new_string":{"type":"string"},"old_string":{"type":"string"}}}}}]"#).unwrap();
let close = "</parameter>";
let text = format!(
"<tool_call>\n<function=edit>\n<parameter=file_path>\nreport.js\n{close}\n<parameter=new_string>\n{close}\n<parameter=old_string>\nlegacy\n{close}\n</function>\n</tool_call>"
);
let (_, done) = Template::Xml.parse_calls(&text, &tools).unwrap();
let args: Json = serde_json::from_str(&done[0].1).unwrap();
assert_eq!(args.get("new_string").as_str(), Some(""));
assert_eq!(args.get("old_string").as_str(), Some("legacy"));

for (p, _) in text.char_indices() {
let partial = Template::Xml.partial_calls(&text[..p], &tools);
if partial.is_empty() {
continue;
}
assert_eq!(partial.len(), 1);
assert_eq!(partial[0].0, "edit");
assert!(
done[0].1.starts_with(&partial[0].1),
"at byte {p}: {:?} is not a prefix of {:?}",
partial[0].1,
done[0].1
);
}
}

#[test]
fn image_source_must_be_a_url() {
let req = |url: &str| crate::serve::chat_request(format!(r#"{{"messages":[{{"role":"user","content":[{{"type":"image_url","image_url":{{"url":"{url}"}}}}]}}]}}"#).as_bytes());
Expand Down