diff --git a/internal/gateway/call_ids_set_test.go b/internal/gateway/call_ids_set_test.go new file mode 100644 index 000000000..09a8727ac --- /dev/null +++ b/internal/gateway/call_ids_set_test.go @@ -0,0 +1,85 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "math/rand/v2" + "strings" + "testing" +) + +// TestCallIDsSetNeverSkipsAnEdit holds callIDsSet to giveCallIDs: a body +// it calls set comes back from the decode byte for byte. The ids, roles +// and keys are drawn so both answers, and edits, come often. +func TestCallIDsSetNeverSkipsAnEdit(t *testing.T) { + r := rand.New(rand.NewPCG(5, 6)) + pick := func(xs ...string) string { return xs[r.IntN(len(xs))] } + id := func() string { + return pick(`"call_1"`, `"call_2"`, `""`, `null`, `7`, `"cx"`, `{}`) + } + set, unset, edited := 0, 0, 0 + for range 20000 { + var msgs []string + for range 1 + r.IntN(6) { + switch r.IntN(5) { + case 0: + msgs = append(msgs, `{"role":"user","content":"hi"}`) + case 1, 2: + var calls []string + for range r.IntN(3) { + c := `{"type":"function","function":{"name":"f","arguments":"{}"}` + if r.IntN(8) > 0 { + c += `,` + pick(`"id"`, `"id"`, `"ID"`) + `:` + id() + } + calls = append(calls, c+`}`) + } + m := `{"role":` + pick(`"assistant"`, `"assistant"`, `"user"`) + `,"content":null` + switch r.IntN(6) { + case 0: + m += `,"tool_calls":null` + case 1: + m += `,"tool_calls":` + pick(`{}`, `"x"`, `[1]`) + default: + m += `,"tool_calls":[` + strings.Join(calls, ",") + `]` + } + msgs = append(msgs, m+`}`) + case 3: + m := `{"role":` + pick(`"tool"`, `"tool"`) + `,"content":"ok"` + if r.IntN(6) > 0 { + m += `,` + pick(`"tool_call_id"`, `"tool_call_id"`) + `:` + id() + } + msgs = append(msgs, m+`}`) + default: + msgs = append(msgs, pick(`7`, `null`, `{"role":"tool"}`, `{"role":7,"tool_calls":[{"id":""}]}`)) + } + } + body := []byte(`{"model":"m","messages":[` + strings.Join(msgs, ",") + `]}`) + if !json.Valid(body) { + t.Fatalf("invalid fixture %s", body) + } + got := giveCallIDs(bytes.Clone(body)) + changed := !bytes.Equal(got, body) + if changed { + edited++ + } + if callIDsSet(body) { + set++ + if changed { + t.Fatalf("callIDsSet(%s) but the decode gives\n%s", body, got) + } + } else { + unset++ + } + if out := chatCallIDs(bytes.Clone(body)); !bytes.Equal(out, got) { + t.Fatalf("chatCallIDs(%s) = %s, want %s", body, out, got) + } + } + if set < 1000 || unset < 1000 || edited < 1000 { + t.Fatalf("set %d, unset %d, edited %d: the test reaches too little", set, unset, edited) + } + for _, b := range []string{`{"model":"m"}`, `{"messages":null}`, `{"messages":{}}`, `[]`} { + if got := chatCallIDs([]byte(b)); string(got) != b { + t.Errorf("chatCallIDs(%s) = %s", b, got) + } + } +} diff --git a/internal/gateway/chat_call_ids.go b/internal/gateway/chat_call_ids.go index 6e4b2e431..60cb328b5 100644 --- a/internal/gateway/chat_call_ids.go +++ b/internal/gateway/chat_call_ids.go @@ -20,6 +20,14 @@ import ( // Chat request, relayed or translated, a plugin's included. A body whose // calls all have ids comes back byte for byte. func chatCallIDs(body []byte) []byte { + if callIDsSet(body) { + return body + } + return giveCallIDs(body) +} + +// giveCallIDs is chatCallIDs past its check, decoding every message. +func giveCallIDs(body []byte) []byte { at := -1 var open []string // the latest call turn's made ids no result has taken yet return editMessages(body, []string{"tool_calls"}, func(m map[string]json.RawMessage) bool { @@ -179,3 +187,57 @@ func wholeNamedCall(msg map[string]json.RawMessage) bool { } return false } + +// callIDsSet says, without decoding body, that chatCallIDs has nothing to +// give: every call has a non-empty string id, so no tool message after +// one is given an id either. False is "maybe": the decode decides. +// Nearly every request with tools is so, and decoding each message to +// see was ~17% of a 2 MB Chat request's CPU. +func callIDsSet(body []byte) bool { + msgs, found, valid := topMember(body, "messages") + if !valid || !found || len(msgs) == 0 || msgs[0] != '[' { + return !found && valid + } + set := func(v []byte) bool { + s, ok := stringBytes(v) + return ok && len(s) > 0 + } + all := true + eachElement(msgs, func(el []byte) bool { + if el[0] != '{' { + all = false + return false + } + var calls []byte + eachMember(el, func(k, v []byte) bool { + if keyIs(k, "tool_calls") { + calls = v + } + return true + }) + if len(calls) == 0 || string(calls) == "null" { + return true + } + if calls[0] != '[' { + all = false + return false + } + eachElement(calls, func(c []byte) bool { + if c[0] != '{' { + all = false + return false + } + var id []byte + eachMember(c, func(k, v []byte) bool { + if keyIs(k, "id") { + id = v + } + return true + }) + all = set(id) + return all + }) + return all + }) + return all +} diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go index 8eaedebd4..7ee1c6f44 100644 --- a/internal/gateway/chattidy.go +++ b/internal/gateway/chattidy.go @@ -897,7 +897,7 @@ func silentAssistantsOut(body []byte) []byte { return body } var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil || !anySilentAssistant(q["messages"]) { + if decodeJSONView(body, &q) != nil || !anySilentAssistant(q["messages"]) { return body } dec := json.NewDecoder(bytes.NewReader(q["messages"])) @@ -1028,7 +1028,10 @@ func withoutMessageReasoning(body []byte, fields []string) []byte { // editMessages hands each message of a Chat request whose JSON names any // of fields to edit, and puts back those edit reports it changed; every // other message keeps its bytes. The body comes back as it was if nothing -// changed. +// changed. What it decodes shares body's bytes (decodeJSONView): an edit +// replaces a member, never writes into one, and keeps none past its +// return, and a changed body is marshalled anew. A copy of each level +// was ~3.8 MB a request for a 2 MB Chat conversation. func editMessages(body []byte, fields []string, edit func(m map[string]json.RawMessage) bool) []byte { has := false for _, f := range fields { @@ -1038,17 +1041,17 @@ func editMessages(body []byte, fields []string, edit func(m map[string]json.RawM return body } var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return body } var msgs []json.RawMessage - if decodeJSON(q["messages"], &msgs) != nil { + if decodeJSONView(q["messages"], &msgs) != nil { return body } changed := false for i, raw := range msgs { var m map[string]json.RawMessage - if decodeJSON(raw, &m) != nil || !edit(m) { + if decodeJSONView(raw, &m) != nil || !edit(m) { continue } if nb, err := marshalPlain(m); err == nil {