gateway: a Chat tool call kept with an empty id goes with one made from its place (#2611, RunMintOn)

RunMintOn's session held an assistant turn whose tool call had "id":""
and a tool result with "tool_call_id":"". magpie relayed it unchanged on
Chat->Chat, and WorkBuddy AI turned the whole request away (400, 11133).
Chat->Messages sent tool_use id "" and Chat->Responses gave the call a
random id while its result kept "".

- chatCallIDs (chat_call_ids.go) runs in attempt for every Chat request,
  before the relay, the translation and a plugin's fetch alike (a moved
  WorkBuddy AI goes through the plugin, so the edit must come first). An
  empty, null or missing call id gets "call_" + a hash of the call's
  message index, position, name and arguments: the same on every resend,
  so the prompt-cache prefix holds. A result with an empty tool_call_id
  takes the turn's unanswered calls in order. A body that already has its
  ids comes back byte-identical.
- chatTidy gives a stream's first fragment of each (choice, index) call an
  id when the upstream sent none, and drops an empty id on later ones;
  chatWhole fills a whole reply's empty ids.
- docs/subsystems/gateway-routing.md says so.

Tests (chat_call_ids_test.go), fixtures from the issue's literal bytes,
against a fake that refuses as WorkBuddy AI does:
- TestEmptyCallIDRelayedWithOne, TestEmptyCallIDReachesPluginWithOne
  (movedFake workbuddy-ai), TestEmptyCallIDTranslatedWithOne (messages,
  responses), TestChatCallIDsLeavesWhatHasIDs, TestStreamedCallGivenAnID,
  TestWholeReplyCallGivenAnID.
- Broken by hand, each watched red: edit removed (relay and plugin get
  the 400; translations send an empty or unpaired id); a random id in
  place of the placed one ("the made id changed between requests");
  stream mend off (first fragments' ids ""); whole mend off ("id":"").

Run at this change on origin/main 81313b912:
- gofmt -l: nothing. go vet -tags nogui ./... on darwin, GOOS=linux and
  GOOS=windows: nothing.
- go test -tags nogui -timeout 45m ./...: 64 packages ok; internal/agent
  and internal/gateway failed on "no space left on device" (the disk
  filled under other sessions' runs: agent's testlog.txt write after
  PASS, gateway's TestRotateSpreadsABurstOfNewConversations renaming
  providers.json). Rerun with space free: internal/agent ok 652.9s,
  internal/gateway ok 732.9s.
- Not tried against a real WorkBuddy AI account (no live configs).
This commit is contained in:
yetone
2026-10-17 03:53:40 +08:00
parent 065fc7500d
commit a69cd07075
5 changed files with 465 additions and 10 deletions
+1
View File
@@ -134,6 +134,7 @@ recorded as a prediction failure (`noPrediction`).
- A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. A second answer to one call is left out, with the images it carried, before the turns are built (`dropSecondAnswers`, #2262): Google refuses a call turn whose `functionResponse` count differs from its `functionCall` count, and the Chat and Messages builds already keep the first answer. The Responses build (`buildResponses`) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (`parseGemini`), not both to the latest. `TestGeminiDropsASecondAnswer`, `TestSecondAnswerDroppedWithItsImages`, `TestGeminiClientUnnamedCallsAnsweredInOrder`.
- A request built for a Messages upstream (`buildAnthropic`: a Chat, Responses or Gemini client translated, and Zed's bridge) has its tool exchanges mended after its messages are built (`pairToolBlocks`, #1558, ggbdpq), since Anthropic answers 400 for a `tool_use` the next message doesn't answer and for a `tool_result` naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, `is_error` set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. [`anthropic_tool_pairing_test.go`](../../internal/gateway/anthropic_tool_pairing_test.go).
- A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in `attempt`, before it is relayed or translated, plugins included ([`responses.go`](../../internal/gateway/responses.go)). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (`joinToolRuns`, #1752, Edward4226): Codex writes its `<image_resize_notice>` right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a `call_id` never moves, the model's own reasoning between its calls stays, and its text between them (an assistant message, with the reasoning right before it) goes ahead of the run's first call, so the step's calls stand together: OpenCode Go opens a new assistant message at such text and answered the call before it "No tool output found for tool call …" (#2100). A call opens a run only when a result after it answers it. A result with no call id becomes a user message after its run (`orphanedToolOutputs`), and a call nothing answers gets a synthetic result at the end of its run (`pairToolItems`, #1341). `TestRelayedCodexImageBatchKeepsItsResultsTogether`, `TestJoinToolRunsOnlyMovesWhatBreaksARun`, `TestRelayedTextBetweenABatchsCallsIsAnswered`.
- A Chat request has every tool call that came with no id (`""`, null or none) given one in `attempt`, before it is relayed or translated, plugins included (`chatCallIDs` in [`chat_call_ids.go`](../../internal/gateway/chat_call_ids.go), #2611, RunMintOn). An upstream that sometimes streams a call without an id (OpenCode Zen's free DeepSeek) has the agent keep it as `""`, which that upstream takes back, while WorkBuddy AI turns a streamed request carrying one away (400, code 11133) and Anthropic takes no empty `tool_use` id. The id is made from the call's place in the request, its name and its arguments, never at random, so the next turn's history goes byte for byte and the upstream's prompt cache holds; the tool messages after the call that answer with no `tool_call_id` take the made ids in the calls' order. A body whose calls all have ids goes as it came. On the reply side, a relayed Chat stream's call whose first fragment has no id is given one, and a later fragment's empty id is left out (`chatTidy`); a whole reply's call is given one too (`chatWhole`). `TestEmptyCallIDRelayedWithOne`, `TestEmptyCallIDReachesPluginWithOne`, `TestEmptyCallIDTranslatedWithOne`, `TestStreamedCallGivenAnID` in [`chat_call_ids_test.go`](../../internal/gateway/chat_call_ids_test.go).
- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
- Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts<n>__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/<key>`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__<key>`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Carrying reasoning across APIs (an envelope) isn't done.
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short). Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`.
+139
View File
@@ -0,0 +1,139 @@
package gateway
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"strconv"
)
// chatCallIDs gives every tool call of a Chat request that came with no
// id ("", null or none) one, and the tool messages after it that answer
// with no tool_call_id that same id, in the calls' order (#2611,
// RunMintOn). An upstream that sometimes leaves a streamed call's id out
// (OpenCode Zen's free DeepSeek) has the agent keep the call as "", which
// that upstream takes back; a strict one (WorkBuddy AI, 400 code 11133 on
// a streamed request) turns every later request of the session away. The
// id comes from the call's place in the request and what it says, never
// at random, so the next turn sends the same history byte for byte and
// the upstream's prompt cache still holds. It runs in attempt for every
// 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 {
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 {
at++
var role string
decodeJSON(m["role"], &role)
switch role {
case "assistant":
var calls []map[string]json.RawMessage
if decodeJSON(m["tool_calls"], &calls) != nil || len(calls) == 0 {
return false
}
open = nil
for i, c := range calls {
if callID(c["id"]) != "" {
continue
}
var fn struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
decodeJSON(c["function"], &fn)
id := placedCallID(at, i, fn.Name, string(fn.Arguments))
c["id"], _ = marshalPlain(id)
open = append(open, id)
}
if open == nil {
return false
}
m["tool_calls"], _ = marshalPlain(calls)
return true
case "tool":
if len(open) == 0 || callID(m["tool_call_id"]) != "" {
return false
}
m["tool_call_id"], _ = marshalPlain(open[0])
open = open[1:]
return true
}
return false
})
}
// callID reads a call's id or a result's tool_call_id: "" for none, null
// or anything but a string.
func callID(raw json.RawMessage) string {
var id string
decodeJSON(raw, &id)
return id
}
// placedCallID is the id chatCallIDs gives the i-th call of the message at
// msg: the same for the same call at the same place on every request.
func placedCallID(msg, i int, name, args string) string {
sum := sha256.Sum256([]byte(strconv.Itoa(msg) + "." + strconv.Itoa(i) + "\x00" + name + "\x00" + args))
return "call_" + hex.EncodeToString(sum[:12])
}
// streamCallIDs is what chatTidy keeps to give a streamed tool call the
// upstream sent no id for one: the calls seen, by choice and index.
type streamCallIDs map[[2]int]bool
// mend gives the first fragment of each call of a delta's tool_calls
// that has no id one, and leaves an empty id out of a later fragment,
// where a client that takes each field a fragment carries would write ""
// over it. It reports whether it changed any.
func (s streamCallIDs) mend(choice int, raw json.RawMessage) (json.RawMessage, bool) {
var calls []map[string]json.RawMessage
if decodeJSON(raw, &calls) != nil {
return raw, false
}
changed := false
for k, c := range calls {
idx := k
decodeJSON(c["index"], &idx)
key := [2]int{choice, idx}
idRaw, has := c["id"]
if !s[key] {
s[key] = true
if callID(idRaw) == "" {
c["id"], _ = marshalPlain("call_" + newID())
changed = true
}
} else if has && callID(idRaw) == "" {
delete(c, "id")
changed = true
}
}
if !changed {
return raw, false
}
out, err := json.Marshal(calls)
if err != nil {
return raw, false
}
return out, true
}
// wholeCallIDs gives each tool call of a whole reply's message that came
// with no id one, and reports whether it did.
func wholeCallIDs(msg map[string]json.RawMessage) bool {
var calls []map[string]json.RawMessage
if decodeJSON(msg["tool_calls"], &calls) != nil {
return false
}
changed := false
for _, c := range calls {
if callID(c["id"]) == "" {
c["id"], _ = marshalPlain("call_" + newID())
changed = true
}
}
if changed {
msg["tool_calls"], _ = marshalPlain(calls)
}
return changed
}
+286
View File
@@ -0,0 +1,286 @@
package gateway
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// #2611's minimal case, as RunMintOn sent it to WorkBuddy AI: a call Pi
// kept with an empty id (an OpenCode Zen free DeepSeek turn), its result
// with an empty tool_call_id, then the user. A turn of the same session
// whose calls came with ids follows, so a call's own id is seen to go as
// it was.
const emptyCallIDTurns = `{"model":"%s","stream":true,"messages":[
{"role":"user","content":"look at the toggle"},
{"role":"assistant","content":null,"tool_calls":[{"id":"","type":"function","function":{"name":"bash","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"","content":"out"},
{"role":"assistant","content":null,"reasoning_content":"Let me find providerSwitch(p)…","tool_calls":[{"id":"call_00_2omk8cv76gjjovgj3caocaif","type":"function","function":{"name":"bash","arguments":"{}"}},{"id":"call_01_h9qf0fe96gtektv6efu80mjt","type":"function","function":{"name":"bash","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"call_00_2omk8cv76gjjovgj3caocaif","content":"a"},
{"role":"tool","tool_call_id":"call_01_h9qf0fe96gtektv6efu80mjt","content":"b"},
{"role":"user","content":"你好"}]}`
// workBuddyPairing answers a streamed Chat request as WorkBuddy AI did
// for #2611: an empty call id, or a result naming no call of the turn
// before it, turns the request away.
func workBuddyPairing(body []byte) (int, string) {
var q struct {
Stream bool `json:"stream"`
Messages []struct {
Role string `json:"role"`
ToolCallID *string `json:"tool_call_id"`
ToolCalls []struct {
ID string `json:"id"`
} `json:"tool_calls"`
} `json:"messages"`
}
json.Unmarshal(body, &q)
refuse := `{"code":null,"message":"WorkBuddy AI: the request parameters were rejected by the model provider","param":null,"type":"invalid_request_error"}`
if !q.Stream {
return 0, ""
}
calls := map[string]bool{}
for _, m := range q.Messages {
switch m.Role {
case "assistant":
calls = map[string]bool{}
for _, c := range m.ToolCalls {
if c.ID == "" || calls[c.ID] {
return 400, refuse
}
calls[c.ID] = true
}
case "tool":
if m.ToolCallID == nil || !calls[*m.ToolCallID] {
return 400, refuse
}
}
}
return 0, ""
}
const chatStreamHello = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"m1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"你好\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
// sentCallIDs reads the ids of a sent Chat request's calls and results in
// order, "call:<id>" and "tool:<id>".
func sentCallIDs(t *testing.T, body []byte) []string {
t.Helper()
var ids []string
for _, raw := range sentMessages(t, body) {
var m struct {
ToolCallID *string `json:"tool_call_id"`
ToolCalls []struct {
ID string `json:"id"`
} `json:"tool_calls"`
}
json.Unmarshal(raw, &m)
for _, c := range m.ToolCalls {
ids = append(ids, "call:"+c.ID)
}
if m.ToolCallID != nil {
ids = append(ids, "tool:"+*m.ToolCallID)
}
}
return ids
}
// checkMadeIDs checks #2611's request went with an id made for its empty
// call, the same on its result, and the next turn's own ids as they were.
func checkMadeIDs(t *testing.T, ids []string) string {
t.Helper()
if len(ids) != 6 || ids[0] == "call:" || ids[1] != "tool:"+strings.TrimPrefix(ids[0], "call:") ||
strings.Join(ids[2:], " ") != "call:call_00_2omk8cv76gjjovgj3caocaif call:call_01_h9qf0fe96gtektv6efu80mjt tool:call_00_2omk8cv76gjjovgj3caocaif tool:call_01_h9qf0fe96gtektv6efu80mjt" {
t.Fatalf("sent ids %v", ids)
}
return ids[0]
}
// A Chat request relayed to a Chat upstream carries a call kept with an
// empty id with one made from its place, and its result with the same
// (#2611): WorkBuddy AI turned every later request of the session away.
// The made id is the same on the next request, so the history's prefix,
// and the upstream's cache of it, stays as it was.
func TestEmptyCallIDRelayedWithOne(t *testing.T) {
f := &fake{t: t, reply: chatStreamHello, refuse: workBuddyPairing}
up := setup(t, provider.Chat, f)
chatProvider(t, up.URL, provider.Provider{ID: "wb", Models: []string{"deepseek-v4.1-flash"}})
srv := New()
var first string
for i := range 2 {
code, body := postTo(t, srv, "/v1/chat/completions", fmt.Sprintf(emptyCallIDTurns, "wb/deepseek-v4.1-flash"))
if code != 200 {
t.Fatalf("request %d: %d %s", i, code, body)
}
id := checkMadeIDs(t, sentCallIDs(t, f.got))
if i == 0 {
first = id
} else if id != first {
t.Fatalf("the made id changed between requests: %s, then %s", first, id)
}
}
}
// The same request reaches WorkBuddy AI moved onto its plugin with the
// made id too: the edit runs before the plugin's fetch.
func TestEmptyCallIDReachesPluginWithOne(t *testing.T) {
f := &fake{t: t, reply: chatStreamHello, refuse: workBuddyPairing}
movedFake(t, "workbuddy-ai", f)
code, body := postTo(t, New(), "/v1/chat/completions", fmt.Sprintf(emptyCallIDTurns, "workbuddy-ai/fake-1"))
if code != 200 {
t.Fatalf("%d %s", code, body)
}
checkMadeIDs(t, sentCallIDs(t, f.got))
}
// Translated, a Chat request's empty call id goes to a Messages upstream
// as a tool_use id its result names, and to a Responses upstream as a
// call_id its output names: neither takes an empty one.
func TestEmptyCallIDTranslatedWithOne(t *testing.T) {
t.Run("messages", func(t *testing.T) {
f := &fake{t: t, reply: sse("event: message_start\n"+`data: {"type":"message_start","message":{"id":"msg","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`,
"event: message_delta\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`,
"event: message_stop\n"+`data: {"type":"message_stop"}`)}
setup(t, provider.Anthropic, f)
code, body := postTo(t, New(), "/v1/chat/completions", fmt.Sprintf(emptyCallIDTurns, "fake/m1"))
if code != 200 {
t.Fatalf("%d %s", code, body)
}
var q struct {
Messages []struct {
Content json.RawMessage `json:"content"`
} `json:"messages"`
}
json.Unmarshal(f.got, &q)
var ids []string
for _, m := range q.Messages {
var blocks []struct {
Type string `json:"type"`
ID string `json:"id"`
ToolUseID string `json:"tool_use_id"`
}
json.Unmarshal(m.Content, &blocks)
for _, b := range blocks {
switch b.Type {
case "tool_use":
ids = append(ids, "call:"+b.ID)
case "tool_result":
ids = append(ids, "tool:"+b.ToolUseID)
}
}
}
checkMadeIDs(t, ids)
})
t.Run("responses", func(t *testing.T) {
f := &fake{t: t, reply: sse(
`data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`,
`data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)}
setup(t, provider.Responses, f)
code, body := postTo(t, New(), "/v1/chat/completions", fmt.Sprintf(emptyCallIDTurns, "fake/m1"))
if code != 200 {
t.Fatalf("%d %s", code, body)
}
var q struct {
Input []struct {
Type string `json:"type"`
CallID string `json:"call_id"`
} `json:"input"`
}
json.Unmarshal(f.got, &q)
var ids []string
for _, it := range q.Input {
switch it.Type {
case "function_call":
ids = append(ids, "call:"+it.CallID)
case "function_call_output":
ids = append(ids, "tool:"+it.CallID)
}
}
checkMadeIDs(t, ids)
})
}
// A body whose calls all have ids goes byte for byte, and results with
// no id beyond the calls left without one are left as they came.
func TestChatCallIDsLeavesWhatHasIDs(t *testing.T) {
body := []byte(strings.ReplaceAll(fmt.Sprintf(emptyCallIDTurns, "m"), `"id":""`, `"id":"call_x"`))
body = []byte(strings.Replace(string(body), `"tool_call_id":""`, `"tool_call_id":"call_x"`, 1))
if got := chatCallIDs(body); string(got) != string(body) {
t.Fatalf("changed:\n%s", got)
}
// two calls with none, answered without ids in their order; a third
// result with none has no call left to take
two := []byte(`{"messages":[{"role":"assistant","tool_calls":[{"type":"function","function":{"name":"a","arguments":"{}"}},{"id":null,"type":"function","function":{"name":"b","arguments":"{}"}}]},{"role":"tool","content":"1"},{"role":"tool","tool_call_id":"","content":"2"},{"role":"tool","tool_call_id":"","content":"3"}]}`)
ids := sentCallIDs(t, chatCallIDs(two))
if len(ids) != 5 || ids[0] == ids[1] || ids[2] != "tool:"+strings.TrimPrefix(ids[0], "call:") || ids[3] != "tool:"+strings.TrimPrefix(ids[1], "call:") || ids[4] != "tool:" {
t.Fatalf("ids %v", ids)
}
}
// A relayed Chat stream whose upstream left a tool call's id out (as
// OpenCode Zen's free DeepSeek sometimes does, #2611) reaches the agent
// with one on the call's first fragment, so the agent never keeps "";
// a later fragment's empty id is left out, and a call with its own id
// keeps it.
func TestStreamedCallGivenAnID(t *testing.T) {
reply := sse(
`data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"type":"function","function":{"name":"bash","arguments":""}}]},"finish_reason":null}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","function":{"arguments":"{\"command\":\"ls\"}"}}]},"finish_reason":null}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"","type":"function","function":{"name":"bash","arguments":"{}"}}]},"finish_reason":null}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"tool_calls":[{"index":2,"id":"call_02_own","type":"function","function":{"name":"bash","arguments":"{}"}}]},"finish_reason":null}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
`data: [DONE]`)
f := &fake{t: t, reply: reply}
up := setup(t, provider.Chat, f)
chatProvider(t, up.URL, provider.Provider{ID: "zen", Models: []string{"deepseek-v4.1-flash-free"}})
code, body := postTo(t, New(), "/v1/chat/completions", `{"model":"zen/deepseek-v4.1-flash-free","stream":true,"messages":[{"role":"user","content":"ls"}]}`)
if code != 200 {
t.Fatalf("%d %s", code, body)
}
var frags []map[string]any
for _, ev := range events(body) {
for _, c := range ev["choices"].([]any) {
d, _ := c.(map[string]any)["delta"].(map[string]any)
calls, _ := d["tool_calls"].([]any)
for _, tc := range calls {
frags = append(frags, tc.(map[string]any))
}
}
}
if len(frags) != 4 {
t.Fatalf("fragments %v\n%s", frags, body)
}
id0, _ := frags[0]["id"].(string)
id1, _ := frags[2]["id"].(string)
if !strings.HasPrefix(id0, "call_") || !strings.HasPrefix(id1, "call_") || id0 == id1 {
t.Fatalf("first fragments' ids %q, %q\n%s", id0, id1, body)
}
if _, has := frags[1]["id"]; has {
t.Fatalf("a later fragment kept its empty id\n%s", body)
}
if frags[3]["id"] != "call_02_own" {
t.Fatalf("a call's own id went as %v", frags[3]["id"])
}
}
// A whole reply's call with no id is given one too.
func TestWholeReplyCallGivenAnID(t *testing.T) {
f := &fake{t: t, ctype: "application/json", reply: `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":null,"tool_calls":[{"id":"","type":"function","function":{"name":"bash","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}`}
up := setup(t, provider.Chat, f)
chatProvider(t, up.URL, provider.Provider{ID: "zen", Models: []string{"deepseek-v4.1-flash-free"}})
code, body := postTo(t, New(), "/v1/chat/completions", `{"model":"zen/deepseek-v4.1-flash-free","stream":false,"messages":[{"role":"user","content":"ls"}]}`)
var got struct {
Choices []struct {
Message struct {
ToolCalls []struct{ ID string } `json:"tool_calls"`
}
}
}
if code != http.StatusOK || json.Unmarshal([]byte(body), &got) != nil || len(got.Choices) != 1 || len(got.Choices[0].Message.ToolCalls) != 1 ||
!strings.HasPrefix(got.Choices[0].Message.ToolCalls[0].ID, "call_") {
t.Fatalf("%d %s", code, body)
}
}
+33 -10
View File
@@ -42,9 +42,15 @@ import (
// reasoning_content, as other upstreams send it, and the text to a string
// content.
//
// And an upstream that sometimes sends a tool call's first fragment with
// no id (OpenCode Zen's free DeepSeek) has the agent keep the call as "",
// which a strict upstream it is sent to later turns away (#2611): such a
// fragment is given an id, and a later fragment's empty one is left out.
//
// Lines pass whole, as they came, unless one has any of them.
type chatTidy struct {
buf []byte
ids streamCallIDs
}
var (
@@ -54,6 +60,7 @@ var (
emptyToolCalls = []byte(`"tool_calls":[]`)
contentParts = []byte(`"content":[`)
contentPartsSpace = []byte(`"content": [`)
toolCallsField = []byte(`"tool_calls"`)
)
// write takes what was read and gives back what to send on: every line
@@ -64,19 +71,19 @@ func (t *chatTidy) write(b []byte) []byte {
if i < 0 {
return nil
}
out := tidyLines(t.buf[:i+1])
out := t.lines(t.buf[:i+1])
t.buf = append(t.buf[:0], t.buf[i+1:]...)
return out
}
// flush is what's left once the stream ends.
func (t *chatTidy) flush() []byte {
out := tidyLines(t.buf)
out := t.lines(t.buf)
t.buf = nil
return out
}
func tidyLines(b []byte) []byte {
func (t *chatTidy) lines(b []byte) []byte {
if !needsTidy(b) {
return append([]byte(nil), b...)
}
@@ -88,7 +95,7 @@ func tidyLines(b []byte) []byte {
} else {
b = nil
}
out = append(out, tidyLine(line)...)
out = append(out, t.line(line)...)
}
return out
}
@@ -101,10 +108,14 @@ func needsTidy(line []byte) bool {
bytes.Contains(line, emptyToolName) ||
bytes.Contains(line, emptyToolCalls) ||
bytes.Contains(line, contentParts) ||
bytes.Contains(line, contentPartsSpace)
bytes.Contains(line, contentPartsSpace) ||
bytes.Contains(line, toolCallsField)
}
func tidyLine(line []byte) []byte {
// tidyLine mends one line as the first of a stream.
func tidyLine(line []byte) []byte { return (&chatTidy{}).line(line) }
func (t *chatTidy) line(line []byte) []byte {
if !needsTidy(line) {
return line
}
@@ -123,7 +134,7 @@ func tidyLine(line []byte) []byte {
return line
}
changed := false
for _, c := range choices {
for k, c := range choices {
if string(c["finish_reason"]) == `""` {
c["finish_reason"] = json.RawMessage("null")
changed = true
@@ -141,6 +152,15 @@ func tidyLine(line []byte) []byte {
delete(delta, "tool_calls")
inDelta = true
} else if ok {
if t.ids == nil {
t.ids = streamCallIDs{}
}
choice := k
decodeJSON(c["index"], &choice)
if mended, chg := t.ids.mend(choice, calls); chg {
calls, delta["tool_calls"] = mended, mended
inDelta = true
}
if mended, chg := withoutEmptyNames(calls); chg {
delta["tool_calls"] = mended
inDelta = true
@@ -261,8 +281,9 @@ func flattenContent(m map[string]json.RawMessage, whole bool) bool {
// on with a string content and its thinking in reasoning_content, and,
// when the request offered tools (names), calls the model wrote into its
// text are made the calls they are, as textCallTidy makes them in a
// stream (#1845). It is held until it ends; any other reply passes byte
// for byte.
// stream (#1845), and a call the upstream gave no id is given one, as
// chatTidy gives it in a stream (#2611). It is held until it ends; any
// other reply passes byte for byte.
type chatWhole struct {
names map[string]bool
buf []byte
@@ -277,7 +298,7 @@ func (t *chatWhole) flush() []byte {
b := t.buf
t.buf = nil
parts := bytes.Contains(b, contentParts) || bytes.Contains(b, contentPartsSpace)
if !parts && !mayWriteCalls(b, t.names) {
if !parts && !mayWriteCalls(b, t.names) && !bytes.Contains(b, toolCallsField) {
return b
}
var reply map[string]json.RawMessage
@@ -295,6 +316,8 @@ func (t *chatWhole) flush() []byte {
continue
}
mended := parts && flattenContent(msg, true)
// a call the upstream gave no id (#2611)
mended = wholeCallIDs(msg) || mended
if wrote, called := wholeTextCalls(msg, t.names); wrote {
if called {
c["finish_reason"] = json.RawMessage(`"tool_calls"`)
+6
View File
@@ -3407,6 +3407,12 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
body = orphanedToolOutputs(body)
body = pairToolItems(body)
}
if from == provider.Chat {
// a call kept with an empty id, which a strict upstream turns
// the whole request away for (#2611); before the relay, the
// translation and a plugin's fetch alike
body = chatCallIDs(body)
}
// every request to the provider goes through its own proxy, if it has
// one (#237)
r = r.WithContext(p.Via(r.Context()))