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
Daniel2aa3f1e0a794
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex f916d3a4c2..b673699171 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -487,6 +487,10 @@ 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()@@ -514,8 +518,16 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionfor _, choice := range resp.Choices {if choice.Delta.Content != "" {- contentBuilder.WriteString(choice.Delta.Content)- sendEvent(ch, AgentEvent{Type: "content", Token: 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})+ }}if choice.Delta.ReasoningContent != "" {@@ -557,6 +569,18 @@ 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 {@@ -825,7 +849,9 @@ func GenerateTitle(client *openai.Client, model string, userMsg string, language}return userMsg}- title := strings.TrimSpace(resp.Choices[0].Message.Content)+ // 部分模型(MINIMAX 等)在非流式响应中也会把推理内容以 <think>...</think> 标签+ // 混在 content 中返回,剥离后再用作标题,避免标题以 <think> 开头。+ title := strings.TrimSpace(stripThinkTags(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.gonew file mode 100644index 0000000000..75cb8a5476--- /dev/null+++ b/kernel/agent/think_splitter.go@@ -0,0 +1,146 @@+// 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.gonew file mode 100644index 0000000000..017f5d35d7--- /dev/null+++ b/kernel/agent/think_splitter_test.go@@ -0,0 +1,226 @@+// 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)+ }+}