diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go index 7b4a15c3b..8eaedebd4 100644 --- a/internal/gateway/chattidy.go +++ b/internal/gateway/chattidy.go @@ -1146,6 +1146,9 @@ func toolPairsOut(body []byte) []byte { if !bodyHas(body, `"tool`) { return body } + if paired, ok := rawToolsPaired(body); ok && paired { + return body + } var q map[string]json.RawMessage if decodeJSON(body, &q) != nil { return body @@ -1238,6 +1241,111 @@ func toolsPaired(msgs []map[string]any) bool { return closed() } +// rawToolsPaired is toolsPaired read from the body as it came, without +// decoding the conversation into maps: what nearly every request with +// tools needs, since its calls are paired already. ok is false for any +// shape the decoding path would read differently or turn away (a message +// that isn't an object, tool_calls that aren't a list of objects), which +// leaves the answer to that path. A key named twice counts as its last, +// as decoding into a map does. +func rawToolsPaired(body []byte) (paired, ok bool) { + msgs, found, valid := topMember(body, "messages") + if !valid || !found || len(msgs) == 0 || msgs[0] != '[' { + return false, false + } + type msg struct { + role, toolID string + ids []string + } + str := func(v []byte) string { + if len(v) == 0 || v[0] != '"' { + return "" + } + s, _ := unquoteJSON(v) + return s + } + var list []msg + ok = true + eachElement(msgs, func(el []byte) bool { + if el[0] != '{' { + ok = false + return false + } + var m msg + var calls []byte + eachMember(el, func(k, v []byte) bool { + switch { + case keyIs(k, "role"): + m.role = str(v) + case keyIs(k, "tool_call_id"): + m.toolID = str(v) + case keyIs(k, "tool_calls"): + calls = v + } + return true + }) + if len(calls) > 0 && string(calls) != "null" { + if calls[0] != '[' { + ok = false + return false + } + m.ids = []string{} + eachElement(calls, func(c []byte) bool { + if c[0] != '{' { + ok = false + return false + } + id := "" + eachMember(c, func(k, v []byte) bool { + if keyIs(k, "id") { + id = str(v) + } + return true + }) + m.ids = append(m.ids, id) + return true + }) + } + list = append(list, m) + return ok + }) + if !ok { + return false, false + } + var pending map[string]bool + closed := func() bool { + for _, open := range pending { + if open { + return false + } + } + pending = nil + return true + } + for _, m := range list { + if m.role == "tool" { + if !pending[m.toolID] { + return false, true + } + pending[m.toolID] = false + continue + } + if !closed() { + return false, true + } + if m.role == "assistant" && len(m.ids) > 0 { + pending = map[string]bool{} + for _, id := range m.ids { + if _, twice := pending[id]; twice { + return false, true + } + pending[id] = true + } + } + } + return closed(), true +} + // joinSplitChatCalls joins a turn's calls split over consecutive // assistant messages into the first, as joinSplitCalls does for the // translations (#1275): the second message's calls follow the first's, diff --git a/internal/gateway/tools_paired_raw_test.go b/internal/gateway/tools_paired_raw_test.go new file mode 100644 index 000000000..7bbdfe1f1 --- /dev/null +++ b/internal/gateway/tools_paired_raw_test.go @@ -0,0 +1,113 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "fmt" + "math/rand/v2" + "strings" + "testing" +) + +// decodedToolsPaired is the answer toolPairsOut's decoding path gives: +// ok false where it returns the body for a shape it can't read. +func decodedToolsPaired(body []byte) (paired, ok bool) { + var q map[string]json.RawMessage + if decodeJSON(body, &q) != nil { + return false, false + } + dec := json.NewDecoder(bytes.NewReader(q["messages"])) + var msgs []map[string]any + if dec.Decode(&msgs) != nil { + return false, false + } + for _, m := range msgs { + if m == nil { + return false, false + } + raw, has := m["tool_calls"] + if !has || raw == nil { + continue + } + list, isList := raw.([]any) + if !isList { + return false, false + } + calls := []map[string]any{} + for _, c := range list { + cm, isObj := c.(map[string]any) + if !isObj { + return false, false + } + calls = append(calls, cm) + } + m["tool_calls"] = calls + } + return toolsPaired(msgs), true +} + +// TestRawToolsPairedAsDecoded holds rawToolsPaired to the decoding path +// on random conversations: calls answered, answered twice, out of order, +// left open, ids repeated or missing, and odd shapes. +func TestRawToolsPairedAsDecoded(t *testing.T) { + r := rand.New(rand.NewPCG(5, 6)) + ids := []string{`"a"`, `"b"`, `"c"`, `""`, `1`, `null`, `"ab"`} + roles := []string{`"user"`, `"assistant"`, `"tool"`, `"system"`, `null`, `"tool"`} + yes, no := 0, 0 + for range 20000 { + var ms []string + for range r.IntN(8) { + var f []string + if r.IntN(10) > 0 { + f = append(f, `"role":`+roles[r.IntN(len(roles))]) + } + if r.IntN(3) == 0 { + f = append(f, `"tool_call_id":`+ids[r.IntN(len(ids))]) + } + switch r.IntN(6) { + case 0, 1: + var cs []string + for range r.IntN(4) { + if r.IntN(15) == 0 { + cs = append(cs, `"x"`) + continue + } + cs = append(cs, `{"id":`+ids[r.IntN(len(ids))]+`,"type":"function"}`) + } + f = append(f, `"tool_calls":[`+strings.Join(cs, ",")+`]`) + case 2: + f = append(f, `"tool_calls":null`) + case 3: + if r.IntN(5) == 0 { + f = append(f, `"tool_calls":{}`) + } + } + if r.IntN(8) == 0 && len(f) > 0 { + f = append(f, f[0]) // a key named twice + } + r.Shuffle(len(f), func(i, j int) { f[i], f[j] = f[j], f[i] }) + m := "{" + strings.Join(f, ",") + "}" + if r.IntN(40) == 0 { + m = "null" + } + ms = append(ms, m) + } + body := []byte(fmt.Sprintf(`{"model":"m","tools":[],"messages":[%s]}`, strings.Join(ms, ","))) + got, gotOK := rawToolsPaired(body) + want, wantOK := decodedToolsPaired(body) + if !gotOK { + continue // the decoding path answers these + } + if !wantOK || got != want { + t.Fatalf("rawToolsPaired = %v, %v; decoded %v, %v for %s", got, gotOK, want, wantOK, body) + } + if got { + yes++ + } else { + no++ + } + } + if yes < 1000 || no < 1000 { + t.Fatalf("paired %d, unpaired %d: the test reaches too little", yes, no) + } +}