Files
magpie/internal/gateway/chat_tool_shape.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

94 lines
2.5 KiB
Go

package gateway
import (
"encoding/json"
"github.com/tidwall/gjson"
)
// A Chat Completions tool is {"type":"function","function":{name,
// description, parameters, strict}}. Some clients send theirs in another
// API's shape on the Chat route: MCP's {"name","description","inputSchema"}
// (ZCode, #2622), Anthropic's input_schema, a bare {"name","parameters"},
// or Responses' flat {"type":"function","name",…}. OpenAI and the strict
// Chat APIs turn every one of those away (SenseNova: "field Tools[0].Type
// invalid, should be set", "function cannot be empty"), and parseChat read
// no name from them, so a translated request offered a tool with none.
// shapeChatTools is a Chat request with each such tool in the Chat shape.
// A tool that already has its function object, a hosted tool (any other
// type), one with no name, and a request that doesn't parse are as they
// came; a tool's other fields stay beside its function.
func shapeChatTools(body []byte) []byte {
if !bodyHas(body, `"tools"`) {
return body
}
tools := gjson.GetBytes(body, "tools")
if !tools.IsArray() {
return body
}
need := false
for _, t := range tools.Array() {
if unshapedChatTool(t) {
need = true
break
}
}
if !need {
return body
}
var raw []json.RawMessage
if json.Unmarshal([]byte(tools.Raw), &raw) != nil {
return body
}
for i, t := range raw {
if !unshapedChatTool(gjson.ParseBytes(t)) {
continue
}
var m map[string]json.RawMessage
if json.Unmarshal(t, &m) != nil {
continue
}
fn := map[string]json.RawMessage{}
for _, k := range []string{"name", "description", "strict"} {
if v, ok := m[k]; ok {
fn[k] = v
delete(m, k)
}
}
for _, k := range []string{"parameters", "inputSchema", "input_schema"} {
if v, ok := m[k]; ok {
if _, set := fn["parameters"]; !set {
fn["parameters"] = v
}
delete(m, k)
}
}
f, err := marshalPlain(fn)
if err != nil {
continue
}
m["type"] = json.RawMessage(`"function"`)
m["function"] = f
out, err := marshalPlain(m)
if err != nil {
continue
}
raw[i] = out
}
return withFields(body, map[string]any{"tools": raw})
}
// unshapedChatTool is whether t is a function tool with its name at the
// top rather than in a function object.
func unshapedChatTool(t gjson.Result) bool {
if !t.IsObject() || t.Get("function").Exists() {
return false
}
if typ := t.Get("type").String(); typ != "" && typ != "function" {
return false
}
n := t.Get("name")
return n.Type == gjson.String && n.String() != ""
}