An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: https://github.com/siyuan-note/siyuan/issues/18041
Daniel23335bac6f05
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex b673699171..f916d3a4c2 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -487,10 +487,6 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionvar contentBuilder strings.Buildervar reasoningBuilder strings.Buildervar aggregatedToolCalls []openai.ToolCall- // thinkSplitter 解析部分模型(如 MINIMAX、DeepSeek-V3、Qwen3、GLM 等)- // 将推理内容以 <think>...</think> 文本标签混在 delta.content 中返回的情况,- // 把标签内文本分流为 reasoning、标签外文本才作为 content。- splitter := newThinkSplitter()for {resp, recvErr := stream.Recv()@@ -518,16 +514,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionfor _, choice := range resp.Choices {if choice.Delta.Content != "" {- // 解析 <think>...</think> 标签:标签内归 reasoning,标签外归 content。- r, c := splitter.Feed(choice.Delta.Content)- if c != "" {- contentBuilder.WriteString(c)- sendEvent(ch, AgentEvent{Type: "content", Token: c})- }- if r != "" {- reasoningBuilder.WriteString(r)- sendEvent(ch, AgentEvent{Type: "reasoning", Token: r})- }+ contentBuilder.WriteString(choice.Delta.Content)+ sendEvent(ch, AgentEvent{Type: "content", Token: choice.Delta.Content})}if choice.Delta.ReasoningContent != "" {@@ -569,18 +557,6 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionstream.Close()- // 流结束时冲刷 splitter 残留缓冲(如模型输出了半个标签就中断),避免丢字。- if r, c := splitter.Flush(); r != "" || c != "" {- if c != "" {- contentBuilder.WriteString(c)- sendEvent(ch, AgentEvent{Type: "content", Token: c})- }- if r != "" {- reasoningBuilder.WriteString(r)- sendEvent(ch, AgentEvent{Type: "reasoning", Token: r})- }- }-if len(aggregatedToolCalls) > 0 {filtered := make([]openai.ToolCall, 0, len(aggregatedToolCalls))for _, tc := range aggregatedToolCalls {@@ -849,9 +825,7 @@ func GenerateTitle(client *openai.Client, model string, userMsg string, language}return userMsg}- // 部分模型(MINIMAX 等)在非流式响应中也会把推理内容以 <think>...</think> 标签- // 混在 content 中返回,剥离后再用作标题,避免标题以 <think> 开头。- title := strings.TrimSpace(stripThinkTags(resp.Choices[0].Message.Content))+ title := strings.TrimSpace(resp.Choices[0].Message.Content)if title == "" {runes := []rune(userMsg)if len(runes) > 30 {diff --git a/kernel/agent/think_splitter.go b/kernel/agent/think_splitter.godeleted file mode 100644index 75cb8a5476..0000000000--- a/kernel/agent/think_splitter.go+++ /dev/null@@ -1,146 +0,0 @@-// SiYuan - Refactor your thinking-// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--package agent--import "strings"--// thinkOpenTag / thinkCloseTag 是部分模型(MINIMAX、DeepSeek-V3、Qwen3、GLM 等)-// 用来包裹推理内容的文本标签。这些模型把推理内容混在 delta.content 中返回,-// 而非放进 OpenAI 约定的 reasoning_content 字段,导致 <think> 文本泄露进对话正文。-const (- thinkOpenTag = "<think>"- thinkCloseTag = "</think>"-)--// thinkSplitter 解析流式 delta.content 中的 <think>...</think> 标签,-// 把标签内文本分流为 reasoning、标签外文本才作为 content。-//-// 标签可能跨多个流式 chunk 到达(如 "<thi" + "nk>"),故采用前缀缓冲 + 状态机处理。-// 对不输出 <think> 的模型:每个 delta 走一次扫描后全部归 content,无额外开销。-type thinkSplitter struct {- // inThink 表示当前是否处于 <think> 标签内部。- inThink bool- // pending 缓冲以 '<' 开头但尚无法判定是否为标签的文本:- // 它可能是 <think>/</think> 的不完整前缀,需等后续 chunk 拼接后才能确定。- pending strings.Builder-}--func newThinkSplitter() *thinkSplitter {- return &thinkSplitter{}-}--// Feed 处理一个流式 chunk,返回其中应归入 reasoning 与 content 的文本。-// 同一 chunk 可能同时产生两部分(如 "</think>正文" 先结束思考再开始正文)。-func (s *thinkSplitter) Feed(delta string) (reasoning, content string) {- var rBuf, cBuf strings.Builder- // flush 把普通文本按当前状态写入对应缓冲区。- flush := func(text string) {- if text == "" {- return- }- if s.inThink {- rBuf.WriteString(text)- } else {- cBuf.WriteString(text)- }- }-- // 把上一轮残留的 pending 与新 delta 拼接后统一处理。- work := s.pending.String() + delta- s.pending.Reset()-- for len(work) > 0 {- // 块内找闭合标签,块外找开标签。- tag := thinkCloseTag- if !s.inThink {- tag = thinkOpenTag- }-- lt := strings.IndexByte(work, '<')- if lt < 0 {- // 整段无 '<',全是普通文本。- flush(work)- work = ""- break- }- // '<' 之前的内容一定是普通文本,先输出。- if lt > 0 {- flush(work[:lt])- work = work[lt:]- }-- // 此时 work 以 '<' 开头,判断它是否为目标标签。- if strings.HasPrefix(work, tag) {- // 完整命中:切换状态,跳过整个标签。- s.inThink = !s.inThink- work = work[len(tag):]- continue- }- if strings.HasPrefix(tag, work) {- // work 是 tag 的不完整前缀(如 work="<thi"、tag="<think>"),- // 标签可能尚未到齐,暂存待下一个 chunk。- s.pending.WriteString(work)- work = ""- break- }- // work 以 '<' 开头,但既不是 tag 也不是 tag 的前缀,- // 说明这个 '<' 只是普通文本。输出它后继续扫描剩余部分。- flush("<")- work = work[1:]- }-- return rBuf.String(), cBuf.String()-}--// Flush 在流结束时调用,把 pending 中残留的不完整标签缓冲按普通文本冲出,避免丢字。-// 典型场景:模型输出了半个标签(如孤立的 "<thi")就中断,或思考块未闭合。-func (s *thinkSplitter) Flush() (reasoning, content string) {- leftover := s.pending.String()- s.pending.Reset()- if leftover == "" {- return "", ""- }- if s.inThink {- return leftover, ""- }- return "", leftover-}--// stripThinkTags 从一段完整文本中移除所有 <think>...</think> 块,返回剩余正文。-// 用于非流式场景(如标题生成):一次性拿到完整 content 后剥离思考内容。-// 未闭合的 <think>(只有开标签)其后内容视为思考、整体移除;多个 think 块都会被处理。-func stripThinkTags(s string) string {- var b strings.Builder- for {- open := strings.Index(s, thinkOpenTag)- if open < 0 {- // 没有更多 think 块,剩余全部是正文。- b.WriteString(s)- return b.String()- }- // 开标签之前是正文,先写入。- b.WriteString(s[:open])- rest := s[open+len(thinkOpenTag):]- close := strings.Index(rest, thinkCloseTag)- if close < 0 {- // 未闭合:丢弃剩余思考内容。- return b.String()- }- // 跳过闭标签,继续处理其后的文本(可能还有 think 块)。- s = rest[close+len(thinkCloseTag):]- }-}diff --git a/kernel/agent/think_splitter_test.go b/kernel/agent/think_splitter_test.godeleted file mode 100644index 017f5d35d7..0000000000--- a/kernel/agent/think_splitter_test.go+++ /dev/null@@ -1,226 +0,0 @@-// SiYuan - Refactor your thinking-// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--package agent--import "testing"--// feedAll 依次喂入多段 delta,累积返回 reasoning 与 content。-func feedAll(t *testing.T, deltas []string) (reasoning, content string) {- t.Helper()- s := newThinkSplitter()- var r, c string- for _, d := range deltas {- rr, cc := s.Feed(d)- r += rr- c += cc- }- fr, fc := s.Flush()- return r + fr, c + fc-}--func TestThinkSplitter_NoTags(t *testing.T) {- // 普通模型不带 <think> 标签,应原样作为 content。- r, c := feedAll(t, []string{"你好", "世界"})- if r != "" || c != "你好世界" {- t.Fatalf("expected content=你好世界, got reasoning=%q content=%q", r, c)- }-}--func TestThinkSplitter_TagsInOneChunk(t *testing.T) {- // 单 chunk 内完整出现开闭标签(日志观测到的 MINIMAX 实际形态)。- // 闭合标签后紧跟正文。- r, c := feedAll(t, []string{"<think>思考内容</think>正文"})- if r != "思考内容" {- t.Fatalf("expected reasoning=思考内容, got %q", r)- }- if c != "正文" {- t.Fatalf("expected content=正文, got %q", c)- }-}--func TestThinkSplitter_OpenTagCrossChunk(t *testing.T) {- // <think> 标签跨多个 chunk 拆分。- r, c := feedAll(t, []string{"<thi", "nk>", "思考", "</think>", "正文"})- if r != "思考" {- t.Fatalf("expected reasoning=思考, got %q", r)- }- if c != "正文" {- t.Fatalf("expected content=正文, got %q", c)- }-}--func TestThinkSplitter_CloseTagCrossChunk(t *testing.T) {- // </think> 闭合标签跨 chunk 拆分,且闭合后紧跟正文在同一后续 chunk。- r, c := feedAll(t, []string{"<think>", "思考", "</thi", "nk>正文"})- if r != "思考" {- t.Fatalf("expected reasoning=思考, got %q", r)- }- if c != "正文" {- t.Fatalf("expected content=正文, got %q", c)- }-}--func TestThinkSplitter_RealMinimaxTrace(t *testing.T) {- // 复刻日志中 MINIMAX 的真实输出序列。- deltas := []string{- "<think>The",- " user sent \"测试\" twice.",- " This is a test.",- "</think>\n\n你好!\n\n",- "- 项目一\n",- "- 项目二\n",- }- r, c := feedAll(t, deltas)- wantR := "The user sent \"测试\" twice. This is a test."- if r != wantR {- t.Fatalf("expected reasoning=%q, got %q", wantR, r)- }- // </think> 后的 \n\n 是模型输出的正文一部分,剥离标签只移除 <think>...</think> 本身,- // 不改动标签外的任何字符(包括闭合标签后的换行)。- wantC := "\n\n你好!\n\n- 项目一\n- 项目二\n"- if c != wantC {- t.Fatalf("expected content=%q, got %q", wantC, c)- }-}--func TestThinkSplitter_UnclosedThink(t *testing.T) {- // 只有 <think> 开标签,流结束时未闭合:思考内容全部归 reasoning。- r, c := feedAll(t, []string{"<think>", "只有思考", "没有结束"})- if r != "只有思考没有结束" {- t.Fatalf("expected reasoning=只有思考没有结束, got %q", r)- }- if c != "" {- t.Fatalf("expected empty content, got %q", c)- }-}--func TestThinkSplitter_LoneAngleBracket(t *testing.T) {- // 普通文本里出现的 '<' 不是标签开头,应原样输出。- r, c := feedAll(t, []string{"a < b && b > c", " 后续"})- if r != "" || c != "a < b && b > c 后续" {- t.Fatalf("expected no split, got reasoning=%q content=%q", r, c)- }-}--func TestThinkSplitter_LoneAngleAtChunkEnd(t *testing.T) {- // '<' 出现在 chunk 末尾且不是标签开头,下一 chunk 才能确认。- // 这里 '<' 后跟空格,明确不是 <think> 前缀。- r, c := feedAll(t, []string{"x <", " y"})- if r != "" || c != "x < y" {- t.Fatalf("expected content=x < y, got reasoning=%q content=%q", r, c)- }-}--func TestThinkSplitter_IncompleteTagAtEOF(t *testing.T) {- // 流结束时 pending 里残留 "<thi"(半个标签前缀),应按普通文本冲出,不丢字。- r, c := feedAll(t, []string{"正文", "<thi"})- // "<thi" 不是完整 <think>,Flush 后作为 content。- if r != "" {- t.Fatalf("expected no reasoning, got %q", r)- }- if c != "正文<thi" {- t.Fatalf("expected content=正文<thi, got %q", c)- }-}--func TestThinkSplitter_StreamingEvents(t *testing.T) {- // 验证流式过程中每个 chunk 的分类,确保前端能收到连续的 reasoning/content 事件。- s := newThinkSplitter()-- // chunk 1: <think> 开标签,无文本输出- r, c := s.Feed("<think>")- if r != "" || c != "" {- t.Fatalf("chunk1: expected empty, got r=%q c=%q", r, c)- }- // chunk 2: 思考内容- r, c = s.Feed("思考")- if r != "思考" || c != "" {- t.Fatalf("chunk2: expected r=思考, got r=%q c=%q", r, c)- }- // chunk 3: 闭合 + 正文- r, c = s.Feed("</think>正文")- if r != "" || c != "正文" {- t.Fatalf("chunk3: expected c=正文, got r=%q c=%q", r, c)- }- // chunk 4: 纯正文- r, c = s.Feed("更多")- if r != "" || c != "更多" {- t.Fatalf("chunk4: expected c=更多, got r=%q c=%q", r, c)- }-}--func TestThinkSplitter_MultipleThinkBlocks(t *testing.T) {- // 同一回复中出现多个 <think> 块。- r, c := feedAll(t, []string{- "<think>第一段思考</think>",- "中间正文",- "<think>第二段思考</think>",- "结尾正文",- })- if r != "第一段思考第二段思考" {- t.Fatalf("expected reasoning=第一段思考第二段思考, got %q", r)- }- if c != "中间正文结尾正文" {- t.Fatalf("expected content=中间正文结尾正文, got %q", c)- }-}--func TestStripThinkTags_NoTags(t *testing.T) {- got := stripThinkTags("普通标题")- if got != "普通标题" {- t.Fatalf("expected 普通标题, got %q", got)- }-}--func TestStripThinkTags_TitleWithThink(t *testing.T) {- // 复刻 MINIMAX 标题生成场景:<think> + 实际标题。- got := stripThinkTags("<think>这是一条测试消息,需要生成标题</think>测试消息")- if got != "测试消息" {- t.Fatalf("expected 测试消息, got %q", got)- }-}--func TestStripThinkTags_TitleWithNewlineAfterClose(t *testing.T) {- // 闭合标签后紧跟换行再是标题(常见形态)。- got := stripThinkTags("<think>思考</think>\n\n关于笔记的整理")- if got != "\n\n关于笔记的整理" {- t.Fatalf("expected \\n\\n关于笔记的整理, got %q", got)- }-}--func TestStripThinkTags_Unclosed(t *testing.T) {- // 只有开标签未闭合:其后内容视为思考、整体移除。- got := stripThinkTags("标题前缀<think>未闭合的思考内容")- if got != "标题前缀" {- t.Fatalf("expected 标题前缀, got %q", got)- }-}--func TestStripThinkTags_LoneAngleBracket(t *testing.T) {- // 普通文本里的 '<' 不是 think 标签,应保留原样。- got := stripThinkTags("a < b 的比较")- if got != "a < b 的比较" {- t.Fatalf("expected 原样保留, got %q", got)- }-}--func TestStripThinkTags_MultipleBlocks(t *testing.T) {- got := stripThinkTags("<think>块一</think>A<think>块二</think>B")- if got != "AB" {- t.Fatalf("expected AB, got %q", got)- }-}diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 355b76ce8c..00700b1070 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -85,7 +85,7 @@ func agentChat(c *gin.Context) {c.JSON(http.StatusOK, ret)return}- client := util.NewOpenAIClient(selectedProvider.APIKey, selectedProvider.BaseURL)+ client := util.NewOpenAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name)confirmTimeout := time.Duration(model.Conf.AI.Agent.ConfirmTimeout) * time.Secondif confirmTimeout <= 0 {@@ -267,7 +267,7 @@ func agentChatTitle(c *gin.Context) {c.JSON(http.StatusOK, ret)return}- client := util.NewOpenAIClient(selectedProvider.APIKey, selectedProvider.BaseURL)+ client := util.NewOpenAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name)title := agent.GenerateTitle(client, selectedModel.Name, req.Message, req.Language)ret := gulu.Ret.NewResult()diff --git a/kernel/model/ai.go b/kernel/model/ai.goindex e813c8c665..e962603321 100644--- a/kernel/model/ai.go+++ b/kernel/model/ai.go@@ -107,7 +107,7 @@ func chatGPTComplete(msg string, contextMsgs []string, cloud bool) (ret string,gpt = &CloudGPT{}} else {gpt = &OpenAIGPT{- c: util.NewOpenAIClient(prov.APIKey, prov.BaseURL),+ c: util.NewOpenAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name),m: m,timeout: prov.RequestTimeout,maxCompletionTokens: editing.MaxCompletionTokens,diff --git a/kernel/util/openai.go b/kernel/util/openai.goindex ccceed3f48..40dd14cb76 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -17,7 +17,10 @@package utilimport (+ "bytes""context"+ "encoding/json"+ "io""net/http""strings""sync"@@ -94,6 +97,87 @@ func NewOpenAIClient(apiKey, apiBaseURL string) *openai.Client {return openai.NewClientWithConfig(config)}+// builtinExtraBody 是「模型名前缀 → 额外请求参数」的内置适配清单。+// 仅收录参数语义为「纯输出格式开关」的模型(不改变思考行为、无副作用),+// 让这类模型从源头把推理内容拆到 reasoning_content 字段,而非以 <think> 标签混在 content 中。+// 其他模型由 agent.thinkSplitter 兜底解析 <think> 标签。+var builtinExtraBody = map[string]map[string]any{+ // MiniMax:开启 reasoning_split 后,thinking 内容拆到 reasoning_content 字段,+ // 不改变是否思考、无流式要求。覆盖 MiniMax-M* 和 abab* 两个命名族。+ "minimax-m": {"reasoning_split": true},+ "abab-": {"reasoning_split": true},+}++// ExtraBodyForModel 按模型名大小写不敏感匹配内置清单,返回需注入的额外请求参数;无匹配返回 nil。+func ExtraBodyForModel(model string) map[string]any {+ lower := strings.ToLower(model)+ for prefix, extra := range builtinExtraBody {+ if strings.HasPrefix(lower, prefix) {+ return extra+ }+ }+ return nil+}++// extraBodyTransport 包装一个 HTTPDoer,在 chat/completions 请求体中注入额外字段。+// 利用 go-openai 在 client 层暴露的 HTTPDoer 扩展点(Chat 路径不支持 withExtraBody),+// 对流式与非流式 chat 请求都生效;非 chat 请求原样透传。+type extraBodyTransport struct {+ base openai.HTTPDoer+ extraBody map[string]any+}++func (t *extraBodyTransport) Do(req *http.Request) (*http.Response, error) {+ if len(t.extraBody) == 0 || req.Method != http.MethodPost || !strings.Contains(req.URL.Path, "chat/completions") {+ return t.base.Do(req)+ }++ body, err := io.ReadAll(req.Body)+ if err != nil {+ return t.base.Do(req)+ }+ if err = req.Body.Close(); err != nil {+ return t.base.Do(req)+ }++ var payload map[string]any+ if err = json.Unmarshal(body, &payload); err != nil {+ // 请求体解析失败,用原始 body 透传,绝不破坏请求。+ req.Body = io.NopCloser(bytes.NewReader(body))+ req.ContentLength = int64(len(body))+ return t.base.Do(req)+ }++ for k, v := range t.extraBody {+ payload[k] = v+ }++ merged, err := json.Marshal(payload)+ if err != nil {+ req.Body = io.NopCloser(bytes.NewReader(body))+ req.ContentLength = int64(len(body))+ return t.base.Do(req)+ }++ req.Body = io.NopCloser(bytes.NewReader(merged))+ req.ContentLength = int64(len(merged))+ return t.base.Do(req)+}++// NewOpenAIClientWithModel 创建 OpenAI client,并按模型名匹配内置清单注入额外请求参数。+// 绝大多数模型无匹配,走 NewOpenAIClient 老路径(不包中间件,零开销);+// 命中清单的模型(如 MiniMax)会注入厂商专属参数(如 reasoning_split)。+func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string) *openai.Client {+ extra := ExtraBodyForModel(model)+ if len(extra) == 0 {+ return NewOpenAIClient(apiKey, apiBaseURL)+ }+ config := openai.DefaultConfig(apiKey)+ config.BaseURL = apiBaseURL+ config.HTTPClient = &extraBodyTransport{base: &http.Client{}, extraBody: extra}+ return openai.NewClientWithConfig(config)+}+// TestModel 测试模型可用性。优先调用 ListModels(GET /v1/models)拉取可用模型清单,// 校验 model 是否在其中;若该端点不可用(部分 OpenAI 兼容服务未实现),则回退到极简 Chat Completion。// 返回值:available 为可用模型清单(仅 ListModels 成功时填充),matched 表示 model 是否可用,diff --git a/kernel/util/openai_extra_test.go b/kernel/util/openai_extra_test.gonew file mode 100644index 0000000000..4753ae19cb--- /dev/null+++ b/kernel/util/openai_extra_test.go@@ -0,0 +1,184 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestExtraBodyForModel(t *testing.T) {+ cases := []struct {+ model string+ want map[string]any+ }{+ {"MiniMax-M3", map[string]any{"reasoning_split": true}},+ {"minimax-m1", map[string]any{"reasoning_split": true}},+ {"MINIMAX-M3", map[string]any{"reasoning_split": true}}, // 大小写不敏感+ {"abab-6.5-chat", map[string]any{"reasoning_split": true}},+ {"ABAB-7", map[string]any{"reasoning_split": true}},+ {"gpt-4o", nil},+ {"deepseek-chat", nil},+ {"claude-3.5-sonnet", nil},+ {"qwen-max", nil},+ {"", nil},+ }+ for _, tc := range cases {+ got := ExtraBodyForModel(tc.model)+ if !extraEqual(got, tc.want) {+ t.Errorf("ExtraBodyForModel(%q) = %v, want %v", tc.model, got, tc.want)+ }+ }+}++func extraEqual(a, b map[string]any) bool {+ if len(a) != len(b) {+ return false+ }+ for k, v := range a {+ if b[k] != v {+ return false+ }+ }+ return true+}++func TestExtraBodyTransport_ChatPostMerged(t *testing.T) {+ // 拦截 chat/completions POST 请求,验证 extraBody 字段被合并进请求体。+ var captured map[string]any+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ _ = json.Unmarshal(body, &captured)+ w.Header().Set("Content-Type", "application/json")+ // 返回一个合法的最小 chat completion 响应。+ w.Write([]byte(`{"id":"1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`))+ }))+ defer server.Close()++ transport := &extraBodyTransport{+ base: server.Client(),+ extraBody: map[string]any{"reasoning_split": true},+ }++ body := `{"model":"minimax-m3","messages":[{"role":"user","content":"hi"}]}`+ req, _ := http.NewRequest(http.MethodPost, server.URL+"/v1/chat/completions", strings.NewReader(body))+ resp, err := transport.Do(req)+ if err != nil {+ t.Fatalf("Do failed: %v", err)+ }+ defer resp.Body.Close()++ if captured["reasoning_split"] != true {+ t.Fatalf("expected reasoning_split=true in merged body, got %v", captured["reasoning_split"])+ }+ if captured["model"] != "minimax-m3" {+ t.Fatalf("expected model preserved, got %v", captured["model"])+ }+}++func TestExtraBodyTransport_NonChatPassthrough(t *testing.T) {+ // 非 chat 请求(如 GET /v1/models)应原样透传,不注入任何字段。+ var receivedBody []byte+ var method string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ method = r.Method+ receivedBody, _ = io.ReadAll(r.Body)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"data":[{"id":"gpt-4o"}]}`))+ }))+ defer server.Close()++ transport := &extraBodyTransport{+ base: server.Client(),+ extraBody: map[string]any{"reasoning_split": true},+ }++ origBody := `{"hello":"world"}`+ req, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/models", strings.NewReader(origBody))+ resp, err := transport.Do(req)+ if err != nil {+ t.Fatalf("Do failed: %v", err)+ }+ defer resp.Body.Close()++ if method != http.MethodGet {+ t.Fatalf("expected GET passthrough, got %s", method)+ }+ if string(receivedBody) != origBody {+ t.Fatalf("non-chat body should pass through unchanged, got %q", string(receivedBody))+ }+}++func TestExtraBodyTransport_InvalidJSONPassthrough(t *testing.T) {+ // 请求体不是合法 JSON 时,应原样透传原始 body,不破坏请求。+ var receivedBody []byte+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ receivedBody, _ = io.ReadAll(r.Body)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{}`))+ }))+ defer server.Close()++ transport := &extraBodyTransport{+ base: server.Client(),+ extraBody: map[string]any{"reasoning_split": true},+ }++ origBody := `not-valid-json`+ req, _ := http.NewRequest(http.MethodPost, server.URL+"/v1/chat/completions", strings.NewReader(origBody))+ resp, err := transport.Do(req)+ if err != nil {+ t.Fatalf("Do failed: %v", err)+ }+ defer resp.Body.Close()++ if string(receivedBody) != origBody {+ t.Fatalf("invalid JSON body should pass through unchanged, got %q want %q", string(receivedBody), origBody)+ }+}++func TestExtraBodyTransport_EmptyExtraPassthrough(t *testing.T) {+ // extraBody 为空时,即便是 chat POST 也应原样透传(不经过合并逻辑)。+ var receivedBody []byte+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ receivedBody, _ = io.ReadAll(r.Body)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{}`))+ }))+ defer server.Close()++ transport := &extraBodyTransport{+ base: server.Client(),+ extraBody: nil,+ }++ origBody := `{"model":"gpt-4o"}`+ req, _ := http.NewRequest(http.MethodPost, server.URL+"/v1/chat/completions", strings.NewReader(origBody))+ resp, err := transport.Do(req)+ if err != nil {+ t.Fatalf("Do failed: %v", err)+ }+ defer resp.Body.Close()++ if string(receivedBody) != origBody {+ t.Fatalf("empty extraBody should pass through unchanged, got %q", string(receivedBody))+ }+}