diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index d6ab16904..126a28648 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -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 + // 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 + "\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 …: 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 …, and MiniMax's Chat + // API (#1267), like the open models served without a reasoning + // parser, as a leading …: 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 = "", "" +// 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{"": "", "": ""} -// text sends a piece of the reply's text, a leading block of it -// as thinking. +// text sends a piece of the reply's text, a leading or +// 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 = "" diff --git a/internal/gateway/minimax_think_test.go b/internal/gateway/minimax_think_test.go new file mode 100644 index 000000000..f6875a9cf --- /dev/null +++ b/internal/gateway/minimax_think_test.go @@ -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 tags, the tags split across chunks, then the answer. +const miniMaxStream = `data: {"id":"0581e2a0","choices":[{"index":0,"delta":{"content":"\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\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 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 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", "\nThe user greets me.\n\n\nHello!"}, + {"MiniMax-M2.7", "api.minimaxi.com", "\nThe user greets me.\n\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 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{"Greeting.\n\nHello"}, "Greeting.", "Hello"}, + {"one byte a chunk", strings.Split("abcd", ""), "ab", "cd"}, + {"a thought's close doesn't end it", []string{"abc"}, "ab", "c"}, + {"a think tag later", []string{"Hi no"}, "", "Hi no"}, + {""}, "", ""}, + } { + 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) + } + }) + } +}