-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoolcall.go
More file actions
55 lines (46 loc) · 1.79 KB
/
Copy pathtoolcall.go
File metadata and controls
55 lines (46 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"regexp"
"strings"
)
const zeroWidthSpace = "\u200B"
// reBrokenClose matches: ]</ + (zero-width-space) + whitespace + <tool_calls>
// e.g. "]\u200B\n<tool_calls>" — model tries to close but inserts zero-width space
var reBrokenClose = regexp.MustCompile(
`\]</` + zeroWidthSpace + `\s*` + regexp.QuoteMeta("<tool_calls>"),
)
// reBrokenWhitespace matches: ]</ + whitespace + <tool_calls>
// e.g. "]</ \n<tool_calls>" — model uses whitespace instead of tag name
var reBrokenWhitespace = regexp.MustCompile(
`\]</\s+` + regexp.QuoteMeta("<tool_calls>"),
)
// reUnclosedTag matches: ]</ + any tag name (letters) + whitespace + <tool_calls>
// e.g. "]</tagname\n<tool_calls>" — model writes a tag name but never closes it
var reUnclosedTag = regexp.MustCompile(
`\]</[a-zA-Z]+\s*` + regexp.QuoteMeta("<tool_calls>"),
)
// FixToolCallXML repairs malformed XML tool call blocks generated by some
// models (e.g. DeepSeek) that omit proper closing tags.
//
// The typical failure mode:
//
// <tool_calls>
// <invoke name="edit">
// <parameter name="edits" string="false">[{"newText":"...","oldText":"..."}]</
// <tool_calls>
// <invoke name="edit">...
//
// Instead of </parameter></invoke></tool_calls>, the model writes a broken
// closing tag (zero-width space + / + whitespace) and starts a new block.
// This function replaces the broken pattern with proper closing tags
// followed by the new block opener.
func FixToolCallXML(text string) string {
if !strings.Contains(text, "<tool_calls>") {
return text
}
replacement := `]</parameter></invoke></tool_calls>` + "\n" + `<tool_calls>`
text = reBrokenClose.ReplaceAllString(text, replacement)
text = reBrokenWhitespace.ReplaceAllString(text, replacement)
text = reUnclosedTag.ReplaceAllString(text, replacement)
return text
}