gateway: a DeepSeek channel that refuses reasoning without an id is asked again without it, and its 422 moves a group on (yyhhyyyyyy on X)
Codex continuing on a DeepSeek channel's Responses API, after a reply that had no reasoning, sent a step with nothing to replay. magpie leads such a step with a reasoning item holding " " and no id (noReasoningItem, reasonFirst), which DeepSeek's own /v1/responses wants: without it it refuses the request with "The `reasoning_text` in the thinking mode must be passed back to the API" (#1822, #1592, #1687, checked on api.deepseek.com 2026-10-12). The reporter's channel turns that item away with 422 "Input tag 'reasoning' found using 'type' does not match any of the expected tags: 'message', 'tool_result'", pydantic's words for a tagged-union member it has no type for. It takes a reasoning item with an id (its own, which Codex sends back), so only the id-less ones, the " " and a translated turn's reasoning text, are refused. The 422 wasn't retryable, so a group stopped at that member. What changed: - idless_reasoning.go: idlessReasoningRefusal matches that message; withoutIDlessReasoning drops reasoning input items without an id. - gateway.go, relayed Responses: on that refusal the request is asked once more without them, and once taken the provider/model is marked (idlessReasoningRefused) and not sent one again. Items with an id go. - gateway.go, translated to Responses: the same, through the build loop (mark, rebuild, drop). - fallback.go: "does not match any of the expected tags" is a shape refusal (shapeWords), the same kind as xAI's "unknown item type": a group's next member (DeepSeek's own API takes the item) is asked, and the member doesn't rest. This only matters when the retry without the items is refused too, or the member can't drop any. - The placeholder itself is unchanged: an upstream that never refused it (DeepSeek's own API) still gets it, so #1822 stays fixed. - docs/subsystems/gateway-routing.md: the Responses replay paragraph. Fixtures are the reporter's message, word for word, in FastAPI's detail envelope and in OpenAI's error object (the reporter gave the message, not the envelope). Run: - New tests: TestIdlessReasoningRefusedByChannel (relayed, both envelopes, second request taken at once), TestTranslatedIdlessReasoningRefusedByChannel (a Chat client translated), TestGroupFailsOverIdlessReasoningRefusal, TestIdlessReasoningKeptForDeepSeek, TestWithoutIDlessReasoning. - Broken by hand: with gateway.go and fallback.go at origin/main (idless_reasoning.go kept so the tests compile), the three refusal tests fail with the reporter's 422 reaching the client; TestIdlessReasoningKeptForDeepSeek passes, as it guards #1822. - mote: go test ./internal/gateway -run with the tests above plus TestDeepSeekStepSaysBeforeItsCall, TestGroupFailsOverARequestShape, TestTranslatedDeepSeek*, TestWithReasoningText*: ok. - mica (mote had a full suite running, load 24): go test -count=1 -timeout 45m ./... at 29cb2262a (this change on origin/main31dcfcc33): 103 packages ok, exit 0. GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. gofmt -l: clean. - Rebased ontoa5b797d8d(main gained image caps in internal/gateway and provider, and sessions timings): mica, go test -count=1 -timeout 45m ./internal/gateway ./internal/provider ./internal/sessions at the pushed tree: ok, ok, ok. gofmt -l: clean. The full suite above ran at the earlier base.be6f8b730(Zen through Bun: internal/provider zen_bun.go, internal/netproxy) landed after that run and touches no file here; it was not run again with this change. Not tried: the reporter's channel itself (its URL isn't known), so the id rule rests on the reporter's reading and their error text. A built magpie end to end.
This commit is contained in:
@@ -391,7 +391,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`).
|
||||
- ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool <name> is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`).
|
||||
- An endpoint that reads only text and images in a `tool_result` refuses the references themselves: "DeepSeek V4.1 supports text and image content only; got 'tool_reference'" (emilochen on X, an Anthropic-compatible URL). A 400 or 422 that refuses `tool_reference` in words (`refsRefused`: a refusal word within the same clause, no brace between, so a request echoed back doesn't count, and "expected `tool_reference`" doesn't either) while the request as sent holds one in a `tool_result` is asked again at once with each reference as the text `toolLoadedText` gives, the tools they name sent without `defer_loading` (the rest stay deferred), and is sent it that way while magpie runs (`shapeRefs`, `withRefsAsText`; `deferredOutUpFront` is the same up-front strip `forwardOnce` makes for Kimi, DeepSeek's own API and OpenCode's DeepSeek). A refusal a deferred block's refusal explains, while such blocks are still sent, is that one's. Chat, Responses and Gemini upstreams already get the references as that text (`stringOrText`). (`TestToolReferenceRefusedGoesAsText`, `TestToolReferenceNamedOtherwiseLearnsNothing`, `TestRefsAsTextLeavesOthers`)
|
||||
- A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level `tools` on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (`defer_loading`, `Tool.Deferred`) that a `tool_result`'s `tool_reference` names (`toolRefs`, `Part.Loads`) now goes, where `Request.LoadedInPlace` is set, in an `{"type":"additional_tools","role":"developer","tools":[…]}` item right after the run of tool outputs that loaded it, once, and not in `tools` (`buildResponses`): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in `tools`, a new prefix, as is expected. `LoadedInPlace` is set (`loadsInPlace`, in `forwardTranslated`) for OpenAI's own API with a key (`api.openai.com`, `*.api.openai.com`), for a ChatGPT (Codex) account, and for a provider set `additionalTools` (`magpie provider set <id> additional-tools=on`); `additional-tools=off` (`additionalToolsOff`) turns it off even where it is the default, and `default` goes back to magpie's. The ChatGPT backend was tried with a real account (#4738, gpt-5.6-terra, gpt-6-luna, gpt-6-sol): it takes the item where it was loaded, the model calls the tool in it, and the next request read 7680–7936 tokens from cache where, with the tool moved into `tools`, it read none. Nothing else is sent it by default, since xAI answers the item 422 (#350), and no relay, other vendor's sign-in (Copilot) or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming `additional_tools` is asked again with every tool in `tools`, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a `tool_addition` block loads (an MCP server's late tool, the advisor) stays in `tools`. `TestLoadedToolsKeepThePrefix`, `TestLoadedToolsInOneItem`, `TestLoadedToolsWhereNotTaken`, `TestLoadsInPlaceScope`, `TestLoadedToolsThroughTheGateway`, `TestCodexAccountLoadsInPlace`.
|
||||
- A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte.
|
||||
- A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte. A channel that turns a reasoning item without an id away (a DeepSeek channel's 422 "Input tag 'reasoning' found using 'type' does not match any of the expected tags: 'message', 'tool_result'", `idlessReasoningRefusal`) is asked once more without such items, relayed or translated, and not sent one again (`idlessReasoningRefused`, `withoutIDlessReasoning`); items with an id still go. The refusal is a shape (`shapeWords`), so a group's next member, DeepSeek's own API among them, is asked and the member doesn't rest (`TestIdlessReasoningRefusedByChannel`, `TestGroupFailsOverIdlessReasoningRefusal`).
|
||||
- A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says `"signature": ""`, as `aBlock` writes `thinking` even when empty: OpenRouter's `/api/v1/messages` holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). `TestOpenRouterDeepSeekThinkingHasASignature`.
|
||||
- A Messages or Chat upstream whose host and model don't say DeepSeek but whose model answers 400 "The `content[].thinking` (or `reasoning_content`) in the thinking mode must be passed back to the API" (`thinkingBackRefusal` in [`thinking_back.go`](../../internal/gateway/thinking_back.go)) is asked once more with its tool turns filled as above (`withThinkingOnToolTurns`, `withReasoningOnToolTurns`), and that provider's model is sent them at once from then on (`thinkingBackNeeded` in `unfit`, filled in `forwardOnce`), on every route to it. A relay serving DeepSeek under another name, or a provider the user named "My Claude", got a routing group's fall from a rate-limited Codex subscription mid tool loop refused, Codex's sealed reasoning having no text to give (qisishiqi on Discord, 2026-11-02). Checked against api.deepseek.com on 2026-11-02: only the tool loop being continued needs it; finished turns and plain replies are taken without. A provider that never asked is sent the turns as before. `TestThinkingBackLearnedBehindAnotherName`, `TestReasoningBackLearnedBehindAnotherName`.
|
||||
- Every thinking block a Messages client gets says a `signature`, a string, as Anthropic's own do (its stream starts each block with `"signature": ""`): Grok Build reads `ContentBlock::Thinking` as `{thinking, signature}`, both required, and turned a whole reply away, "missing field `signature`" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (`anthropicEncoder.thinking`), `renderAnthropic` and `whole_stream.go` write the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (`sigFieldTidy` in [`thinking_signature.go`](../../internal/gateway/thinking_signature.go), in `passthrough`); a block already signed goes byte for byte, and `redacted_thinking` is untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (`anthropicBody` leaves it out for Anthropic, keeps its text where reasoning is replayed), and a relay sends it back to the vendor that wrote the block, but never to an upstream serving Claude (`withoutForeignThinking`, above). `TestMessagesThinkingIsSigned`, `TestSignedThinkingRelayedAsItCame`.
|
||||
|
||||
@@ -1821,8 +1821,12 @@ func promptRefused(status int, body []byte) bool {
|
||||
// specified other fields alongside any_of. When using any_of, it must be
|
||||
// the only field set." (#5374, worksyang) — a description beside an
|
||||
// anyOf, which Google's Schema takes alone, the reporter's same tools
|
||||
// another member took.
|
||||
var shapeWords = lazyre.New(`(?i)failed to deserialize|unknown (item |content |input )?(type|variant|field|parameter)|unknown_parameter|unrecognized (request argument|field|parameter)|extra (inputs|fields) are not permitted|additional properties are not allowed|schema exceeds the maximum (nesting )?depth|schema[^"]{0,60}\bnesting depth\b|function_declarations\[\d+\]\.parameters\b|schema specified other fields alongside any_?of|InferHub\.001001005\.400`)
|
||||
// another member took. And pydantic's word for an item whose type its
|
||||
// tagged union has no member for, a DeepSeek channel's 422 "Input tag
|
||||
// 'reasoning' found using 'type' does not match any of the expected tags:
|
||||
// 'message', 'tool_result'" (yyhhyyyyyy on X): the same kind as xAI's
|
||||
// unknown item type, which DeepSeek's own API, another member, takes.
|
||||
var shapeWords = lazyre.New(`(?i)failed to deserialize|unknown (item |content |input )?(type|variant|field|parameter)|does not match any of the expected tags|unknown_parameter|unrecognized (request argument|field|parameter)|extra (inputs|fields) are not permitted|additional properties are not allowed|schema exceeds the maximum (nesting )?depth|schema[^"]{0,60}\bnesting depth\b|function_declarations\[\d+\]\.parameters\b|schema specified other fields alongside any_?of|InferHub\.001001005\.400`)
|
||||
|
||||
// unsaidWords are Command Code's Provider API turning a request away with
|
||||
// nothing but a trace id: {"message":"invalid request error trace_id:
|
||||
|
||||
@@ -6843,6 +6843,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
body = withoutOffsetlessCitations(body)
|
||||
}
|
||||
}
|
||||
if !s.fits(p.ID, idlessReasoningRefused(model), proto) {
|
||||
// a reasoning item without an id, the " " a step leads with
|
||||
// for DeepSeek, to a channel that turned one away before
|
||||
// (idless_reasoning.go)
|
||||
body = withoutIDlessReasoning(body)
|
||||
}
|
||||
// Relays enforce OpenAI's item ID prefixes too, including during
|
||||
// compaction. call_id stays unchanged so tool outputs remain paired.
|
||||
body = callItemIDs(body)
|
||||
@@ -7334,6 +7340,21 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && idlessReasoningRefusal.Match(wordsOf(b)) {
|
||||
// and a reasoning item without an id, which a DeepSeek
|
||||
// channel reads as neither a message nor a tool's result
|
||||
// (422 "Input tag 'reasoning' found using 'type' does not
|
||||
// match any of the expected tags", yyhhyyyyyy on X): asked
|
||||
// once more without it, and not sent one again
|
||||
if nb := withoutIDlessReasoning(body); !bytes.Equal(nb, body) {
|
||||
refused = append(refused, idlessReasoningRefused(model))
|
||||
body = nb
|
||||
if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil {
|
||||
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && refusesCitationOffsets(res.StatusCode, b) {
|
||||
// and a citation without the offsets OpenAI's schema wants,
|
||||
// which the ChatGPT backend and the relays in front of it
|
||||
@@ -8510,6 +8531,12 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
|
||||
// the other magpie searches for it (search_remote.go)
|
||||
body = withFields(body, map[string]any{"web_search_options": map[string]any{}})
|
||||
}
|
||||
if to == provider.Responses && !s.fits(p.ID, idlessReasoningRefused(model), to) {
|
||||
// a reasoning item without an id (a turn's text, or the " "
|
||||
// a step leads with for DeepSeek), to a channel that turned
|
||||
// one away before (idless_reasoning.go)
|
||||
body = withoutIDlessReasoning(body)
|
||||
}
|
||||
if !s.fits(p.ID, historyToolsRefused, to) {
|
||||
// a stub for each tool the history called and tools lacks,
|
||||
// to an upstream that turned such a call away before
|
||||
@@ -8578,6 +8605,15 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
|
||||
r.MaxTokens, req, filledOutput = 0, &r, false
|
||||
continue
|
||||
}
|
||||
if to == provider.Responses && badRequest(res.StatusCode) && idlessReasoningRefusal.Match(wordsOf(b)) &&
|
||||
s.fits(p.ID, idlessReasoningRefused(model), to) && !bytes.Equal(withoutIDlessReasoning(body), body) {
|
||||
// a reasoning item without an id turned away (a DeepSeek
|
||||
// channel's 422, idless_reasoning.go): asked again without
|
||||
// one, and so from then on
|
||||
log.Printf("gateway: %s turned away reasoning without an id for %s (%d); sent none from now on", p.ID, model, res.StatusCode)
|
||||
s.markUnfit(p.ID, idlessReasoningRefused(model), to)
|
||||
continue
|
||||
}
|
||||
if req.LoadedInPlace && refusesField(res.StatusCode, b, additionalToolsItem) && bodyHas(body, `"`+additionalToolsItem+`"`) {
|
||||
// an upstream that turns the item away is asked again with the
|
||||
// loaded tools among the others, and not sent it again: the
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
)
|
||||
|
||||
// idlessReasoningRefusal is an upstream's Responses API turning a request
|
||||
// away over a reasoning input item it reads as neither a message nor a
|
||||
// tool's result: a DeepSeek channel's 422 "Input tag 'reasoning' found
|
||||
// using 'type' does not match any of the expected tags: 'message',
|
||||
// 'tool_result'" (yyhhyyyyyy on X), pydantic's words for a tagged union
|
||||
// whose tag it has no member for. It takes a reasoning item with an id
|
||||
// (one it gave, which Codex sends back), and refuses one without: the
|
||||
// " " a step leads with when it has none (noReasoningItem, reasonFirst),
|
||||
// or a translated turn's reasoning text (buildResponses), neither of which
|
||||
// has an id.
|
||||
var idlessReasoningRefusal = lazyre.New(`(?i)input tag \\?['"]?reasoning\\?['"]? found using \\?['"]?type\\?['"]? does not match any of the expected tags`)
|
||||
|
||||
// idlessReasoningRefused is how unfit remembers a provider turning away,
|
||||
// for model, a reasoning item without an id (withoutIDlessReasoning).
|
||||
func idlessReasoningRefused(model string) string { return "idless reasoning\x00" + model }
|
||||
|
||||
// withoutIDlessReasoning is a Responses body without its reasoning input
|
||||
// items that carry no id, for an upstream that refused one
|
||||
// (idlessReasoningRefusal). A body with none comes back as it is.
|
||||
func withoutIDlessReasoning(body []byte) []byte {
|
||||
if !bodyHas(body, `"reasoning"`) {
|
||||
return body
|
||||
}
|
||||
var q map[string]json.RawMessage
|
||||
if decodeJSONView(body, &q) != nil {
|
||||
return body
|
||||
}
|
||||
items, isList := inputList(q["input"])
|
||||
if !isList {
|
||||
return body
|
||||
}
|
||||
kept := make([]json.RawMessage, 0, len(items))
|
||||
for _, raw := range items {
|
||||
var it struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if decodeJSONView(raw, &it) == nil && it.Type == "reasoning" && it.ID == "" {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, raw)
|
||||
}
|
||||
if len(kept) == len(items) {
|
||||
return body
|
||||
}
|
||||
q["input"], _ = marshalJSON(kept)
|
||||
nb, err := marshalJSON(q)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
return nb
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// idlessReasoningMsg is the reporter's error, word for word (yyhhyyyyyy on
|
||||
// X): a DeepSeek channel's Responses API refusing the " " reasoning item
|
||||
// magpie put first in a step that had none.
|
||||
const idlessReasoningMsg = `Input tag 'reasoning' found using 'type' does not match any of the expected tags: 'message', 'tool_result'`
|
||||
|
||||
// idlessReasoning422s are that message in the envelopes a channel answers
|
||||
// in: pydantic's own (FastAPI's detail list) and OpenAI's error object.
|
||||
var idlessReasoning422s = []string{
|
||||
`{"detail":[{"type":"union_tag_invalid","loc":["body","input",3],"msg":"` + idlessReasoningMsg + `","input":{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":" "}]},"ctx":{"discriminator":"'type'","tag":"reasoning","expected_tags":"'message', 'tool_result'"}}]}`,
|
||||
`{"error":{"message":"` + idlessReasoningMsg + `","type":"invalid_request_error"}}`,
|
||||
}
|
||||
|
||||
// idlessChannel is that channel: a reasoning item with an id (one it gave)
|
||||
// is taken, one without is turned away with 422.
|
||||
type idlessChannel struct {
|
||||
mu sync.Mutex
|
||||
refuse string
|
||||
inputs [][]map[string]any
|
||||
}
|
||||
|
||||
func (u *idlessChannel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var q struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
json.Unmarshal(body, &q)
|
||||
u.mu.Lock()
|
||||
u.inputs = append(u.inputs, q.Input)
|
||||
u.mu.Unlock()
|
||||
for _, it := range q.Input {
|
||||
if it["type"] == "reasoning" && it["id"] == nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
io.WriteString(w, u.refuse)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_ch","status":"in_progress"}}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"done"}]}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_ch","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`))
|
||||
}
|
||||
|
||||
func (u *idlessChannel) sent() (n int, last []map[string]any) {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
if len(u.inputs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return len(u.inputs), u.inputs[len(u.inputs)-1]
|
||||
}
|
||||
|
||||
// TestIdlessReasoningRefusedByChannel (yyhhyyyyyy on X): Codex continuing
|
||||
// on a DeepSeek channel whose reply had no reasoning sends a step with
|
||||
// nothing to replay, and magpie leads it with a " " reasoning item without
|
||||
// an id (reasonFirst), which DeepSeek's own API wants (#1822). The channel
|
||||
// turned the whole request away with 422 and the agent got it. It is asked
|
||||
// once more without the item, and not sent one again; its own reasoning,
|
||||
// with an id, still goes.
|
||||
func TestIdlessReasoningRefusedByChannel(t *testing.T) {
|
||||
for _, refuse := range idlessReasoning422s {
|
||||
fresh(t)
|
||||
up := &idlessChannel{refuse: refuse}
|
||||
srv := httptest.NewServer(up)
|
||||
defer srv.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "ch", Name: "Channel", Key: "k", Models: []string{"deepseek-v4-pro"}, Responses: srv.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
input := `{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the login bug"}]},
|
||||
{"type":"reasoning","id":"rs_ch1","summary":[],"content":[{"type":"reasoning_text","text":"Look first."}]},
|
||||
{"type":"function_call","call_id":"c1","name":"shell","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c1","output":"main.go"},
|
||||
{"type":"function_call","call_id":"c2","name":"shell","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c2","output":"ok"}`
|
||||
req := `{"model":"ch/deepseek-v4-pro","stream":true,"store":false,"tools":[{"type":"function","name":"shell","parameters":{"type":"object"}}],"input":[` + input + `]}`
|
||||
code, b := postTo(t, s, "/v1/responses", req)
|
||||
if code != 200 || strings.Contains(b, "expected tags") {
|
||||
t.Fatalf("%.40s: %d %s", refuse, code, b)
|
||||
}
|
||||
n, last := up.sent()
|
||||
if n != 2 {
|
||||
t.Fatalf("asked %d times, want the refusal and once more", n)
|
||||
}
|
||||
if got := stepShape(last); got != `message:user,reasoning="Look first.",function_call,function_call_output,function_call,function_call_output` {
|
||||
t.Fatalf("sent %s", got)
|
||||
}
|
||||
if code, b := postTo(t, s, "/v1/responses", req); code != 200 {
|
||||
t.Fatalf("again: %d %s", code, b)
|
||||
}
|
||||
if n, _ := up.sent(); n != 3 {
|
||||
t.Fatalf("asked %d times in all, want the second request taken at once", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Translated to the channel (an agent on Chat), a turn's reasoning goes
|
||||
// as an item without an id, and the " " before a step without one too:
|
||||
// the channel's 422 has them left out, and the member asked again.
|
||||
func TestTranslatedIdlessReasoningRefusedByChannel(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &idlessChannel{refuse: idlessReasoning422s[0]}
|
||||
srv := httptest.NewServer(up)
|
||||
defer srv.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "ch", Name: "Channel", Key: "k", Models: []string{"deepseek-v4-pro"}, Responses: srv.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
req := `{"model":"ch/deepseek-v4-pro","stream":false,"tools":[{"type":"function","function":{"name":"shell","parameters":{"type":"object"}}}],"messages":[
|
||||
{"role":"user","content":"fix the login bug"},
|
||||
{"role":"assistant","content":"","reasoning_content":"Look first.","tool_calls":[{"id":"c1","type":"function","function":{"name":"shell","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c1","content":"main.go"},
|
||||
{"role":"assistant","content":"","tool_calls":[{"id":"c2","type":"function","function":{"name":"shell","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c2","content":"ok"}]}`
|
||||
code, b := postTo(t, s, "/v1/chat/completions", req)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, b)
|
||||
}
|
||||
n, last := up.sent()
|
||||
if n != 2 {
|
||||
t.Fatalf("asked %d times, want the refusal and once more", n)
|
||||
}
|
||||
for _, it := range last {
|
||||
if it["type"] == "reasoning" {
|
||||
t.Fatalf("sent %s", stepShape(last))
|
||||
}
|
||||
}
|
||||
if code, b := postTo(t, s, "/v1/chat/completions", req); code != 200 {
|
||||
t.Fatalf("again: %d %s", code, b)
|
||||
}
|
||||
if n, _ := up.sent(); n != 3 {
|
||||
t.Fatalf("asked %d times in all, want the second request taken at once", n)
|
||||
}
|
||||
}
|
||||
|
||||
// What DeepSeek's own API wants is unchanged: an upstream that never
|
||||
// refused it still gets the " " a step leads with (#1822).
|
||||
func TestIdlessReasoningKeptForDeepSeek(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &deepseekResponses{}
|
||||
srv := httptest.NewServer(up)
|
||||
defer srv.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Preset: "deepseek", Key: "k", Models: []string{"deepseek-flash"}, Responses: srv.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, b := post(t, "/v1/responses", `{"model":"deepseek/deepseek-flash","stream":true,"store":false,"input":[
|
||||
{"type":"message","role":"user","content":[{"type":"input_text","text":"ls"}]},
|
||||
{"type":"function_call","call_id":"c1","name":"shell","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c1","output":"main.go"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, b)
|
||||
}
|
||||
if got := stepShape(up.last()); got != `message:user,reasoning=" ",function_call,function_call_output` {
|
||||
t.Fatalf("sent %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A channel that turns such an item away is a shape it can't read, not a
|
||||
// fault of the account or of the request: a group's next member, DeepSeek's
|
||||
// own API, may take it as it is, and the member doesn't rest.
|
||||
func TestGroupFailsOverIdlessReasoningRefusal(t *testing.T) {
|
||||
for _, refuse := range idlessReasoning422s {
|
||||
if !retryable(422, []byte(refuse)) || !shapeRefused(422, []byte(refuse)) {
|
||||
t.Errorf("not handed on: %s", refuse)
|
||||
}
|
||||
fresh(t)
|
||||
a := &scripted{replies: []reply{{422, "", refuse}}}
|
||||
b := &scripted{replies: []reply{{200, "", chatOK}}}
|
||||
scriptedOn(t, "a", provider.Chat, a)
|
||||
scriptedOn(t, "b", provider.Chat, b)
|
||||
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || !strings.Contains(body, "hello") || a.n != 1 || b.n != 1 {
|
||||
t.Fatalf("%d %s (a %d, b %d)", code, body, a.n, b.n)
|
||||
}
|
||||
r := s.trace.routes[len(s.trace.routes)-1]
|
||||
if len(r.Tries) != 2 || r.Tries[0].Fail != failShape || r.Tries[0].Rest != nil {
|
||||
t.Fatalf("tries %+v", r.Tries)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithoutIDlessReasoning(t *testing.T) {
|
||||
in := `{"model":"m","input":[{"type":"message","role":"user","content":"hi"},{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":" "}]},{"type":"reasoning","id":"rs_1","summary":[]},{"type":"function_call","call_id":"c","name":"x","arguments":"{}"}]}`
|
||||
var q struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
json.Unmarshal(withoutIDlessReasoning([]byte(in)), &q)
|
||||
if got := stepShape(q.Input); got != "message:user,reasoning,function_call" || q.Input[1]["id"] != "rs_1" {
|
||||
t.Fatalf("%s", got)
|
||||
}
|
||||
for _, b := range []string{`{"model":"m","input":"hi"}`, `{"model":"m","input":[{"type":"reasoning","id":"rs_1"}]}`} {
|
||||
if got := string(withoutIDlessReasoning([]byte(b))); got != b {
|
||||
t.Errorf("%s became %s", b, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user