Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

tools: ignore braces inside JSON strings when detecting tool call end (#16937)

Aditya Aggarwal32a97b749378
diff --git a/tools/tools.go b/tools/tools.go
index c319a6d44..b8ea767da 100644
--- a/tools/tools.go
+++ b/tools/tools.go
@@ -358,7 +358,23 @@ func (p *Parser) done() bool {
}
var count int
+ var inString, escaped bool
for _, c := range p.buffer {
+ if escaped {
+ escaped = false
+ continue
+ }
+ if c == '\\' {
+ escaped = true
+ continue
+ }
+ if c == '"' {
+ inString = !inString
+ continue
+ }
+ if inString {
+ continue
+ }
if c == byte(open) {
count++
} else if c == byte(close) {
diff --git a/tools/tools_test.go b/tools/tools_test.go
index 2b8b04f8b..689d65172 100644
--- a/tools/tools_test.go
+++ b/tools/tools_test.go
@@ -842,6 +842,24 @@ func TestDone(t *testing.T) {
buffer: []byte("[]"),
want: true,
},
+ {
+ name: "json close brace inside string",
+ tag: "{",
+ buffer: []byte("{\"note\": \"a}b\""),
+ want: false,
+ },
+ {
+ name: "json complete with brace inside string",
+ tag: "{",
+ buffer: []byte("{\"note\": \"a}b\"}"),
+ want: true,
+ },
+ {
+ name: "list close bracket inside string",
+ tag: "[",
+ buffer: []byte("[{\"note\": \"x]y\"}"),
+ want: false,
+ },
}
for _, tt := range tests {