gateway: a Chat request's tool pairs are checked without decoding it
toolPairsOut decoded every Chat request that mentions a tool into
[]map[string]any to learn whether its calls are answered, which they
nearly always are: 0.79s of 5.1s in BenchmarkLargeRequest/chat, ~10 MB
of allocations a 2 MB request. rawToolsPaired reads the roles, the
tool_call_id and the calls' ids from the body as it came, and the
decoding path runs only when they aren't paired, or for a shape it
would read differently (a message that isn't an object, tool_calls
that aren't a list of objects). A key named twice counts as its last,
as decoding into a map does.
BenchmarkLargeRequest/chat on mica, 200x: 28.1 -> 23.4 ms, 33.7 ->
23.8 MB and 94.5k -> 69.4k allocations a request; the other protocols
are unchanged.
TestRawToolsPairedAsDecoded holds it to the decoding path's answer on
20000 random conversations (answered twice, out of order, left open,
ids repeated, missing or not strings, escaped roles, null messages).
Broken by hand (a repeated id no longer refuses the pairing) it is red;
restored, green.
Real account: the built app (mote, sandbox HOME) sent DeepSeek a 6KB
/v1/chat/completions request with tools and a call answered ("It's
18°C and sunny in Paris.", 200), and one with the call left unanswered,
which the decoding path still mends (200, "the request was
interrupted").
Run (mica, at this head): gofmt -l clean, go vet ./internal/gateway for
darwin, linux and windows, go test -count=1 ./internal/gateway ok (858s).
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user