Skip to content
Open
Show file tree
Hide file tree
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
10 changes: 10 additions & 0 deletions changelog/unreleased/toolcall-contract-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### English

- Add `internal/toolcall`: one canonical model of tool declarations, tool choice, argument repair, native call identity and rendering, so protocols stop each re-implementing the contract.
- Validate `tools`, `tool_choice` and `parallel_tool_calls` through that parser in the shared chat-request validation every protocol entry runs, so an orphan `auto` degrades to unspecified while `required` or a named choice fails instead of silently dropping the tool request.

### 中文

- 新增 `internal/toolcall`:工具声明、工具选择、参数修复、原生调用身份与渲染只有一份规范模型,协议层不再各自实现这套契约。
- Responses 入口与各协议的共用请求校验都通过该解析器校验 `tools`、`tool_choice`、`parallel_tool_calls`:孤立的 `auto` 降级为未指定,`required` 或指定工具则校验失败,不再静默丢弃工具请求。

193 changes: 193 additions & 0 deletions internal/toolcall/args.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package toolcall

import (
"encoding/json"
"strings"
)

const maxCloseClosers = 24

// RepairArguments attempts formatting-level repair only. It returns ok=false
// when a value was cut mid-string, so callers never receive a value the model
// did not finish writing.
func RepairArguments(raw string) (string, bool) {
text := strings.TrimSpace(raw)
if text == "" {
return "{}", true
}
if json.Valid([]byte(text)) {
return text, true
}
candidates := argumentRepairCandidates(text)
for _, candidate := range candidates {
if json.Valid([]byte(candidate)) {
return candidate, true
}
}
for _, candidate := range candidates {
if closed, ok := closeArgumentTail(candidate); ok {
return closed, true
}
}
if prefix, ok := decodeArgumentPrefix(text); ok {
return prefix, true
}
return "", false
}

func decodeArgumentPrefix(text string) (string, bool) {
decoder := json.NewDecoder(strings.NewReader(text))
var value any
if err := decoder.Decode(&value); err != nil {
return "", false
}
var extra any
if err := decoder.Decode(&extra); err == nil {
return "", false
}
encoded, err := json.Marshal(value)
if err != nil {
return "", false
}
return string(encoded), true
}

func argumentRepairCandidates(text string) []string {
candidates := []string{text}
if withoutTrailing := stripTrailingCommas(text); withoutTrailing != text {
candidates = append(candidates, withoutTrailing)
}
if escaped := escapeBareQuotes(text); escaped != text {
candidates = append(candidates, escaped, stripTrailingCommas(escaped))
}
return candidates
}

// stripTrailingCommas removes `,` that directly precede a closing brace or
// bracket, which models emit routinely and strict JSON rejects.
func stripTrailingCommas(text string) string {
var out strings.Builder
out.Grow(len(text))
for index := 0; index < len(text); index++ {
character := text[index]
if character == ',' {
next := index + 1
for next < len(text) && isJSONSpace(text[next]) {
next++
}
if next < len(text) && (text[next] == '}' || text[next] == ']') {
continue
}
}
out.WriteByte(character)
}
return out.String()
}

// escapeBareQuotes escapes `"` characters that appear inside a JSON string
// value. A closing quote is accepted only when the next non-space byte is one
// of `, } ] :` or the end of the buffer.
func escapeBareQuotes(text string) string {
var out strings.Builder
out.Grow(len(text))
inString := false
for index := 0; index < len(text); {
character := text[index]
if !inString {
out.WriteByte(character)
if character == '"' {
inString = true
}
index++
continue
}
if character == '\\' && index+1 < len(text) {
out.WriteString(text[index : index+2])
index += 2
continue
}
if character == '"' {
next := index + 1
for next < len(text) && isJSONSpace(text[next]) {
next++
}
if next >= len(text) || strings.IndexByte(",}]:", text[next]) >= 0 {
out.WriteByte(character)
inString = false
} else {
out.WriteString(`\"`)
}
index++
continue
}
out.WriteByte(character)
index++
}
return out.String()
}

// closeArgumentTail appends the closers the model never got to emit, but only
// when no string is left open - a value cut mid-string stays unrepaired.
func closeArgumentTail(text string) (string, bool) {
stack := make([]byte, 0, maxCloseClosers)
var out strings.Builder
out.Grow(len(text) + maxCloseClosers)
inString := false
for index := 0; index < len(text); index++ {
character := text[index]
if inString {
out.WriteByte(character)
if character == '\\' && index+1 < len(text) {
out.WriteByte(text[index+1])
index++
continue
}
if character == '"' {
inString = false
}
continue
}
switch character {
case '"':
inString = true
out.WriteByte(character)
case '{', '[':
if len(stack) >= maxCloseClosers {
return "", false
}
stack = append(stack, character)
out.WriteByte(character)
case '}', ']':
if len(stack) == 0 {
return "", false
}
open := stack[len(stack)-1]
if (character == '}' && open != '{') || (character == ']' && open != '[') {
return "", false
}
stack = stack[:len(stack)-1]
out.WriteByte(character)
default:
out.WriteByte(character)
}
}
if inString || len(stack) == 0 {
return "", false
}
for index := len(stack) - 1; index >= 0; index-- {
if stack[index] == '{' {
out.WriteString("}")
} else {
out.WriteString("]")
}
}
closed := stripTrailingCommas(out.String())
if json.Valid([]byte(closed)) {
return closed, true
}
return "", false
}

func isJSONSpace(character byte) bool {
return character == ' ' || character == '\t' || character == '\n' || character == '\r'
}
Loading
Loading