gateway: a DeepSeek step that said something before its call leads with its reasoning, so DeepSeek no longer refuses it with 400 (#1822, #1592, #1687)
Codex through magpie to OpenCode Go's DeepSeek (#1822), and to DeepSeek's own API (#1592, #1687), was refused now and then with "The `reasoning_text` in the thinking mode must be passed back to the API". The cause, checked against api.deepseek.com/v1/responses on 2026-10-12: DeepSeek reads each step (a run of reasoning, assistant messages and calls after a user message or tool output) as one assistant message whose thinking is the item the step starts with. In the current turn (since the last user message), a step that has a call or follows a tool output must lead with a reasoning item. [message, reasoning, call] and [output, message] are refused; [reasoning, message, call] and [output, reasoning, message] are taken. When a step had no reasoning (another model's turn, a translated one), magpie inserted its " " reasoning right before the call, which gave [message, reasoning " ", call]. A step with only a call worked, and only the current turn is checked, which is why the reporter saw it come and go. What changed: - responses.go: withReasoningText and buildResponses now share reasonFirst. Each such step leads with reasoning: the step's own first reasoning item is moved ahead, otherwise one holding a space is put first. A sealed item keeps its id and encrypted_content. A body already in that shape goes byte for byte. - Sibling, the same API family: an assistant reply right after a tool result, with no reasoning, is refused too (checked on DeepSeek's Chat and Anthropic endpoints). Chat (withReasoningOnToolTurns relayed, buildChat translated) now gives such a reply reasoning_content " ". Anthropic (withThinkingOnToolTurns) gives it a thinking block. Anthropic takes thinking anywhere in the message, so ordering is not an issue there. - The DeepSeek fakes in the tests now model the real rules. The stricter Responses fake also turns TestDeepSeekGroupMemberAfterChatGPT red on the old code: its "an assistant note" case is this bug, which the old lenient fake hid. - docs/subsystems/gateway-routing.md: the Responses, Chat and Messages replay paragraphs. What was run: - New tests: TestDeepSeekStepSaysBeforeItsCall covers the reporter's shape across OpenCode Go, DeepSeek and a group, streamed and not. Also TestWithReasoningTextLedStepsUnchanged, TestTranslatedDeepSeekStepLeadsWithReasoning, TestChatReplyAfterToolGetsReasoning and TestAnthropicReplyAfterToolGetsThinking. All but the unchanged-body test fail on the old code. - gofmt -l; go vet ./... on darwin, and with -tags nogui on linux and windows; go test ./internal/gateway. - Real API: direct requests to api.deepseek.com (Responses, Chat, Anthropic) with the old and new shapes, as listed above. What wasn't: - OpenCode Go's own endpoint: the test account is refused with "This Go model requires Global regions", an account setting, so its fix rests on it relaying DeepSeek's rule unchanged (the reporter's error text is DeepSeek's). - A built magpie end to end against the real API. - Other thinking vendors (Kimi, GLM) were not checked for the same step rule. Their paths are unchanged.
This commit is contained in:
@@ -74,10 +74,10 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- 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 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. 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 Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`.
|
||||
- A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). A reply without tool calls, any other model and Mistral (#494) are sent as before.
|
||||
- A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). An assistant message right after a tool result, a reply with no call of its own, gets one too: DeepSeek refuses it the same way (checked 2026-10-12, #1822). A reply to the user, any other model and Mistral (#494) are sent as before.
|
||||
- Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`).
|
||||
- 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). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); a step without one gets a reasoning item holding a space before its first call. A sealed item keeps its id and `encrypted_content`.
|
||||
- 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`, 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 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 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 Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`grok_integral.go`](../../internal/gateway/grok_integral.go)).
|
||||
- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code, Zed) are always told in the system prompt. A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before.
|
||||
- Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671).
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -254,8 +255,9 @@ func anthropicReplaysThinking(host, model string) bool {
|
||||
}
|
||||
|
||||
// withThinkingOnToolTurns gives each assistant message of a Messages
|
||||
// request that has a tool_use and no thinking block one holding
|
||||
// noReasoning, and turns a redacted_thinking block (Claude's, sealed, which
|
||||
// request that has a tool_use, or that answers tool results alone (DeepSeek
|
||||
// refuses that one too, checked 2026-10-12, #1822), and no thinking block
|
||||
// one holding noReasoning, and turns a redacted_thinking block (Claude's, sealed, which
|
||||
// DeepSeek can't read) into that too, or leaves it out when the message
|
||||
// has thinking already, for anthropicReplaysThinking. A Claude Code routing
|
||||
// group that falls from Claude to DeepSeek sends both (#1611). Every other
|
||||
@@ -271,12 +273,29 @@ func withThinkingOnToolTurns(body []byte) []byte {
|
||||
}
|
||||
space, _ := json.Marshal(aBlock{Type: "thinking", Thinking: noReasoning})
|
||||
changed := false
|
||||
// afterTool: the message before is the user's tool results alone
|
||||
afterTool := false
|
||||
for i, raw := range msgs {
|
||||
var m map[string]json.RawMessage
|
||||
var role string
|
||||
var blocks []json.RawMessage
|
||||
if decodeJSON(raw, &m) != nil || decodeJSON(m["role"], &role) != nil || role != "assistant" ||
|
||||
decodeJSON(m["content"], &blocks) != nil {
|
||||
if decodeJSON(raw, &m) != nil || decodeJSON(m["role"], &role) != nil {
|
||||
afterTool = false
|
||||
continue
|
||||
}
|
||||
if role != "assistant" {
|
||||
afterTool = decodeJSON(m["content"], &blocks) == nil && len(blocks) > 0 &&
|
||||
!slices.ContainsFunc(blocks, func(b json.RawMessage) bool {
|
||||
var t struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
return decodeJSON(b, &t) != nil || t.Type != "tool_result"
|
||||
})
|
||||
continue
|
||||
}
|
||||
after := afterTool
|
||||
afterTool = false
|
||||
if decodeJSON(m["content"], &blocks) != nil {
|
||||
continue
|
||||
}
|
||||
var out []json.RawMessage
|
||||
@@ -300,7 +319,7 @@ func withThinkingOnToolTurns(body []byte) []byte {
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
if called && !thought {
|
||||
if (called || after) && !thought {
|
||||
out = append([]json.RawMessage{space}, out...)
|
||||
edited = true
|
||||
}
|
||||
|
||||
@@ -279,6 +279,9 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
}
|
||||
}
|
||||
turns := joinSplitCalls(r.Messages)
|
||||
// afterTool: the last message sent is a tool result, with no message
|
||||
// of the user's after it
|
||||
afterTool := false
|
||||
for i, m := range turns {
|
||||
if m.Role == "assistant" {
|
||||
showSeen()
|
||||
@@ -344,11 +347,13 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
}
|
||||
} else if think != "" && replay {
|
||||
am["reasoning_content"] = think
|
||||
} else if replay && len(calls) > 0 {
|
||||
// a tool call with no thinking (another model's turn), which
|
||||
// DeepSeek turns the whole request away for (#1462)
|
||||
} else if replay && (len(calls) > 0 || afterTool) {
|
||||
// a tool call with no thinking (another model's turn), or a
|
||||
// reply to a tool result with none, which DeepSeek turns the
|
||||
// whole request away for (#1462, #1822)
|
||||
am["reasoning_content"] = noReasoning
|
||||
}
|
||||
afterTool = false
|
||||
msgs = append(msgs, am)
|
||||
continue
|
||||
}
|
||||
@@ -404,6 +409,7 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
}
|
||||
}
|
||||
msgs = append(msgs, tools...)
|
||||
afterTool = len(tools) > 0 && len(content) == 0 && len(seen) == 0
|
||||
flush()
|
||||
}
|
||||
showSeen()
|
||||
|
||||
@@ -11,7 +11,8 @@ import (
|
||||
// deepseekRefuseToolTurns answers as DeepSeek's Chat API does in thinking
|
||||
// mode (checked against api.deepseek.com, October 2026): a tool call made
|
||||
// since the user's last message that comes back without reasoning_content
|
||||
// turns the whole request away, while an empty one, a reply's, or one
|
||||
// turns the whole request away, as does a reply to a tool result without
|
||||
// it, while an empty one, another reply's, or one
|
||||
// from before the user's last message missing are taken.
|
||||
func deepseekRefuseToolTurns(body []byte) (int, string) {
|
||||
var q struct {
|
||||
@@ -24,10 +25,13 @@ func deepseekRefuseToolTurns(body []byte) (int, string) {
|
||||
last = i
|
||||
}
|
||||
}
|
||||
afterTool := false
|
||||
for _, m := range q.Messages[last+1:] {
|
||||
if string(m["role"]) == `"assistant"` && len(m["tool_calls"]) > 0 && m["reasoning_content"] == nil {
|
||||
// a reply to a tool result too (checked 2026-10-12, #1822)
|
||||
if string(m["role"]) == `"assistant"` && (len(m["tool_calls"]) > 0 || afterTool) && m["reasoning_content"] == nil {
|
||||
return 400, `{"error":{"message":"The ` + "`reasoning_content`" + ` in the thinking mode must be passed back to the API. (request_id: 06048513-d7c7-4cdf-9998-47bfc20484e6)","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`
|
||||
}
|
||||
afterTool = string(m["role"]) == `"tool"`
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
|
||||
@@ -347,17 +347,30 @@ func reasoningText(m map[string]json.RawMessage) string {
|
||||
const noReasoning = " "
|
||||
|
||||
// withReasoningOnToolTurns gives each assistant message of a Chat request
|
||||
// that has tool calls and no reasoning_content one: the thinking it sent
|
||||
// back in another field (reasoning, reasoning_details), else noReasoning.
|
||||
// A message with reasoning_content of its own keeps it, a reply without
|
||||
// tool calls is left as it is (DeepSeek doesn't ask for its thinking), and
|
||||
// a body with no tool calls comes back byte for byte.
|
||||
// that has tool calls, or that follows a tool message of its turn, and no
|
||||
// reasoning_content one: the thinking it sent back in another field
|
||||
// (reasoning, reasoning_details), else noReasoning. DeepSeek turns away a
|
||||
// reply after a tool result with none as it does a call (checked against
|
||||
// api.deepseek.com on 2026-10-12, #1822). A message with reasoning_content
|
||||
// of its own keeps it, any other reply is left as it is (DeepSeek doesn't
|
||||
// ask for its thinking), and a body with no tool calls comes back byte for
|
||||
// byte.
|
||||
func withReasoningOnToolTurns(body []byte) []byte {
|
||||
afterTool := false
|
||||
return editMessages(body, []string{"tool_calls"}, func(m map[string]json.RawMessage) bool {
|
||||
var role string
|
||||
var calls []json.RawMessage
|
||||
if decodeJSON(m["role"], &role) != nil || role != "assistant" ||
|
||||
decodeJSON(m["tool_calls"], &calls) != nil || len(calls) == 0 {
|
||||
decodeJSON(m["role"], &role)
|
||||
switch role {
|
||||
case "tool":
|
||||
afterTool = true
|
||||
case "user":
|
||||
afterTool = false
|
||||
}
|
||||
if raw, ok := m["tool_calls"]; ok && decodeJSON(raw, &calls) != nil {
|
||||
return false
|
||||
}
|
||||
if role != "assistant" || len(calls) == 0 && !afterTool {
|
||||
return false
|
||||
}
|
||||
var own *string
|
||||
|
||||
@@ -26,13 +26,19 @@ func deepseekRefuseAnthropic(body []byte) (int, string) {
|
||||
}
|
||||
json.Unmarshal(body, &q)
|
||||
thinking := q.Thinking == nil || q.Thinking.Type != "disabled"
|
||||
// afterTool: the message before is tool results alone, which a reply
|
||||
// with no thinking is refused after too (checked 2026-10-12, #1822)
|
||||
afterTool := false
|
||||
for i, m := range q.Messages {
|
||||
var blocks []struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
json.Unmarshal(m.Content, &blocks)
|
||||
after := afterTool
|
||||
afterTool = m.Role == "user" && len(blocks) > 0
|
||||
thought, called := false, false
|
||||
for _, b := range blocks {
|
||||
afterTool = afterTool && b.Type == "tool_result"
|
||||
switch b.Type {
|
||||
case "redacted_thinking":
|
||||
return 422, `{"error":{"message":"Failed to deserialize the JSON body into the target type: messages[` + string(rune('0'+i)) + "].content: unknown variant `redacted_thinking`, expected one of `text`, `image`, `document`, `thinking`, `server_tool_use`, `tool_use`, `tool_result`" + `","type":"invalid_request_error"}}`
|
||||
@@ -42,7 +48,7 @@ func deepseekRefuseAnthropic(body []byte) (int, string) {
|
||||
called = true
|
||||
}
|
||||
}
|
||||
if thinking && m.Role == "assistant" && called && !thought {
|
||||
if thinking && m.Role == "assistant" && (called || after) && !thought {
|
||||
return 400, `{"error":{"message":"The ` + "`content[].thinking`" + ` in the thinking mode must be passed back to the API. (request_id: e689e65a-f4f1-4efb-a4e0-44b98b5325d4)","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// stepShape lists a Responses input's items by type, a reasoning item with
|
||||
// its reasoning_text and a message with its role.
|
||||
func stepShape(input []map[string]any) string {
|
||||
var got []string
|
||||
for _, it := range input {
|
||||
s, _ := it["type"].(string)
|
||||
switch s {
|
||||
case "reasoning":
|
||||
content, _ := it["content"].([]any)
|
||||
for _, c := range content {
|
||||
if m, _ := c.(map[string]any); m["type"] == "reasoning_text" {
|
||||
s += fmt.Sprintf("=%q", m["text"])
|
||||
}
|
||||
}
|
||||
case "message":
|
||||
s += ":" + fmt.Sprint(it["role"])
|
||||
}
|
||||
got = append(got, s)
|
||||
}
|
||||
return strings.Join(got, ",")
|
||||
}
|
||||
|
||||
// TestDeepSeekStepSaysBeforeItsCall (#1822, Codex → OpenCode Go's DeepSeek;
|
||||
// #1592 and #1687 on DeepSeek's own API): a step of Codex's history that
|
||||
// said something and then made a call, with no reasoning item (another
|
||||
// model's turn), was sent [message, reasoning " ", call]: magpie put the
|
||||
// reasoning it made up right before the call. DeepSeek reads a step as one
|
||||
// assistant message whose thinking is the item it starts with, so it
|
||||
// refused the request with "The `reasoning_text` in the thinking mode must
|
||||
// be passed back to the API", while a step with only a call was taken. Each
|
||||
// step now leads with its reasoning: its own moved ahead of what it said,
|
||||
// else a space.
|
||||
func TestDeepSeekStepSaysBeforeItsCall(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &deepseekResponses{}
|
||||
srv := httptest.NewServer(up)
|
||||
defer srv.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "opencode-go", Name: "OpenCode Go", Key: "k", Models: []string{"deepseek-v4.1-flash"}, Responses: srv.URL + "/zen/go/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{ID: "codex-brain", Name: "codex-brain", Members: []string{"opencode-go/deepseek-v4.1-flash"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := `{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the login bug"}]}`
|
||||
said := func(text string) string {
|
||||
return `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"` + text + `"}]}`
|
||||
}
|
||||
call := func(id string) string {
|
||||
return `{"type":"function_call","call_id":"` + id + `","name":"shell","arguments":"{\"command\":[\"ls\"]}"},
|
||||
{"type":"function_call_output","call_id":"` + id + `","output":"main.go"}`
|
||||
}
|
||||
sealed := `{"type":"reasoning","id":"rs_0d1f","summary":[],"content":null,"encrypted_content":"gAAAAABpZm9vYmFy"}`
|
||||
summed := `{"type":"reasoning","id":"rs_2","summary":[{"type":"summary_text","text":"Run the tests."}],"content":null,"encrypted_content":null}`
|
||||
for _, c := range []struct{ name, input, want string }{
|
||||
{"the reporter's: said, then called, no reasoning",
|
||||
user + `,` + sealed + `,` + call("c1") + `,` + said("I'll run the tests.") + `,` + call("c2"),
|
||||
`message:user,reasoning=" ",function_call,function_call_output,reasoning=" ",message:assistant,function_call,function_call_output`},
|
||||
{"said, reasoning, called",
|
||||
user + `,` + said("Looking.") + `,` + summed + `,` + call("c1"),
|
||||
`message:user,reasoning="Run the tests.",message:assistant,function_call,function_call_output`},
|
||||
{"said after a tool output",
|
||||
user + `,` + call("c1") + `,` + said("It passes."),
|
||||
`message:user,reasoning=" ",function_call,function_call_output,reasoning=" ",message:assistant`},
|
||||
{"a step that leads with its reasoning",
|
||||
user + `,` + summed + `,` + said("Looking.") + `,` + call("c1"),
|
||||
`message:user,reasoning="Run the tests.",message:assistant,function_call,function_call_output`},
|
||||
} {
|
||||
for _, model := range []string{"opencode-go/deepseek-v4.1-flash", "deepseek/deepseek-flash", "group/codex-brain"} {
|
||||
for _, stream := range []string{"true", "false"} {
|
||||
code, b := post(t, "/v1/responses", `{"model":"`+model+`","stream":`+stream+`,"store":false,"reasoning":{"effort":"high","summary":"auto"},"include":["reasoning.encrypted_content"],
|
||||
"tools":[{"type":"function","name":"shell","parameters":{"type":"object","properties":{"command":{"type":"array","items":{"type":"string"}}}}}],"input":[`+c.input+`]}`)
|
||||
if code != 200 {
|
||||
t.Errorf("%s, %s, stream %s: %d %s", c.name, model, stream, code, b)
|
||||
continue
|
||||
}
|
||||
if got := stepShape(up.last()); got != c.want {
|
||||
t.Errorf("%s, %s: sent\n%s\nwant\n%s", c.name, model, got, c.want)
|
||||
}
|
||||
for _, it := range up.last() {
|
||||
if it["id"] == "rs_0d1f" && it["encrypted_content"] != "gAAAAABpZm9vYmFy" {
|
||||
t.Errorf("%s: the sealed item lost its encrypted_content: %v", c.name, it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// withReasoningText leaves a body whose steps all lead with reasoning text
|
||||
// byte for byte, and a reply to the user (no call, no tool output before
|
||||
// it) without reasoning, as DeepSeek takes it.
|
||||
func TestWithReasoningTextLedStepsUnchanged(t *testing.T) {
|
||||
for _, b := range []string{
|
||||
`{"model":"deepseek-flash","input":[{"type":"message","role":"user","content":"hi"},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello!"}]},{"type":"message","role":"user","content":"ls"}]}`,
|
||||
`{"model":"deepseek-flash", "input":[{"type":"message","role":"user","content":"ls"},{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"x"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Looking."}]},{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"},{"type":"function_call_output","call_id":"c1","output":"ok"},{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"y"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Done."}]}]}`,
|
||||
} {
|
||||
if got := string(withReasoningText([]byte(b))); got != b {
|
||||
t.Errorf("%s\nbecame %s", b, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Translated to DeepSeek's Responses API (an agent of another protocol, or
|
||||
// Codex's web_search), an assistant turn that said something before its
|
||||
// call goes with its reasoning first too (#1822).
|
||||
func TestTranslatedDeepSeekStepLeadsWithReasoning(t *testing.T) {
|
||||
for _, c := range []struct{ input, want string }{
|
||||
{`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Looking."}]},
|
||||
{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"}`,
|
||||
`message:user,reasoning=" ",message:assistant,function_call,function_call_output`},
|
||||
{`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Looking."}]},
|
||||
{"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"Need ls."}]},
|
||||
{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"}`,
|
||||
`message:user,reasoning="Need ls.",message:assistant,function_call,function_call_output`},
|
||||
} {
|
||||
r, err := parseResponses([]byte(`{"model":"m","input":[{"type":"message","role":"user","content":"ls"},` + c.input + `,
|
||||
{"type":"function_call_output","call_id":"c1","output":"ok"}]}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var q struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
json.Unmarshal(buildResponses(r, "deepseek-flash", "api.deepseek.com", false), &q)
|
||||
if got := stepShape(q.Input); got != c.want {
|
||||
t.Errorf("sent %s\nwant %s", got, c.want)
|
||||
}
|
||||
if b := buildResponses(r, "gpt-5.4", "relay.example", false); strings.Contains(string(b), `"reasoning_text"`) {
|
||||
t.Errorf("gpt-5.4 was given reasoning: %s", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A Chat request to a DeepSeek model whose last reply answers a tool result
|
||||
// with no reasoning_content gets one, relayed or translated: DeepSeek's
|
||||
// Chat API refuses it as it does a bare call (checked 2026-10-12, #1822).
|
||||
func TestChatReplyAfterToolGetsReasoning(t *testing.T) {
|
||||
f := &fake{t: t, reply: chatWholeOK, ctype: "application/json", refuse: deepseekRefuseToolTurns}
|
||||
up := setup(t, provider.Chat, f)
|
||||
chatProvider(t, up.URL, provider.Provider{ID: "go", Models: []string{"deepseek-v4.1-flash"}})
|
||||
srv := New()
|
||||
code, body := postTo(t, srv, "/v1/chat/completions", `{"model":"go/deepseek-v4.1-flash","stream":false,"messages":[
|
||||
{"role":"user","content":"what time is it?"},
|
||||
{"role":"assistant","content":null,"tool_calls":[`+timeCall+`],"reasoning_content":"Ask."},
|
||||
{"role":"tool","tool_call_id":"call_1","content":"12:00"},
|
||||
{"role":"assistant","content":"It is 12:00."}]}`)
|
||||
if code != 200 || f.calls != 1 {
|
||||
t.Fatalf("relayed: %d after %d calls: %s", code, f.calls, body)
|
||||
}
|
||||
sameJSON(t, sentMessages(t, f.got)[3], `{"role":"assistant","content":"It is 12:00.","reasoning_content":" "}`)
|
||||
|
||||
f.calls = 0
|
||||
f.reply, f.ctype = `data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":"Yes."},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n", ""
|
||||
code, body = postTo(t, srv, "/v1/responses", `{"model":"go/deepseek-v4.1-flash","stream":false,"input":[
|
||||
{"type":"message","role":"user","content":[{"type":"input_text","text":"what time is it?"}]},
|
||||
{"type":"function_call","call_id":"call_1","name":"get_time","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call_1","output":"12:00"},
|
||||
{"type":"message","role":"assistant","content":[{"type":"output_text","text":"It is 12:00."}]}]}`)
|
||||
if code != 200 || f.calls != 1 {
|
||||
t.Fatalf("translated: %d after %d calls: %s", code, f.calls, body)
|
||||
}
|
||||
}
|
||||
|
||||
// The same on DeepSeek's Anthropic endpoint: a reply to tool results alone
|
||||
// goes with a thinking block (checked 2026-10-12, #1822); a reply to the
|
||||
// user goes as it was.
|
||||
func TestAnthropicReplyAfterToolGetsThinking(t *testing.T) {
|
||||
b := `{"model":"deepseek-flash","messages":[
|
||||
{"role":"user","content":"ls"},
|
||||
{"role":"assistant","content":[{"type":"thinking","thinking":"x"},{"type":"tool_use","id":"t","name":"n","input":{}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":"ok"}]},
|
||||
{"role":"assistant","content":[{"type":"text","text":"Done."}]},
|
||||
{"role":"user","content":[{"type":"text","text":"thanks"}]},
|
||||
{"role":"assistant","content":[{"type":"text","text":"You're welcome."}]}]}`
|
||||
if code, msg := deepseekRefuseAnthropic([]byte(b)); code == 0 {
|
||||
t.Fatal("the fake took a reply to tool results with no thinking")
|
||||
} else if code, msg = deepseekRefuseAnthropic(withThinkingOnToolTurns([]byte(b))); code != 0 {
|
||||
t.Fatalf("%d %s", code, msg)
|
||||
}
|
||||
ms := sentAnthropicMessages(t, withThinkingOnToolTurns([]byte(b)))
|
||||
sameJSON(t, ms[3], `{"role":"assistant","content":[{"type":"thinking","thinking":" "},{"type":"text","text":"Done."}]}`)
|
||||
sameJSON(t, ms[5], `{"role":"assistant","content":[{"type":"text","text":"You're welcome."}]}`)
|
||||
}
|
||||
@@ -30,32 +30,11 @@ func (u *deepseekResponses) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
u.mu.Lock()
|
||||
u.inputs = append(u.inputs, q.Input)
|
||||
u.mu.Unlock()
|
||||
// api.deepseek.com's /v1/responses (deepseek-flash, high, checked
|
||||
// 2026-10-11 for #1592) also refuses a tool call whose step has no
|
||||
// reasoning item, as one of the ChatGPT backend's sealed items leaves it
|
||||
thought := false
|
||||
for _, it := range q.Input {
|
||||
ok := true
|
||||
switch {
|
||||
case it["type"] == "reasoning":
|
||||
thought, ok = true, false
|
||||
content, _ := it["content"].([]any)
|
||||
for _, c := range content {
|
||||
if m, _ := c.(map[string]any); m["type"] == "reasoning_text" && m["text"] != "" {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
case it["type"] == "function_call":
|
||||
ok = thought
|
||||
case it["type"] == "function_call_output", it["role"] == "user":
|
||||
thought = false
|
||||
}
|
||||
if !ok {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, `{"error":{"message":"The `+"`reasoning_text`"+` in the thinking mode must be passed back to the API.","type":"invalid_request_error","param":"input","code":"invalid_request_error"}}`)
|
||||
return
|
||||
}
|
||||
if !deepseekTakesInput(q.Input) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, `{"error":{"message":"The `+"`reasoning_text`"+` in the thinking mode must be passed back to the API.","type":"invalid_request_error","param":"input","code":"invalid_request_error"}}`)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
@@ -64,6 +43,61 @@ func (u *deepseekResponses) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
`data: {"type":"response.completed","response":{"id":"resp_ds","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`))
|
||||
}
|
||||
|
||||
// deepseekTakesInput is whether api.deepseek.com's /v1/responses
|
||||
// (deepseek-flash, high) takes a request's input in thinking mode: every
|
||||
// reasoning item has a reasoning_text that isn't empty (#1104), and each
|
||||
// step of the turn being continued (the model's reasoning, what it said and
|
||||
// its calls, between a user message or a tool output and the next) that
|
||||
// makes a call (#1592) or follows a tool output starts with a reasoning
|
||||
// item. A step that said something before its reasoning, or with none
|
||||
// before its call, is refused (#1822). Checked 2026-10-11 and 2026-10-12:
|
||||
// [text, reasoning, call] and [output, text] are refused, [reasoning, text,
|
||||
// call] is taken, and a step before the last user message isn't looked at.
|
||||
func deepseekTakesInput(input []map[string]any) bool {
|
||||
turn := -1
|
||||
for i, it := range input {
|
||||
if it["role"] == "user" {
|
||||
turn = i
|
||||
}
|
||||
}
|
||||
start, lead, called, afterOut := -1, false, false, false
|
||||
stepOK := func() bool { return start < turn || lead || !called && !afterOut }
|
||||
for i, it := range input {
|
||||
typ, _ := it["type"].(string)
|
||||
role, _ := it["role"].(string)
|
||||
if typ == "reasoning" {
|
||||
ok := false
|
||||
content, _ := it["content"].([]any)
|
||||
for _, c := range content {
|
||||
if m, _ := c.(map[string]any); m["type"] == "reasoning_text" && m["text"] != "" {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if typ == "reasoning" || typ == "function_call" || typ == "custom_tool_call" || (typ == "message" || typ == "") && role == "assistant" {
|
||||
if start < 0 {
|
||||
start, lead, called = i, typ == "reasoning", false
|
||||
}
|
||||
called = called || strings.HasSuffix(typ, "_call")
|
||||
continue
|
||||
}
|
||||
if start >= 0 && !stepOK() {
|
||||
return false
|
||||
}
|
||||
start = -1
|
||||
switch {
|
||||
case strings.HasSuffix(typ, "_output"):
|
||||
afterOut = true
|
||||
case role == "user":
|
||||
afterOut = false
|
||||
}
|
||||
}
|
||||
return start < 0 || stepOK()
|
||||
}
|
||||
|
||||
func (u *deepseekResponses) last() []map[string]any {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
|
||||
+138
-42
@@ -693,18 +693,19 @@ func replaysReasoning(model, host string) bool {
|
||||
}
|
||||
|
||||
// withReasoningText gives each reasoning item in a Responses request that
|
||||
// carries no reasoning_text its summary as one, else noReasoning, and each
|
||||
// tool call a step made with no reasoning item one holding noReasoning, for
|
||||
// an upstream that wants the reasoning back (replaysReasoning). Codex sends
|
||||
// an item back as it got it: one from a turn magpie translated has only a
|
||||
// carries no reasoning_text its summary as one, else noReasoning, and has
|
||||
// each step that needs one lead with a reasoning item (reasonFirst), for an
|
||||
// upstream that wants the reasoning back (replaysReasoning). Codex sends an
|
||||
// item back as it got it: one from a turn magpie translated has only a
|
||||
// summary, one the ChatGPT backend sealed has only encrypted_content, and a
|
||||
// turn another model in a mixed group served may have no reasoning item at
|
||||
// all. DeepSeek refuses the whole request over any of them, and over an
|
||||
// empty reasoning_text, with "The `reasoning_text` in the thinking mode must
|
||||
// be passed back to the API" (#1104, #1592). A body with nothing to give
|
||||
// comes back byte for byte.
|
||||
// be passed back to the API" (#1104, #1592, #1822). A body with nothing to
|
||||
// give comes back byte for byte.
|
||||
func withReasoningText(body []byte) []byte {
|
||||
if !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`_call"`)) {
|
||||
if !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`_call"`)) &&
|
||||
!bytes.Contains(body, []byte(`_output"`)) {
|
||||
return body
|
||||
}
|
||||
var q map[string]json.RawMessage
|
||||
@@ -716,11 +717,8 @@ func withReasoningText(body []byte) []byte {
|
||||
return body
|
||||
}
|
||||
changed := false
|
||||
// thought: the step the model is on (since the last user message or
|
||||
// tool output) has a reasoning item
|
||||
thought := false
|
||||
out := make([]json.RawMessage, 0, len(items))
|
||||
for _, raw := range items {
|
||||
kinds := make([]stepKind, len(items))
|
||||
for i, raw := range items {
|
||||
var it struct {
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
@@ -728,25 +726,11 @@ func withReasoningText(body []byte) []byte {
|
||||
Content []rText `json:"content"`
|
||||
}
|
||||
if decodeJSON(raw, &it) != nil {
|
||||
out = append(out, raw)
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case it.Type == "reasoning":
|
||||
thought = true
|
||||
case it.Type == "function_call", it.Type == "custom_tool_call":
|
||||
if !thought {
|
||||
r, _ := json.Marshal(map[string]any{"type": "reasoning", "summary": []any{},
|
||||
"content": []map[string]string{{"type": "reasoning_text", "text": noReasoning}}})
|
||||
out = append(out, r)
|
||||
thought, changed = true, true
|
||||
}
|
||||
case strings.HasSuffix(it.Type, "_output"), it.Type == "message" && it.Role != "assistant", it.Type == "" && it.Role != "" && it.Role != "assistant":
|
||||
thought = false
|
||||
}
|
||||
kinds[i] = stepKindOf(it.Type, it.Role)
|
||||
if it.Type != "reasoning" ||
|
||||
slices.ContainsFunc(it.Content, func(c rText) bool { return c.Type == "reasoning_text" && c.Text != "" }) {
|
||||
out = append(out, raw)
|
||||
continue
|
||||
}
|
||||
var b strings.Builder
|
||||
@@ -758,19 +742,21 @@ func withReasoningText(body []byte) []byte {
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
if decodeJSON(raw, &m) != nil {
|
||||
out = append(out, raw)
|
||||
continue
|
||||
}
|
||||
m["content"], _ = json.Marshal([]map[string]string{{"type": "reasoning_text", "text": b.String()}})
|
||||
if nb, err := json.Marshal(m); err == nil {
|
||||
raw, changed = nb, true
|
||||
items[i], changed = nb, true
|
||||
}
|
||||
out = append(out, raw)
|
||||
}
|
||||
none, _ := json.Marshal(noReasoningItem())
|
||||
if led, ok := reasonFirst(items, kinds, json.RawMessage(none)); ok {
|
||||
items, changed = led, true
|
||||
}
|
||||
if !changed {
|
||||
return body
|
||||
}
|
||||
q["input"], _ = json.Marshal(out)
|
||||
q["input"], _ = json.Marshal(items)
|
||||
nb, err := json.Marshal(q)
|
||||
if err != nil {
|
||||
return body
|
||||
@@ -778,6 +764,107 @@ func withReasoningText(body []byte) []byte {
|
||||
return nb
|
||||
}
|
||||
|
||||
// stepKind is what a Responses input item is to a step of the model's: its
|
||||
// reasoning, something it said or a call it made, what answered a call, or
|
||||
// a message of the user's (or the system's) that starts a turn.
|
||||
type stepKind int
|
||||
|
||||
const (
|
||||
stepOther stepKind = iota
|
||||
stepReasoning
|
||||
stepSaid
|
||||
stepCall
|
||||
stepOutput
|
||||
stepTurn
|
||||
)
|
||||
|
||||
func stepKindOf(typ, role string) stepKind {
|
||||
switch {
|
||||
case typ == "reasoning":
|
||||
return stepReasoning
|
||||
case strings.HasSuffix(typ, "_output"):
|
||||
return stepOutput
|
||||
case strings.HasSuffix(typ, "_call"):
|
||||
return stepCall
|
||||
case (typ == "message" || typ == "") && role == "assistant":
|
||||
return stepSaid
|
||||
case typ == "message" || typ == "" && role != "":
|
||||
return stepTurn
|
||||
}
|
||||
return stepOther
|
||||
}
|
||||
|
||||
// noReasoningItem is the reasoning item a step leads with when it has none
|
||||
// of its own (reasonFirst).
|
||||
func noReasoningItem() map[string]any {
|
||||
return map[string]any{"type": "reasoning", "summary": []any{},
|
||||
"content": []map[string]any{{"type": "reasoning_text", "text": noReasoning}}}
|
||||
}
|
||||
|
||||
// reasonFirst has each step of the model's (a run of its reasoning, what it
|
||||
// said and the calls it made, between a user message or a tool output and
|
||||
// the next) that makes a call, or that follows a tool output, lead with a
|
||||
// reasoning item: the step's first one moved ahead of the rest, else none.
|
||||
// DeepSeek's /v1/responses reads a step as one assistant message whose
|
||||
// thinking is the reasoning item it starts with, and turns the whole
|
||||
// request away ("The `reasoning_text` in the thinking mode must be passed
|
||||
// back to the API") when a step of the turn being continued starts with
|
||||
// anything else: a call (#1592), or what the model said, as Codex sends a
|
||||
// step that said something before its call with its reasoning between them,
|
||||
// or with none, which magpie put between them (#1822). Checked against
|
||||
// api.deepseek.com on 2026-10-12: [text, reasoning, call] and [output,
|
||||
// text] are refused, [reasoning, text, call] and [output, reasoning, text]
|
||||
// are taken. ok is false, and items comes back as it is, when every such
|
||||
// step leads with one already.
|
||||
func reasonFirst[T any](items []T, kinds []stepKind, none T) (led []T, ok bool) {
|
||||
step := func(k stepKind) bool { return k == stepReasoning || k == stepSaid || k == stepCall }
|
||||
afterOutput := false
|
||||
for i := 0; i < len(items); {
|
||||
if !step(kinds[i]) {
|
||||
switch kinds[i] {
|
||||
case stepOutput:
|
||||
afterOutput = true
|
||||
case stepTurn:
|
||||
afterOutput = false
|
||||
}
|
||||
if ok {
|
||||
led = append(led, items[i])
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
j, calls, first := i, false, -1
|
||||
for ; j < len(items) && step(kinds[j]); j++ {
|
||||
calls = calls || kinds[j] == stepCall
|
||||
if kinds[j] == stepReasoning && first < 0 {
|
||||
first = j
|
||||
}
|
||||
}
|
||||
if (calls || afterOutput) && first != i {
|
||||
if !ok {
|
||||
led, ok = append(make([]T, 0, len(items)+1), items[:i]...), true
|
||||
}
|
||||
if first < 0 {
|
||||
led = append(led, none)
|
||||
} else {
|
||||
led = append(led, items[first])
|
||||
}
|
||||
for x := i; x < j; x++ {
|
||||
if x != first {
|
||||
led = append(led, items[x])
|
||||
}
|
||||
}
|
||||
} else if ok {
|
||||
led = append(led, items[i:j]...)
|
||||
}
|
||||
i = j
|
||||
}
|
||||
if !ok {
|
||||
return items, false
|
||||
}
|
||||
return led, true
|
||||
}
|
||||
|
||||
// sealedReasoning is a reasoning item a Responses API sealed, fit to go
|
||||
// back to one as it came: encrypted_content in it, and no reasoning text
|
||||
// (which OpenAI and the ChatGPT backend refuse in input, #1411; one with
|
||||
@@ -803,8 +890,6 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
replay := replaysReasoning(model, host)
|
||||
var input []any
|
||||
for _, m := range r.Messages {
|
||||
// thought: this assistant turn has sent a reasoning item
|
||||
thought := false
|
||||
var content []map[string]any
|
||||
flushMsg := func() {
|
||||
if len(content) == 0 {
|
||||
@@ -844,18 +929,9 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
flushMsg()
|
||||
input = append(input, map[string]any{"type": "reasoning", "summary": []any{},
|
||||
"content": []map[string]any{{"type": "reasoning_text", "text": p.Text}}})
|
||||
thought = true
|
||||
}
|
||||
case ToolCall:
|
||||
flushMsg()
|
||||
if replay && !thought {
|
||||
// a call with no thinking (another model's turn, or
|
||||
// reasoning sealed by the ChatGPT backend), which
|
||||
// DeepSeek turns the whole request away for (#1592)
|
||||
input = append(input, map[string]any{"type": "reasoning", "summary": []any{},
|
||||
"content": []map[string]any{{"type": "reasoning_text", "text": noReasoning}}})
|
||||
thought = true
|
||||
}
|
||||
id := p.ID
|
||||
if id == "" {
|
||||
id = "call_" + newID()
|
||||
@@ -884,6 +960,26 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
}
|
||||
flushMsg()
|
||||
}
|
||||
if replay {
|
||||
// each step that makes a call, or follows a tool output, leads with
|
||||
// its reasoning, or with a space's (#1592, #1822)
|
||||
kinds := make([]stepKind, len(input))
|
||||
for i, it := range input {
|
||||
var k struct {
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
switch v := it.(type) {
|
||||
case map[string]any:
|
||||
k.Type, _ = v["type"].(string)
|
||||
k.Role, _ = v["role"].(string)
|
||||
case json.RawMessage:
|
||||
decodeJSON(v, &k)
|
||||
}
|
||||
kinds[i] = stepKindOf(k.Type, k.Role)
|
||||
}
|
||||
input, _ = reasonFirst(input, kinds, any(noReasoningItem()))
|
||||
}
|
||||
if input == nil {
|
||||
input = []any{}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user