diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go
index 1ebe178c4..5e5bd7b37 100644
--- a/internal/gateway/chat.go
+++ b/internal/gateway/chat.go
@@ -997,7 +997,14 @@ type chatDecoder struct {
lead string
thought bool
thoughtClose string
- past bool // the reply's text has begun; no tag is looked for now
+ // code is where the thinking is in Markdown code, where a close tag is
+ // an example written out, not the close (#2634: "使用 `…`
+ // 标签" cut the reply at the example's close)
+ code mdCode
+ past bool // the reply's text has begun; no tag is looked for now
+ // trim is a thinking block just closed: the line breaks after its
+ // close are left out of the answer, in whatever chunk they come
+ trim bool
}
// thoughtTags are the tags a leading block of thinking comes between in a
@@ -1033,21 +1040,15 @@ func (d *chatDecoder) text(s string, emit func(Event)) {
if d.thought {
s = d.lead + s
d.lead = ""
- if i := strings.Index(s, thoughtClose); i >= 0 {
+ if i, keep := d.code.find(s, thoughtClose, false); i >= 0 {
if i > 0 {
emit(Event{Kind: KThink, Text: s[:i]})
}
- d.thought, d.past = false, true
- s = strings.TrimLeft(s[i+len(thoughtClose):], "\n")
+ d.thought, d.past, d.trim = false, true, true
+ s = s[i+len(thoughtClose):]
} else {
- // the end of it may be the close tag begun
- keep := 0
- for n := min(len(thoughtClose)-1, len(s)); n > 0; n-- {
- if strings.HasSuffix(s, thoughtClose[:n]) {
- keep = n
- break
- }
- }
+ // the end of it may be the close tag, or a run of backticks,
+ // begun
if t := s[:len(s)-keep]; t != "" {
emit(Event{Kind: KThink, Text: t})
}
@@ -1055,11 +1056,91 @@ func (d *chatDecoder) text(s string, emit func(Event)) {
return
}
}
+ if d.trim {
+ if s = strings.TrimLeft(s, "\n"); s != "" {
+ d.trim = false
+ }
+ }
if s != "" {
emit(Event{Kind: KText, Text: s})
}
}
+// mdCode follows whether text read piece by piece is in Markdown code: an
+// inline span, taken to end with its line, or a fenced block.
+type mdCode struct {
+ span int // the backticks the open inline span began with; 0 for none
+ fence int // the backticks the open fenced block began with; 0 for none
+ mid bool // past the line's leading spaces
+}
+
+// find gives where close is first outside code in s, read on from the
+// pieces before, or -1 and how many bytes at the end of s are held back
+// for the next piece: a close tag or a run of backticks that may go on
+// there. Unless last, that is; then nothing is held.
+func (m *mdCode) find(s, close string, last bool) (at, hold int) {
+ for j := 0; j < len(s); {
+ switch c := s[j]; {
+ case c == '`':
+ k := j
+ for k < len(s) && s[k] == '`' {
+ k++
+ }
+ if k == len(s) && !last {
+ return -1, len(s) - j
+ }
+ switch n := k - j; {
+ case m.fence > 0:
+ if !m.mid && n >= m.fence {
+ m.fence = 0
+ }
+ case m.span > 0:
+ if n == m.span {
+ m.span = 0
+ }
+ case !m.mid && n >= 3:
+ m.fence = n
+ default:
+ m.span = n
+ }
+ m.mid = true
+ j = k
+ case c == '\n':
+ m.span, m.mid = 0, false
+ j++
+ case c == ' ' || c == '\t':
+ j++
+ case c == '<' && m.span == 0 && m.fence == 0:
+ if strings.HasPrefix(s[j:], close) {
+ return j, 0
+ }
+ if !last && strings.HasPrefix(close, s[j:]) {
+ return -1, len(s) - j
+ }
+ m.mid = true
+ j++
+ default:
+ m.mid = true
+ j++
+ }
+ }
+ return -1, 0
+}
+
+// afterThought is t without a leading … block, a whole
+// reply's thinking where its API leaves it in the text; t when it has none.
+func afterThought(t string) string {
+ rest, ok := strings.CutPrefix(t, "")
+ if !ok {
+ return t
+ }
+ var m mdCode
+ if i, _ := m.find(rest, "", true); i >= 0 {
+ return strings.TrimSpace(rest[i+len(""):])
+ }
+ return t
+}
+
// markedThought sends a piece of text Gemini marked as a thought
// (extra_content.google.thought) as thinking. AI Studio's OpenAI-compatible
// API may still wrap it in tags, and mark only the chunk with the
@@ -1184,6 +1265,12 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error {
}
if t != "" {
emit(Event{Kind: KThink, Text: t})
+ if !d.thought && d.lead == "" {
+ // a reply whose thinking has a field of its own doesn't
+ // also give it in its text: a there is the
+ // model's words (#2634)
+ d.past = true
+ }
}
if c.Delta.ExtraContent.Google.Thought {
d.markedThought(content, emit)
diff --git a/internal/gateway/codex_titles.go b/internal/gateway/codex_titles.go
index e02c47b68..f412b4161 100644
--- a/internal/gateway/codex_titles.go
+++ b/internal/gateway/codex_titles.go
@@ -278,11 +278,7 @@ func noPrediction(said string) string {
// or unusable answer is no prediction.
func predictionJSON(said string) (string, bool) {
t := strings.TrimSpace(said)
- if rest, ok := strings.CutPrefix(t, ""); ok {
- if _, after, ok := strings.Cut(rest, ""); ok {
- t = strings.TrimSpace(after)
- }
- }
+ t = afterThought(t)
if strings.HasPrefix(t, "```") {
t = strings.TrimPrefix(t, "```")
if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {
@@ -324,11 +320,7 @@ func noDescription(said string) string {
// object Codex asks for. An unusable answer returns an empty string.
func descriptionJSON(said string) string {
t := strings.TrimSpace(said)
- if rest, ok := strings.CutPrefix(t, ""); ok {
- if _, after, ok := strings.Cut(rest, ""); ok {
- t = strings.TrimSpace(after)
- }
- }
+ t = afterThought(t)
if strings.HasPrefix(t, "```") {
t = strings.TrimPrefix(t, "```")
if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {
@@ -492,11 +484,7 @@ func titleShapeOf(body []byte) titleShape {
func titleJSON(said string, shape titleShape) string {
t := strings.TrimSpace(said)
// a reasoning model's thoughts, where its API leaves them in the text
- if rest, ok := strings.CutPrefix(t, ""); ok {
- if _, after, ok := strings.Cut(rest, ""); ok {
- t = strings.TrimSpace(after)
- }
- }
+ t = afterThought(t)
if strings.HasPrefix(t, "```") {
t = strings.TrimPrefix(t, "```")
if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {
diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go
index 789b87894..ef30ce6b5 100644
--- a/internal/gateway/continuation.go
+++ b/internal/gateway/continuation.go
@@ -523,7 +523,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
return writeError(w, from, 502, failed), failed
}
} else {
- dec := decoder(actual)
+ dec := decoderFor(p, actual)
attemptSee := see
if names := textCallNames(request.Tools); names != nil {
t := &textCallSee{names: names, see: see}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 791161629..7da9c376f 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -5542,7 +5542,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
}
return writeVendorError(w, from, res.StatusCode, msg, b), msg
}
- dec := decoder(actual)
+ dec := decoderFor(p, actual)
rd, sse := eventStream(res)
if !sse {
// the provider ignored stream:true; read the whole reply as one
@@ -5787,6 +5787,18 @@ func build(proto provider.Protocol, r *Request, model, host string, rejectTemp b
return out, nil
}
+// decoderFor is decoder for p's replies. A plugin's Chat text is read as
+// OpenCode reads it, as it came: the plugin knows its vendor and gives its
+// reasoning apart, so a at the head of its text is the model's
+// words, not a block of thinking to take out (Qoder's, #2634).
+func decoderFor(p provider.Provider, proto provider.Protocol) func(data string, emit func(Event)) error {
+ if proto == provider.Chat && p.IsPlugin() {
+ d := &chatDecoder{past: true}
+ return d.decode
+ }
+ return decoder(proto)
+}
+
func decoder(proto provider.Protocol) func(data string, emit func(Event)) error {
switch proto {
case provider.Chat:
diff --git a/internal/gateway/search.go b/internal/gateway/search.go
index d39077ce8..767ec56ae 100644
--- a/internal/gateway/search.go
+++ b/internal/gateway/search.go
@@ -1085,7 +1085,7 @@ func (s *Server) askTranslated(p provider.Provider, to provider.Protocol, model
go func() {
defer close(events)
defer res.Body.Close()
- dec := decoder(actual)
+ dec := decoderFor(p, actual)
send := func(ev Event) error {
select {
case events <- ev:
diff --git a/internal/gateway/think_code_test.go b/internal/gateway/think_code_test.go
new file mode 100644
index 000000000..e5ea65ad6
--- /dev/null
+++ b/internal/gateway/think_code_test.go
@@ -0,0 +1,212 @@
+package gateway
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// The reply in Kane-Kuroneko's #2634, as its bytes were: thinking that
+// writes the close tag out as an inline-code example, then the answer.
+const exampleClose = "开始分析。使用 `...` 标签。\n继续分析。\n最终正文。"
+
+// The boundary #2634 saw from Qoder's plugin: the answer began at the
+// backtick after the first , and the reasoning was "...\n".
+const qoderBoundary = "...\n` 标签或 JSON 格式,Qoder 插件将其转为 OpenAI `tool_calls`"
+
+// chatChunks is a Chat stream giving text one Unicode character a delta,
+// each reasoning piece before it in reasoning_content.
+func chatChunks(text string, reasoning ...string) string {
+ var lines []string
+ add := func(delta map[string]any, finish any) {
+ b, _ := json.Marshal(map[string]any{"id": "c1", "object": "chat.completion.chunk", "model": "m1",
+ "choices": []any{map[string]any{"index": 0, "delta": delta, "finish_reason": finish}}})
+ lines = append(lines, "data: "+string(b))
+ }
+ for _, r := range reasoning {
+ add(map[string]any{"role": "assistant", "reasoning_content": r}, nil)
+ }
+ for _, r := range text {
+ add(map[string]any{"role": "assistant", "content": string(r)}, nil)
+ }
+ add(map[string]any{}, "stop")
+ lines = append(lines, `data: {"id":"c1","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":5,"completion_tokens":5}}`, "data: [DONE]")
+ return sse(lines...)
+}
+
+// A example written in Markdown code, inline or fenced, is the
+// thinking's words; only the close outside code ends it, however the text
+// falls across chunks.
+func TestChatThinkCloseInCode(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
+ }
+ runes := func(s string) []string {
+ var out []string
+ for _, r := range s {
+ out = append(out, string(r))
+ }
+ return out
+ }
+ want := "开始分析。使用 `...` 标签。\n继续分析。"
+ for _, c := range []struct {
+ name string
+ parts []string
+ think, text string
+ }{
+ {"#2634 whole", []string{exampleClose}, want, "最终正文。"},
+ {"#2634 a character a chunk", runes(exampleClose), want, "最终正文。"},
+ {"#2634 a byte a chunk", strings.Split(exampleClose, ""), want, "最终正文。"},
+ {"a double-backtick span", []string{"a ``x``` bc"}, "a ``x``` b", "c"},
+ {"a fenced block", runes("like\n```xml\n\n```\nso\nok"), "like\n```xml\n\n```\nso", "ok"},
+ {"a span ends with its line", []string{"a `b\n\nok"}, "a `b\n", "ok"},
+ {"backticks after the close", runes("a\n`x` y"), "a", "`x` y"},
+ {"a close tag split by a chunk", []string{"a `", "x` bc"}, "a `x` b", "c"},
+ {"backticks held at the end", []string{"a ``"}, "a ``", ""},
+ } {
+ 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)
+ }
+ })
+ }
+}
+
+// A reply whose thinking came in reasoning_content gives none in its text:
+// a there is what the model said (#2634).
+func TestChatThinkTagAfterReasoningField(t *testing.T) {
+ var d chatDecoder
+ var think, text string
+ readSSE(strings.NewReader(chatChunks(qoderBoundary, "先想一想。")), func(_, data string) error {
+ return d.decode(data, func(ev Event) {
+ switch ev.Kind {
+ case KThink:
+ think += ev.Text
+ case KText:
+ text += ev.Text
+ }
+ })
+ })
+ if think != "先想一想。" || text != qoderBoundary {
+ t.Errorf("think %q text %q, want the reasoning field's and the text as it came", think, text)
+ }
+}
+
+// #2634 through each route that reads a built-in Chat upstream's text:
+// Codex's Responses and Claude Code's Messages get the example's close in
+// the reasoning and the answer whole.
+func TestThinkExampleReachesClientsWhole(t *testing.T) {
+ f := &fake{t: t, reply: chatChunks(exampleClose)}
+ setup(t, provider.Chat, f)
+ code, body := post(t, "/v1/responses", `{"model":"fake/m1","stream":true,"input":[{"role":"user","content":"hi"}]}`)
+ if code != 200 {
+ t.Fatalf("responses: %d %s", code, body)
+ }
+ reasoning, text := thinkAndText(body)
+ if !strings.Contains(reasoning, "`...` 标签。\n继续分析。") || text != "最终正文。" {
+ t.Errorf("responses: reasoning %q, message %q", reasoning, text)
+ }
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"fake/m1","stream":true,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))
+ req.Header.Set("anthropic-version", "2023-06-01")
+ New().Handler().ServeHTTP(rec, req)
+ if rec.Code != 200 {
+ t.Fatalf("messages: %d %s", rec.Code, rec.Body)
+ }
+ var thinking, said string
+ for _, ev := range events(rec.Body.String()) {
+ if ev["type"] != "content_block_delta" {
+ continue
+ }
+ d, _ := ev["delta"].(map[string]any)
+ if s, ok := d["thinking"].(string); ok {
+ thinking += s
+ }
+ if s, ok := d["text"].(string); ok {
+ said += s
+ }
+ }
+ if !strings.Contains(thinking, "`...` 标签。\n继续分析。") || said != "最终正文。" {
+ t.Errorf("messages: thinking %q, text %q", thinking, said)
+ }
+}
+
+// thinkAndText is a Responses stream's reasoning summary and message
+// text, from its finished items.
+func thinkAndText(body string) (reasoning, text string) {
+ for _, ev := range events(body) {
+ if ev["type"] != "response.output_item.done" {
+ continue
+ }
+ item, _ := ev["item"].(map[string]any)
+ key, parts := "text", item["content"]
+ if item["type"] == "reasoning" {
+ parts = item["summary"]
+ }
+ list, _ := parts.([]any)
+ for _, p := range list {
+ m, _ := p.(map[string]any)
+ s, _ := m[key].(string)
+ if item["type"] == "reasoning" {
+ reasoning += s
+ } else {
+ text += s
+ }
+ }
+ }
+ return
+}
+
+// A plugin's Chat reply reaches Codex as OpenCode would show it: Qoder's
+// plugin gives its reasoning apart, so text that begins with is
+// the answer, all of it, never cut at the first (#2634).
+func TestPluginThinkTagIsText(t *testing.T) {
+ pid := besideFake(t, "qoder", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.ReadAll(r.Body)
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, chatChunks(qoderBoundary))
+ }))
+ code, body := post(t, "/v1/responses", `{"model":"`+pid+`/fake-1","stream":true,"input":[{"role":"user","content":"hi"}]}`)
+ if code != 200 {
+ t.Fatalf("%d %s", code, body)
+ }
+ if reasoning, text := thinkAndText(body); reasoning != "" || text != qoderBoundary {
+ t.Errorf("reasoning %q, message %q; want the text as the plugin gave it", reasoning, text)
+ }
+}
+
+// A title, description or prediction Codex asked for loses a leading
+// thinking block the same way: up to the close outside code.
+func TestAfterThoughtCloseInCode(t *testing.T) {
+ if got := afterThought(exampleClose); got != "最终正文。" {
+ t.Errorf("afterThought = %q", got)
+ }
+ if got := descriptionJSON("`` is a tag\nFix the parser"); !strings.Contains(got, "Fix the parser") || strings.Contains(got, "is a tag") {
+ t.Errorf("descriptionJSON = %q", got)
+ }
+ if got := afterThought("never closed"); got != "never closed" {
+ t.Errorf("afterThought of an open block = %q", got)
+ }
+}