firstBalancedObject 返回与首个 { 配对的 } 索引;解析失败返回 -1。 处理引号和反斜杠转义。
(s string)
| 251 | // firstBalancedObject 返回与首个 { 配对的 } 索引;解析失败返回 -1。 |
| 252 | // 处理引号和反斜杠转义。 |
| 253 | func firstBalancedObject(s string) int { |
| 254 | depth := 0 |
| 255 | inStr := false |
| 256 | esc := false |
| 257 | for i := 0; i < len(s); i++ { |
| 258 | c := s[i] |
| 259 | if esc { |
| 260 | esc = false |
| 261 | continue |
| 262 | } |
| 263 | if c == '\\' { |
| 264 | esc = true |
| 265 | continue |
| 266 | } |
| 267 | if c == '"' { |
| 268 | inStr = !inStr |
| 269 | continue |
| 270 | } |
| 271 | if inStr { |
| 272 | continue |
| 273 | } |
| 274 | switch c { |
| 275 | case '{': |
| 276 | depth++ |
| 277 | case '}': |
| 278 | depth-- |
| 279 | if depth == 0 { |
| 280 | return i |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | return -1 |
| 285 | } |
| 286 | |
| 287 | // buildToolCallFromObject 从 map 抽出 name + arguments 拼成 ToolCall。 |
| 288 | // 兼容字段别名: name / tool / tool_name / function。 |