gateway: MiniMax's thinking reaches Codex as reasoning, folded, not as the answer's text (#1267, pluo)

MiniMax's own Chat API (api.minimax.io, api.minimaxi.com), which Codex's
Responses requests to a MiniMax key are translated onto, gives a model's
thinking at the head of the text between <think>…</think>. The Chat decoder
only knew Gemini's leading <thought>…</thought>, so the thinking went to
Codex as message text. A leading <think> block is now thinking too, however
its tags fall across chunks; a tag later in the text stays text.

MiniMax asks for that thinking back in the assistant's text on later turns
(interleaved thinking), which it got before only because it was taken for
text. On MiniMax's own hosts it now goes back between <think> tags; a relay
serving MiniMax's models, and every other Chat upstream, is sent what it was
before.

Verified: TestMiniMaxThinkTagsReachCodexAsReasoning (Codex /v1/responses
through the gateway to a fake Chat upstream with MiniMax-shaped chunks),
TestMiniMaxThinkingGoesBackInTags and TestChatThinkTags fail on the old
chat.go (message text "<think>\nThe user greets me…</think>\n\nHello!",
items [message]; assistant content "Hello!" without the thinking) and pass
with it. The chunk shape is from MiniMax's OpenAI-compatible docs; no real
MiniMax key was tried.
This commit is contained in:
yetone
2026-10-08 16:51:47 +08:00
parent 7067fce5ec
commit 2ab69d0f87
2 changed files with 182 additions and 12 deletions
+36 -12
View File
@@ -224,6 +224,12 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
// served (#388), as Command Code's plugin does for a Go key, as the
// built-in replayed it to /alpha/generate
replay := strings.Contains(host, "deepseek") || strings.Contains(strings.ToLower(model), "deepseek") || host == provider.CommandCodePlanID
// MiniMax's own Chat API gives a model's thinking in the text, between
// <think> tags, and wants it back there on the turns after (its
// interleaved thinking): the decoder takes it out as thinking (#1267),
// so it goes back in where it came from. A relay serving MiniMax's
// models may give the thinking apart and take it back otherwise.
inlineThink := strings.HasSuffix(host, "minimax.io") || strings.HasSuffix(host, "minimaxi.com")
// Gemini wants each step's thought signature back on its first call
// (#687), and one it can't check for a step it didn't sign
gemini := geminiCompat(host, model)
@@ -292,6 +298,9 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
}
}
t := text(m.Parts)
if think != "" && inlineThink && !(r.Resume && i == len(r.Messages)-1) {
t = "<think>" + think + "</think>\n\n" + t
}
if t != "" || len(calls) == 0 {
am["content"] = t
}
@@ -749,32 +758,47 @@ type chatDecoder struct {
toolID string // id of the open tool call, as some relays repeat it on every fragment
choice string // index of the first choice seen; an empty string means none yet
// Gemini's OpenAI-compatible API, asked for thoughts, may give them
// in the text as a leading <thought>…</thought>: lead holds the text
// while it could still be that tag's start, thought is being inside it
lead string
thought bool
past bool // the reply's text has begun; no tag is looked for now
// in the text as a leading <thought>…</thought>, and MiniMax's Chat
// API (#1267), like the open models served without a reasoning
// parser, as a leading <think>…</think>: lead holds the text while it
// could still be such a tag's start, thought is being inside one, and
// thoughtClose is the tag that ends it
lead string
thought bool
thoughtClose string
past bool // the reply's text has begun; no tag is looked for now
}
const thoughtOpen, thoughtClose = "<thought>", "</thought>"
// thoughtTags are the tags a leading block of thinking comes between in a
// Chat reply's text, by its opening tag.
var thoughtTags = map[string]string{"<thought>": "</thought>", "<think>": "</think>"}
// text sends a piece of the reply's text, a leading <thought> block of it
// as thinking.
// text sends a piece of the reply's text, a leading <thought> or <think>
// block of it as thinking.
func (d *chatDecoder) text(s string, emit func(Event)) {
if !d.past && !d.thought {
d.lead += s
lead := strings.TrimLeft(d.lead, " \n")
if len(lead) < len(thoughtOpen) && strings.HasPrefix(thoughtOpen, lead) {
return
for open := range thoughtTags {
if len(lead) < len(open) && strings.HasPrefix(open, lead) {
return
}
}
if !strings.HasPrefix(lead, thoughtOpen) {
open := ""
for o := range thoughtTags {
if strings.HasPrefix(lead, o) {
open = o
}
}
if open == "" {
d.past = true
s, d.lead = d.lead, ""
emit(Event{Kind: KText, Text: s})
return
}
s, d.lead, d.thought = strings.TrimPrefix(lead, thoughtOpen), "", true
s, d.lead, d.thought, d.thoughtClose = strings.TrimPrefix(lead, open), "", true, thoughtTags[open]
}
thoughtClose := d.thoughtClose
if d.thought {
s = d.lead + s
d.lead = ""
+146
View File
@@ -0,0 +1,146 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// miniMaxStream is a reply as MiniMax's Chat API streams it (its
// OpenAI-compatible docs for MiniMax-M2): the thinking at the head of the
// text between <think> tags, the tags split across chunks, then the answer.
const miniMaxStream = `data: {"id":"0581e2a0","choices":[{"index":0,"delta":{"content":"<th","role":"assistant","name":"MiniMax AI","audio_content":""}}],"created":1759900000,"model":"MiniMax-M2.7","object":"chat.completion.chunk"}
data: {"id":"0581e2a0","choices":[{"index":0,"delta":{"content":"ink>\nThe user greets me","role":"assistant","name":"MiniMax AI","audio_content":""}}],"created":1759900000,"model":"MiniMax-M2.7","object":"chat.completion.chunk"}
data: {"id":"0581e2a0","choices":[{"index":0,"delta":{"content":". Reply briefly.\n</thi","role":"assistant","name":"MiniMax AI","audio_content":""}}],"created":1759900000,"model":"MiniMax-M2.7","object":"chat.completion.chunk"}
data: {"id":"0581e2a0","choices":[{"index":0,"delta":{"content":"nk>\n\nHello!","role":"assistant","name":"MiniMax AI","audio_content":""}}],"created":1759900000,"model":"MiniMax-M2.7","object":"chat.completion.chunk"}
data: {"id":"0581e2a0","choices":[{"finish_reason":"stop","index":0,"delta":{"content":"","role":"assistant","name":"MiniMax AI","audio_content":""}}],"created":1759900000,"model":"MiniMax-M2.7","object":"chat.completion.chunk","usage":{"total_tokens":40,"prompt_tokens":20,"completion_tokens":20}}
data: [DONE]
`
func miniMaxSetup(t *testing.T, f *fake) {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
up := httptest.NewServer(f)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "minimax", Name: "MiniMax", Key: "k", Models: []string{"MiniMax-M2.7"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
}
// Codex asks MiniMax on its Chat API, which gives the thinking in the text
// between <think> tags. Codex folds it only as a reasoning item, so the
// tags' content goes to Codex as reasoning and the answer alone as the
// message (pluo, #1267: the thinking read as the answer's text).
func TestMiniMaxThinkTagsReachCodexAsReasoning(t *testing.T) {
f := &fake{t: t, reply: miniMaxStream}
miniMaxSetup(t, f)
code, body := post(t, "/v1/responses", `{"model":"minimax/MiniMax-M2.7","stream":true,"input":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("code %d: %s", code, body)
}
var reasoning, text string
var order []string
for _, ev := range events(body) {
if ev["type"] != "response.output_item.done" {
continue
}
item, _ := ev["item"].(map[string]any)
order = append(order, item["type"].(string))
b, _ := json.Marshal(item)
switch item["type"] {
case "reasoning":
reasoning += string(b)
case "message":
text += string(b)
}
}
if !strings.Contains(reasoning, "The user greets me. Reply briefly.") {
t.Errorf("no reasoning item with the thinking; items %v:\n%s", order, body)
}
if !strings.Contains(text, `"Hello!"`) || strings.Contains(text, "think") || strings.Contains(text, "greets") {
t.Errorf("message %s, want the answer alone", text)
}
if len(order) != 2 || order[0] != "reasoning" || order[1] != "message" {
t.Errorf("items %v, want reasoning then message", order)
}
}
// The thinking goes back to MiniMax where it came from, in the assistant's
// text between <think> tags, as MiniMax asks for its interleaved thinking;
// a relay serving MiniMax's models, or another model on Chat, is sent no
// thinking, as before.
func TestMiniMaxThinkingGoesBackInTags(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "\nThe user greets me.\n"}, {Kind: Text, Text: "Hello!"}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "again"}}},
}}
for _, c := range []struct{ model, host, want string }{
{"MiniMax-M2.7", "api.minimax.io", "<think>\nThe user greets me.\n</think>\n\nHello!"},
{"MiniMax-M2.7", "api.minimaxi.com", "<think>\nThe user greets me.\n</think>\n\nHello!"},
{"minimax/minimax-m3", "openrouter.ai", "Hello!"},
{"kimi-k3", "api.moonshot.cn", "Hello!"},
} {
var q struct {
Messages []map[string]any `json:"messages"`
}
if err := json.Unmarshal(buildChat(r, c.model, c.host, false), &q); err != nil {
t.Fatal(err)
}
if got := q.Messages[1]["content"]; got != c.want {
t.Errorf("%s at %s: assistant content %q, want %q", c.model, c.host, got, c.want)
}
}
}
// A <think> block at the head of a Chat reply is thinking however the tags
// fall across chunks; one later in the text, or a tag that only starts
// like it, is the answer as it came.
func TestChatThinkTags(t *testing.T) {
run := func(parts ...string) (think, text string) {
var d chatDecoder
for i, p := range parts {
ch := map[string]any{"index": 0, "delta": map[string]any{"content": p}}
if i == len(parts)-1 {
ch["finish_reason"] = "stop"
}
b, _ := json.Marshal(map[string]any{"id": "x", "choices": []any{ch}})
d.decode(string(b), func(ev Event) {
switch ev.Kind {
case KThink:
think += ev.Text
case KText:
text += ev.Text
}
})
}
return
}
for _, c := range []struct {
name string
parts []string
think, text string
}{
{"whole", []string{"<think>Greeting.</think>\n\nHello"}, "Greeting.", "Hello"},
{"one byte a chunk", strings.Split("<think>ab</think>cd", ""), "ab", "cd"},
{"a thought's close doesn't end it", []string{"<think>a</thought>b</think>c"}, "a</thought>b", "c"},
{"a think tag later", []string{"Hi <think>no</think>"}, "", "Hi <think>no</think>"},
{"<thin is text", []string{"<thin", "g>"}, "", "<thing>"},
} {
t.Run(c.name, func(t *testing.T) {
if think, text := run(c.parts...); think != c.think || text != c.text {
t.Errorf("think %q text %q, want %q %q", think, text, c.think, c.text)
}
})
}
}