Files
magpie/internal/gateway/message_tools.go
T
yetone 63c91cae5f gateway: the body's key checks look for the needle's rarest byte
Each request ran ~45 bytes.Contains over its whole body to ask whether
a key is there at all ("developer", "compaction, "display", the
passthrough key...). Most needles begin with a quote, JSON's commonest
byte, so bytes.Index stopped at every quote, gave up on that and
compared at every byte: on a 2 MB body ~9 ms a request, 36% of the
gateway's CPU in BenchmarkLargeRequest's profile.

bodyHas/bodyIndex find the needle's rarest byte (a static rank of the
bytes JSON, English and code use most) with IndexByte and compare the
needle only there; a needle of common bytes only hands the rest to
strings.Index after 64 misses, so it is never slower than before, and
it allocates nothing (a []byte(sep) of a needle over 32 bytes did).
148 literal and constant needles in internal/gateway use it, and
mayHoldHEIC's "eXB" walk uses bodyIndex.

mayHoldOddBase64 walked every byte through a switch (~2 ms a 2 MB
body); a run it looks for ends a string, so it now looks back from each
quote with a class table and gives the same answer.

Run on mica (Apple M6) at this tree:
- BenchmarkBodyHas, 7 needles over a 2 MB body: 4.43 ms -> 0.38 ms,
  0 allocs (was 1).
- BenchmarkLargeRequest -benchtime 200x, before -> after:
  anthropic 31.2 -> 28.9 ms, anthropic-group 31.4 -> 27.8,
  chat 35.7 -> 32.8, responses 39.8 -> 29.8.
- go vet ./internal/gateway; gofmt -l clean.
- go test ./internal/gateway -count 1 -timeout 45m: ok (858s).
- Broken by hand: bodyIndex's start off by one -> TestBodyIndexIsIndex
  red (wrong index on 5 needles and the random bodies); the URL-safe
  class never counted -> TestOddBase64LooksAsItWalked red. Both green
  again restored.

TestBodyIndexIsIndex holds bodyIndex to bytes.Index on a large
conversation and 3000 random bodies of common and rare bytes;
TestOddBase64LooksAsItWalked holds the new check to the old byte walk
(kept in the test) on 20000 random bodies and the three protocols'
large conversations.

Real account: the built app (mote, sandbox HOME) sent a 6KB request to
DeepSeek on /v1/responses and /v1/messages, both 200 "pong". Not
tried: Codex (the sandbox's sign-in is stale, and renewing it there
would rotate the live refresh token).
2026-11-14 05:51:42 +08:00

98 lines
2.8 KiB
Go

package gateway
import (
"encoding/json"
"github.com/tidwall/gjson"
)
// Pi with supportsMidConvoToolAdditions on gives a tool it adds during a
// conversation in a message of its own, not in the request's tools, which
// it keeps as they were at the start (#2322, Pi 1.2.0):
//
// {"role":"system","tools":[{"type":"function","function":{…}}]}
//
// No Chat Completions API reads tools there (OpenAI turns a system message
// with no content away), and parseChat read only the request's own tools,
// so the model could never call the tool on any route. Such tools join the
// request's tools as Codex's additional_tools do (liftAdditionalTools).
// liftMessageTools is a Chat request with the tools its messages carry
// moved into its own tools, each once by name: a tool the request already
// has, or an earlier message gave, keeps that first definition, as a
// tool_addition's does (withoutDeferredTools). A system or developer
// message that carried only tools is left out, rather than sent on as an
// empty system message; one with content keeps its place without its
// tools. A request with no message tools, or one that doesn't parse, is
// as it came.
func liftMessageTools(body []byte) []byte {
if !bodyHas(body, `"tools"`) {
return body
}
if len(gjson.GetBytes(body, "messages.#.tools").Array()) == 0 {
return body
}
var v struct {
Messages []json.RawMessage `json:"messages"`
Tools []json.RawMessage `json:"tools"`
}
if json.Unmarshal(body, &v) != nil {
return body
}
have := map[string]bool{}
for _, t := range v.Tools {
have[chatToolKey(gjson.ParseBytes(t))] = true
}
tools := v.Tools
msgs := make([]json.RawMessage, 0, len(v.Messages))
for _, raw := range v.Messages {
m := gjson.ParseBytes(raw)
more := m.Get("tools")
if !more.Exists() {
msgs = append(msgs, raw)
continue
}
for _, t := range more.Array() {
if !t.IsObject() {
continue
}
if k := chatToolKey(t); !have[k] {
have[k] = true
tools = append(tools, json.RawMessage(t.Raw))
}
}
role := m.Get("role").String()
if (role == "system" || role == "developer") && emptyContent(m.Get("content")) {
continue
}
var mm map[string]json.RawMessage
if json.Unmarshal(raw, &mm) != nil {
msgs = append(msgs, raw)
continue
}
delete(mm, "tools")
out, err := marshalPlain(mm)
if err != nil {
return body
}
msgs = append(msgs, out)
}
fields := map[string]any{"messages": msgs}
if len(tools) > 0 {
fields["tools"] = tools
}
return withFields(body, fields)
}
// chatToolKey is a Chat tool's name, a hosted tool's without one by its
// type.
func chatToolKey(t gjson.Result) string {
if n := t.Get("function.name").String(); n != "" {
return n
}
if n := t.Get("name").String(); n != "" {
return n
}
return "#" + t.Get("type").String()
}