An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Show Gemini thought summaries and preserve parallel tool calls https://github.com/siyuan-note/siyuan/issues/18817
Daniel99b1c469edc2
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex bfae493a72..5db125db43 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -917,7 +917,8 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag}}stream, firstResp, roundCancel, requestMessages, imageDowngraded, imageUnsupportedDetected, streamErr :=- createProtocolImageCompatibleStream(ctx, client, protocol, req, responseInput, imageCapabilityKey,+ createProtocolImageCompatibleStream(util.ContextWithGeminiThoughtSummaries(ctx), client, protocol, req,+ responseInput, imageCapabilityKey,imageInputDisabled, maxRetries, requestTimeout, streamIdleTimeout, delayForCategory, ch)if imageUnsupportedDetected {imageInputDisabled = true@@ -956,9 +957,50 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagvar contentBuilder strings.Buildervar reasoningBuilder strings.Builder- var aggregatedToolCalls []openai.ToolCall+ var toolCallAccumulator toolCallStreamAccumulatorresponseOutputTokens := 0lastDraftCheckpoint := time.Now()+ var reasoningSplitter reasoningTagSplitter+ splitTaggedReasoning := thoughtSignatureState.TaggedSummariesAvailable()+ writeContent := func(token string) {+ if token == "" {+ return+ }+ contentBuilder.WriteString(token)+ sendEvent(ch, AgentEvent{Type: "content", Token: token})+ }+ writeReasoning := func(token string) {+ if token == "" {+ return+ }+ reasoningBuilder.WriteString(token)+ sendEvent(ch, AgentEvent{Type: "reasoning", Token: token})+ }+ writeTaggedContent := func(token string) {+ if !splitTaggedReasoning {+ writeContent(token)+ return+ }+ for _, segment := range reasoningSplitter.Write(token) {+ if segment.reasoning {+ writeReasoning(segment.text)+ } else {+ writeContent(segment.text)+ }+ }+ }+ flushTaggedContent := func() {+ if !splitTaggedReasoning {+ return+ }+ for _, segment := range reasoningSplitter.Flush() {+ if segment.reasoning {+ writeReasoning(segment.text)+ } else {+ writeContent(segment.text)+ }+ }+ }firstResponsePending := truefor {@@ -970,6 +1012,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagresp, recvErr = recvStreamWithIdleTimeout(stream, streamIdleTimeout, roundCancel)}if recvErr != nil {+ flushTaggedContent()if recvErr == io.EOF {break}@@ -996,6 +1039,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagselect {case <-ctx.Done():+ flushTaggedContent()turn.DraftContent = contentBuilder.String()turn.DraftRoundID = roundIDsaveTurn("interrupted")@@ -1007,34 +1051,14 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagfor _, choice := range resp.Choices {if choice.Delta.Content != "" {- contentBuilder.WriteString(choice.Delta.Content)- sendEvent(ch, AgentEvent{Type: "content", Token: choice.Delta.Content})+ writeTaggedContent(choice.Delta.Content)}if choice.Delta.ReasoningContent != "" {- reasoningBuilder.WriteString(choice.Delta.ReasoningContent)- sendEvent(ch, AgentEvent{Type: "reasoning", Token: choice.Delta.ReasoningContent})+ writeReasoning(choice.Delta.ReasoningContent)}- for _, tcd := range choice.Delta.ToolCalls {- idx := 0- if tcd.Index != nil {- idx = *tcd.Index- }- for len(aggregatedToolCalls) <= idx {- aggregatedToolCalls = append(aggregatedToolCalls, openai.ToolCall{})- }- if tcd.ID != "" {- aggregatedToolCalls[idx].ID = tcd.ID- }- if tcd.Type != "" {- aggregatedToolCalls[idx].Type = tcd.Type- }- if tcd.Function.Name != "" {- aggregatedToolCalls[idx].Function.Name = tcd.Function.Name- }- aggregatedToolCalls[idx].Function.Arguments += tcd.Function.Arguments- }+ toolCallAccumulator.Add(choice.Delta.ToolCalls)}if contentBuilder.Len() > 0 && time.Since(lastDraftCheckpoint) >= time.Second {turn.DraftContent = contentBuilder.String()@@ -1066,6 +1090,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagturn.DraftContent = ""turn.DraftRoundID = ""+ aggregatedToolCalls := toolCallAccumulator.ToolCalls()if len(aggregatedToolCalls) > 0 {filtered := make([]openai.ToolCall, 0, len(aggregatedToolCalls))for _, tc := range aggregatedToolCalls {diff --git a/kernel/agent/assistant_context_test.go b/kernel/agent/assistant_context_test.goindex 9ef5ad35a3..3adc34ac48 100644--- a/kernel/agent/assistant_context_test.go+++ b/kernel/agent/assistant_context_test.go@@ -326,6 +326,7 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {thoughtSignature = "gemini-thought-signature"argumentsJSON = "{\n \"action\": \"list\",\n \"limit\": 9007199254740993\n}"toolReasoning = "I need to call the test tool."+ taggedToolReasoning = "<thought>" + toolReasoning + "</thought>"firstFinalReasoning = "The tool result is sufficient."secondFinalReasoning = "I can answer from the restored context.")@@ -380,8 +381,8 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {case 1:flusher := prepareTestStream(t, w)chunk := fmt.Sprintf(- `data: {"id":"chatcmpl-tool","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"reasoning_content":%q,"tool_calls":[{"index":0,"id":%q,"function":{"name":%q,"arguments":%q},"extra_content":{"google":{"thought_signature":%q}}}]},"finish_reason":"tool_calls"}]}`+"\n\n",- toolReasoning, toolCallID, toolName, argumentsJSON, thoughtSignature,+ `data: {"id":"chatcmpl-tool","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"content":%q,"tool_calls":[{"index":0,"id":%q,"function":{"name":%q,"arguments":%q},"extra_content":{"google":{"thought_signature":%q}}}]},"finish_reason":"tool_calls"}]}`+"\n\n",+ taggedToolReasoning, toolCallID, toolName, argumentsJSON, thoughtSignature,)if _, err = io.WriteString(w, chunk); err != nil {t.Errorf("write tool response failed: %v", err)@@ -407,7 +408,7 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {firstTurnID := ""events := AgentChat(- context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "test-model", "", 0,+ context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "models/gemini-3.5-flash", "", 0,testSessionID, "user-1", 1,"use the tool", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,)@@ -452,7 +453,7 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {}events = AgentChat(- context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "test-model", "", 0,+ context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "models/gemini-3.5-flash", "", 0,testSessionID, "user-2", 3,"continue", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,)@@ -525,7 +526,7 @@ func assertRestoredAssistantContext(continue}if len(message.ToolCalls) == 1 && message.ToolCalls[0].Function.Name == toolName {- toolAssistantFound = message.ReasoningContent == toolReasoning &&+ toolAssistantFound = message.Content == "" && message.ReasoningContent == toolReasoning &&message.ToolCalls[0].ID == toolCallID &&message.ToolCalls[0].Function.Arguments == argumentsJSON}diff --git a/kernel/agent/gemini_parallel_tools_test.go b/kernel/agent/gemini_parallel_tools_test.gonew file mode 100644index 0000000000..9218243c21--- /dev/null+++ b/kernel/agent/gemini_parallel_tools_test.go@@ -0,0 +1,186 @@+// SiYuan - From thought to insight, with agents+// 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 (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+ "time"++ kernelConf "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"+)++const testGeminiThoughtSignatureFallback = "skip_thought_signature_validator"++func TestAgentChatPreservesUnindexedParallelGeminiToolCalls(t *testing.T) {+ useTestDataDir(t)+ originalConf := kernelModel.Conf+ kernelModel.Conf = kernelModel.NewAppConf()+ kernelModel.Conf.AI = kernelConf.NewAI()+ kernelModel.Conf.AI.MCP = nil+ kernelModel.Conf.AI.Agent.MaxToolCallRounds = 1+ kernelModel.Conf.Variables = kernelConf.NewVariables()+ t.Cleanup(func() { kernelModel.Conf = originalConf })++ const (+ toolName = "test_gemini_parallel_context"+ firstCallID = "call-first"+ secondCallID = "call-second"+ thoughtSignature = "gemini-parallel-signature"+ firstArguments = `{"value":"first"}`+ secondArguments = `{"value":"second"}`+ )+ var executed atomic.Int32+ tools.SetTool(toolName, &tools.Tool{+ Name: toolName,+ Source: "native",+ ReadOnlyHint: true,+ InputSchema: tools.ToolSchema{+ Type: "object",+ Properties: map[string]tools.Property{+ "value": {Type: "string"},+ },+ Required: []string{"value"},+ },+ ActionEffects: map[string]tools.ToolEffects{+ "": {LocalRead: true},+ },+ Handler: func(args map[string]any) (tools.CallToolResult, error) {+ value, _ := args["value"].(string)+ if value != "first" && value != "second" {+ t.Errorf("unexpected tool value: %q", value)+ }+ executed.Add(1)+ return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: "ok"}}}, nil+ },+ })+ t.Cleanup(func() { tools.RemoveTool(toolName) })++ session := map[string]any{+ "id": testSessionID,+ "title": "parallel Gemini tools test",+ "createdAt": int64(1),+ "updatedAt": int64(1),+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use both tools"}},+ }+ if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)+ }++ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ attempt := requests.Add(1)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Errorf("read request failed: %v", err)+ return+ }+ switch attempt {+ case 1:+ flusher := prepareTestStream(t, w)+ chunk := fmt.Sprintf(+ `data: {"id":"chatcmpl-tools","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"tool_calls":[{"id":%q,"type":"function","function":{"name":%q,"arguments":%q},"extra_content":{"google":{"thought_signature":%q}}},{"id":%q,"type":"function","function":{"name":%q,"arguments":%q}}]},"finish_reason":"tool_calls"}]}`+"\n\n",+ firstCallID, toolName, firstArguments, thoughtSignature,+ secondCallID, toolName, secondArguments,+ )+ if _, err = io.WriteString(w, chunk); err != nil {+ t.Errorf("write tool response failed: %v", err)+ return+ }+ flusher.Flush()+ writeTestStreamDone(t, w, flusher)+ case 2:+ assertParallelGeminiToolHistory(t, body, toolName, firstCallID, secondCallID,+ firstArguments, secondArguments, thoughtSignature)+ writeAssistantContextStream(t, w, "", "done")+ default:+ t.Errorf("unexpected request attempt: %d", attempt)+ }+ }))+ defer server.Close()++ events := AgentChat(+ context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "models/gemini-3.7-flash", "", 0,+ testSessionID, "user-1", 1,+ "use both tools", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,+ )+ for event := range events {+ if event.Type == "error" {+ t.Fatalf("agent turn failed: %s", event.Error)+ }+ }+ if requests.Load() != 2 || executed.Load() != 2 {+ t.Fatalf("unexpected request or execution count: requests=%d, executed=%d", requests.Load(), executed.Load())+ }+}++func assertParallelGeminiToolHistory(t *testing.T, body []byte, toolName, firstCallID, secondCallID,+ firstArguments, secondArguments, thoughtSignature string) {+ t.Helper()+ var payload map[string]any+ if err := json.Unmarshal(body, &payload); err != nil {+ t.Fatal(err)+ }+ messages, _ := payload["messages"].([]any)+ wantArguments := map[string]string{firstCallID: firstArguments, secondCallID: secondArguments}+ wantSignatures := map[string]string{+ firstCallID: thoughtSignature,+ secondCallID: testGeminiThoughtSignatureFallback,+ }+ foundCalls := map[string]bool{}+ foundResults := map[string]bool{}+ for _, rawMessage := range messages {+ message, _ := rawMessage.(map[string]any)+ if message["role"] == "assistant" {+ toolCalls, _ := message["tool_calls"].([]any)+ for _, rawToolCall := range toolCalls {+ toolCall, _ := rawToolCall.(map[string]any)+ callID, _ := toolCall["id"].(string)+ function, _ := toolCall["function"].(map[string]any)+ if _, ok := wantArguments[callID]; !ok || function["name"] != toolName {+ continue+ }+ if function["arguments"] != wantArguments[callID] {+ t.Errorf("unexpected arguments for %s: %v", callID, function["arguments"])+ }+ if signature := geminiThoughtSignatureForTest(toolCall); signature != wantSignatures[callID] {+ t.Errorf("unexpected signature for %s: %q", callID, signature)+ }+ foundCalls[callID] = true+ }+ }+ if message["role"] == "tool" {+ callID, _ := message["tool_call_id"].(string)+ if _, ok := wantArguments[callID]; ok {+ foundResults[callID] = true+ }+ }+ }+ for callID := range wantArguments {+ if !foundCalls[callID] || !foundResults[callID] {+ t.Errorf("parallel tool history is incomplete for %s", callID)+ }+ }+}diff --git a/kernel/agent/reasoning_tags.go b/kernel/agent/reasoning_tags.gonew file mode 100644index 0000000000..8a0b723841--- /dev/null+++ b/kernel/agent/reasoning_tags.go@@ -0,0 +1,134 @@+// SiYuan - From thought to insight, with agents+// 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"++type reasoningTagSegment struct {+ text string+ reasoning bool+}++type reasoningTagSplitter struct {+ buffer string+ closingTag string+}++var reasoningOpeningTags = []struct {+ open string+ close string+}{+ {open: "<thought>", close: "</thought>"},+ {open: "<think>", close: "</think>"},+}++func (s *reasoningTagSplitter) Write(text string) []reasoningTagSegment {+ s.buffer += text+ return s.drain(false)+}++func (s *reasoningTagSplitter) Flush() []reasoningTagSegment {+ return s.drain(true)+}++func (s *reasoningTagSplitter) drain(flush bool) (segments []reasoningTagSegment) {+ for s.buffer != "" {+ if s.closingTag != "" {+ if index := strings.Index(s.buffer, s.closingTag); index >= 0 {+ segments = appendReasoningTagSegment(segments, s.buffer[:index], true)+ s.buffer = s.buffer[index+len(s.closingTag):]+ s.closingTag = ""+ continue+ }+ keep := 0+ if !flush {+ keep = longestReasoningTagPrefixSuffix(s.buffer, []string{s.closingTag})+ }+ segments = appendReasoningTagSegment(segments, s.buffer[:len(s.buffer)-keep], true)+ s.buffer = s.buffer[len(s.buffer)-keep:]+ break+ }++ index, closingTag := findReasoningOpeningTag(s.buffer)+ if index >= 0 {+ segments = appendReasoningTagSegment(segments, s.buffer[:index], false)+ openingLength := len(reasoningOpeningTagForClose(closingTag))+ s.buffer = s.buffer[index+openingLength:]+ s.closingTag = closingTag+ continue+ }++ keep := 0+ if !flush {+ openingTags := make([]string, 0, len(reasoningOpeningTags))+ for _, tag := range reasoningOpeningTags {+ openingTags = append(openingTags, tag.open)+ }+ keep = longestReasoningTagPrefixSuffix(s.buffer, openingTags)+ }+ segments = appendReasoningTagSegment(segments, s.buffer[:len(s.buffer)-keep], false)+ s.buffer = s.buffer[len(s.buffer)-keep:]+ break+ }+ return+}++func findReasoningOpeningTag(text string) (index int, closingTag string) {+ index = -1+ for _, tag := range reasoningOpeningTags {+ candidate := strings.Index(text, tag.open)+ if candidate >= 0 && (index < 0 || candidate < index) {+ index = candidate+ closingTag = tag.close+ }+ }+ return+}++func reasoningOpeningTagForClose(closingTag string) string {+ for _, tag := range reasoningOpeningTags {+ if tag.close == closingTag {+ return tag.open+ }+ }+ return ""+}++func longestReasoningTagPrefixSuffix(text string, tags []string) int {+ longest := 0+ for _, tag := range tags {+ limit := min(len(text), len(tag)-1)+ for length := limit; length > longest; length-- {+ if strings.HasSuffix(text, tag[:length]) {+ longest = length+ break+ }+ }+ }+ return longest+}++func appendReasoningTagSegment(segments []reasoningTagSegment, text string, reasoning bool) []reasoningTagSegment {+ if text == "" {+ return segments+ }+ if len(segments) > 0 && segments[len(segments)-1].reasoning == reasoning {+ segments[len(segments)-1].text += text+ return segments+ }+ return append(segments, reasoningTagSegment{text: text, reasoning: reasoning})+}diff --git a/kernel/agent/reasoning_tags_test.go b/kernel/agent/reasoning_tags_test.gonew file mode 100644index 0000000000..fa49c6876a--- /dev/null+++ b/kernel/agent/reasoning_tags_test.go@@ -0,0 +1,73 @@+// SiYuan - From thought to insight, with agents+// 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"++func TestReasoningTagSplitter(t *testing.T) {+ tests := []struct {+ name string+ chunks []string+ wantContent string+ wantReasoning string+ }{+ {+ name: "thought tag split across chunks",+ chunks: []string{"<tho", "ught>reason", "ing</th", "ought>answer"},+ wantContent: "answer",+ wantReasoning: "reasoning",+ },+ {+ name: "think tag with surrounding content",+ chunks: []string{"before<think>inside</think>after"},+ wantContent: "beforeafter",+ wantReasoning: "inside",+ },+ {+ name: "ordinary content",+ chunks: []string{"plain < text", " remains unchanged"},+ wantContent: "plain < text remains unchanged",+ },+ {+ name: "incomplete tag is flushed",+ chunks: []string{"answer<th"},+ wantContent: "answer<th",+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ var splitter reasoningTagSplitter+ var content, reasoning string+ consume := func(segments []reasoningTagSegment) {+ for _, segment := range segments {+ if segment.reasoning {+ reasoning += segment.text+ } else {+ content += segment.text+ }+ }+ }+ for _, chunk := range test.chunks {+ consume(splitter.Write(chunk))+ }+ consume(splitter.Flush())+ if content != test.wantContent || reasoning != test.wantReasoning {+ t.Fatalf("content = %q, reasoning = %q", content, reasoning)+ }+ })+ }+}diff --git a/kernel/agent/tool_call_stream.go b/kernel/agent/tool_call_stream.gonew file mode 100644index 0000000000..4ab28a461e--- /dev/null+++ b/kernel/agent/tool_call_stream.go@@ -0,0 +1,108 @@+// SiYuan - From thought to insight, with agents+// 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 (+ "encoding/json"+ "strings"++ "github.com/sashabaranov/go-openai"+)++// toolCallStreamAccumulator 兼容省略 index 的流式工具调用,并按调用 ID 保持多个并行调用相互独立。+type toolCallStreamAccumulator struct {+ calls []openai.ToolCall+ indexByID map[string]int+}++func (a *toolCallStreamAccumulator) Add(deltas []openai.ToolCall) {+ for position, delta := range deltas {+ index := a.resolveIndex(delta, position, len(deltas))+ for len(a.calls) <= index {+ a.calls = append(a.calls, openai.ToolCall{})+ }++ call := &a.calls[index]+ if delta.ID != "" {+ call.ID = delta.ID+ if a.indexByID == nil {+ a.indexByID = map[string]int{}+ }+ a.indexByID[delta.ID] = index+ }+ if delta.Type != "" {+ call.Type = delta.Type+ }+ if delta.Function.Name != "" {+ call.Function.Name = delta.Function.Name+ }+ call.Function.Arguments = mergeStreamedToolCallArguments(call.Function.Arguments, delta.Function.Arguments)+ }+}++func (a *toolCallStreamAccumulator) ToolCalls() []openai.ToolCall {+ return a.calls+}++func (a *toolCallStreamAccumulator) resolveIndex(delta openai.ToolCall, position, batchSize int) int {+ if delta.Index != nil && *delta.Index >= 0 {+ return *delta.Index+ }+ if delta.ID != "" {+ if index, ok := a.indexByID[delta.ID]; ok {+ return index+ }+ if batchSize > 1 && position < len(a.calls) {+ existingID := a.calls[position].ID+ if existingID == "" || existingID == delta.ID {+ return position+ }+ }+ if len(a.calls) == 0 {+ return 0+ }+ return len(a.calls)+ }+ if batchSize > 1 {+ return position+ }+ return 0+}++func mergeStreamedToolCallArguments(existing, fragment string) string {+ if fragment == "" {+ return existing+ }+ if existing == "" {+ return fragment+ }+ if strings.HasPrefix(fragment, existing) {+ return fragment+ }+ if strings.HasPrefix(existing, fragment) {+ return existing+ }+ if isCompleteToolCallArguments(existing) && isCompleteToolCallArguments(fragment) {+ return fragment+ }+ return existing + fragment+}++func isCompleteToolCallArguments(value string) bool {+ var object map[string]any+ return json.Unmarshal([]byte(value), &object) == nil && object != nil+}diff --git a/kernel/agent/tool_call_stream_test.go b/kernel/agent/tool_call_stream_test.gonew file mode 100644index 0000000000..f2f4107020--- /dev/null+++ b/kernel/agent/tool_call_stream_test.go@@ -0,0 +1,114 @@+// SiYuan - From thought to insight, with agents+// 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"++ "github.com/sashabaranov/go-openai"+)++func TestToolCallStreamAccumulatorIndexedFragments(t *testing.T) {+ index := 0+ var accumulator toolCallStreamAccumulator+ accumulator.Add([]openai.ToolCall{{+ Index: &index,+ ID: "call-1",+ Type: openai.ToolTypeFunction,+ Function: openai.FunctionCall{+ Name: "notebook",+ Arguments: `{"action":`,+ },+ }})+ accumulator.Add([]openai.ToolCall{{+ Index: &index,+ Function: openai.FunctionCall{+ Arguments: `"list"}`,+ },+ }})++ calls := accumulator.ToolCalls()+ if len(calls) != 1 || calls[0].ID != "call-1" || calls[0].Function.Name != "notebook" ||+ calls[0].Function.Arguments != `{"action":"list"}` {+ t.Fatalf("unexpected accumulated tool call: %#v", calls)+ }+}++func TestToolCallStreamAccumulatorParallelCallsWithoutIndexes(t *testing.T) {+ var accumulator toolCallStreamAccumulator+ accumulator.Add([]openai.ToolCall{+ {+ ID: "call-1",+ Function: openai.FunctionCall{+ Name: "notebook",+ Arguments: `{"action":"query"}`,+ },+ },+ {+ ID: "call-2",+ Function: openai.FunctionCall{+ Name: "notebook",+ Arguments: `{"action":"list"}`,+ },+ },+ })++ calls := accumulator.ToolCalls()+ if len(calls) != 2 {+ t.Fatalf("unexpected tool call count: %d", len(calls))+ }+ if calls[0].ID != "call-1" || calls[0].Function.Arguments != `{"action":"query"}` {+ t.Fatalf("unexpected first tool call: %#v", calls[0])+ }+ if calls[1].ID != "call-2" || calls[1].Function.Arguments != `{"action":"list"}` {+ t.Fatalf("unexpected second tool call: %#v", calls[1])+ }+}++func TestToolCallStreamAccumulatorSeparateCallsWithoutIndexes(t *testing.T) {+ var accumulator toolCallStreamAccumulator+ accumulator.Add([]openai.ToolCall{{+ ID: "call-1",+ Function: openai.FunctionCall{Name: "sql", Arguments: `{"stmt":"SELECT 1"}`},+ }})+ accumulator.Add([]openai.ToolCall{{+ ID: "call-2",+ Function: openai.FunctionCall{Name: "notebook", Arguments: `{"action":"list"}`},+ }})++ calls := accumulator.ToolCalls()+ if len(calls) != 2 || calls[0].ID != "call-1" || calls[1].ID != "call-2" {+ t.Fatalf("separate unindexed calls were merged: %#v", calls)+ }+}++func TestToolCallStreamAccumulatorCumulativeArguments(t *testing.T) {+ var accumulator toolCallStreamAccumulator+ accumulator.Add([]openai.ToolCall{{+ ID: "call-1",+ Function: openai.FunctionCall{Name: "notebook", Arguments: `{"action":`},+ }})+ accumulator.Add([]openai.ToolCall{{+ ID: "call-1",+ Function: openai.FunctionCall{Arguments: `{"action":"list"}`},+ }})++ calls := accumulator.ToolCalls()+ if len(calls) != 1 || calls[0].Function.Arguments != `{"action":"list"}` {+ t.Fatalf("cumulative arguments were duplicated: %#v", calls)+ }+}diff --git a/kernel/util/openai_gemini.go b/kernel/util/openai_gemini.goindex 108c2ea852..9a1c69ec67 100644--- a/kernel/util/openai_gemini.go+++ b/kernel/util/openai_gemini.go@@ -37,12 +37,14 @@ const ()type geminiThoughtSignatureContextKey struct{}+type geminiThoughtSummariesContextKey struct{}// GeminiThoughtSignatureState 保存同一次 Agent 请求中的 Gemini 工具调用签名。// 签名是不透明值,只按工具调用 ID 写入和读取,不进行解码或修改。type GeminiThoughtSignatureState struct {- mu sync.RWMutex- signatures map[string]string+ mu sync.RWMutex+ signatures map[string]string+ taggedSummariesAvailable bool}func NewGeminiThoughtSignatureState() *GeminiThoughtSignatureState {@@ -56,6 +58,11 @@ func ContextWithGeminiThoughtSignatureState(ctx context.Context, state *GeminiThreturn context.WithValue(ctx, geminiThoughtSignatureContextKey{}, state)}+// ContextWithGeminiThoughtSummaries 请求 Gemini 返回可展示的思考摘要,仅用于 Agent 主响应。+func ContextWithGeminiThoughtSummaries(ctx context.Context) context.Context {+ return context.WithValue(ctx, geminiThoughtSummariesContextKey{}, true)+}+func (s *GeminiThoughtSignatureState) Set(callID, signature string) {if s == nil || callID == "" || signature == "" {return@@ -78,11 +85,35 @@ func (s *GeminiThoughtSignatureState) Get(callID string) string {return signature}+func (s *GeminiThoughtSignatureState) TaggedSummariesAvailable() bool {+ if s == nil {+ return false+ }+ s.mu.RLock()+ available := s.taggedSummariesAvailable+ s.mu.RUnlock()+ return available+}++func (s *GeminiThoughtSignatureState) enableTaggedSummaries() {+ if s == nil {+ return+ }+ s.mu.Lock()+ s.taggedSummariesAvailable = true+ s.mu.Unlock()+}+func geminiThoughtSignatureStateFromContext(ctx context.Context) *GeminiThoughtSignatureState {state, _ := ctx.Value(geminiThoughtSignatureContextKey{}).(*GeminiThoughtSignatureState)return state}+func geminiThoughtSummariesRequested(ctx context.Context) bool {+ requested, _ := ctx.Value(geminiThoughtSummariesContextKey{}).(bool)+ return requested+}+func isGoogleGeminiOpenAICompatibleEndpoint(apiBaseURL, model string) bool {parsed, err := url.Parse(strings.TrimSpace(apiBaseURL))if err != nil || !strings.EqualFold(parsed.Hostname(), "generativelanguage.googleapis.com") {@@ -112,7 +143,7 @@ func (t *geminiThoughtSignatureTransport) Do(req *http.Request) (*http.Response,state := geminiThoughtSignatureStateFromContext(req.Context())isChatRequest := req.Method == http.MethodPost && strings.Contains(req.URL.Path, "chat/completions")if state != nil && isChatRequest {- injectGeminiThoughtSignatures(req, state)+ prepareGeminiChatRequest(req, state, geminiThoughtSummariesRequested(req.Context()))}resp, err := t.base.Do(req)@@ -128,7 +159,7 @@ func (t *geminiThoughtSignatureTransport) Do(req *http.Request) (*http.Response,return resp, nil}-func injectGeminiThoughtSignatures(req *http.Request, state *GeminiThoughtSignatureState) {+func prepareGeminiChatRequest(req *http.Request, state *GeminiThoughtSignatureState, includeThoughtSummaries bool) {if req.Body == nil {return}@@ -148,6 +179,13 @@ func injectGeminiThoughtSignatures(req *http.Request, state *GeminiThoughtSignat}messages, _ := payload["messages"].([]any)changed := false+ if includeThoughtSummaries {+ var summariesConfigured bool+ changed, summariesConfigured = configureGeminiThoughtSummaries(payload)+ if summariesConfigured {+ state.enableTaggedSummaries()+ }+ }for _, rawMessage := range messages {message, _ := rawMessage.(map[string]any)if message["role"] != openai.ChatMessageRoleAssistant {@@ -183,6 +221,72 @@ func injectGeminiThoughtSignatures(req *http.Request, state *GeminiThoughtSignatrestoreOpenAIRequestBody(req, merged)}+func configureGeminiThoughtSummaries(payload map[string]any) (changed, configured bool) {+ model, _ := payload["model"].(string)+ if !isGemini3Model(model) {+ return false, false+ }++ reasoningEffort, _ := payload["reasoning_effort"].(string)+ thinkingLevel, supported := geminiThinkingLevel(reasoningEffort)+ if reasoningEffort != "" && !supported {+ return false, false+ }++ extraBody := ensureGeminiJSONMap(payload, "extra_body")+ google := ensureGeminiJSONMap(extraBody, "google")+ thinkingConfig := ensureGeminiJSONMap(google, "thinking_config")+ if includeThoughts, _ := thinkingConfig["include_thoughts"].(bool); !includeThoughts {+ thinkingConfig["include_thoughts"] = true+ changed = true+ }+ if reasoningEffort != "" {+ delete(payload, "reasoning_effort")+ changed = true+ if _, hasLevel := thinkingConfig["thinking_level"]; !hasLevel {+ if _, hasBudget := thinkingConfig["thinking_budget"]; !hasBudget {+ thinkingConfig["thinking_level"] = thinkingLevel+ changed = true+ }+ }+ }+ return changed, true+}++func ensureGeminiJSONMap(parent map[string]any, key string) map[string]any {+ child, _ := parent[key].(map[string]any)+ if child == nil {+ child = map[string]any{}+ parent[key] = child+ }+ return child+}++func isGemini3Model(model string) bool {+ normalized := strings.ToLower(strings.TrimSpace(model))+ if slash := strings.LastIndex(normalized, "/"); slash >= 0 {+ normalized = normalized[slash+1:]+ }+ return strings.HasPrefix(normalized, "gemini-3")+}++func geminiThinkingLevel(reasoningEffort string) (string, bool) {+ normalized := strings.ToLower(strings.TrimSpace(reasoningEffort))+ switch normalized {+ case "":+ return "", true+ case "none":+ // Gemini 3 无法关闭思考,使用所有 Gemini 3 模型均支持的最低档位。+ return "low", true+ case "low", "medium", "high":+ return normalized, true+ case "xhigh", "max":+ return "high", true+ default:+ return "", false+ }+}+func isGeminiFunctionToolCall(toolCall map[string]any) bool {toolType, _ := toolCall["type"].(string)if toolType != "" && toolType != string(openai.ToolTypeFunction) {diff --git a/kernel/util/openai_gemini_test.go b/kernel/util/openai_gemini_test.goindex 488c68c3a7..3f4cf4323f 100644--- a/kernel/util/openai_gemini_test.go+++ b/kernel/util/openai_gemini_test.go@@ -48,6 +48,50 @@ func TestIsGoogleGeminiOpenAICompatibleEndpoint(t *testing.T) {}}+func TestGeminiThinkingLevel(t *testing.T) {+ tests := []struct {+ effort string+ level string+ ok bool+ }{+ {"", "", true},+ {"none", "low", true},+ {"low", "low", true},+ {"medium", "medium", true},+ {"high", "high", true},+ {"xhigh", "high", true},+ {"max", "high", true},+ {"unsupported", "", false},+ }+ for _, test := range tests {+ level, ok := geminiThinkingLevel(test.effort)+ if level != test.level || ok != test.ok {+ t.Errorf("geminiThinkingLevel(%q) = %q, %v", test.effort, level, ok)+ }+ }+}++func TestConfigureGeminiThoughtSummariesScope(t *testing.T) {+ gemini3 := map[string]any{"model": "models/gemini-3.5-flash"}+ changed, configured := configureGeminiThoughtSummaries(gemini3)+ if !changed || !configured {+ t.Fatal("Gemini 3 thought summaries were not configured")+ }+ thinkingConfig := gemini3["extra_body"].(map[string]any)["google"].(map[string]any)["thinking_config"].(map[string]any)+ if thinkingConfig["include_thoughts"] != true {+ t.Fatalf("unexpected Gemini 3 thinking config: %#v", thinkingConfig)+ }+ if _, hasLevel := thinkingConfig["thinking_level"]; hasLevel {+ t.Fatalf("default Gemini thinking level must remain model-defined: %#v", thinkingConfig)+ }++ gemini25 := map[string]any{"model": "models/gemini-2.5-flash", "reasoning_effort": "high"}+ changed, configured = configureGeminiThoughtSummaries(gemini25)+ if changed || configured || gemini25["reasoning_effort"] != "high" {+ t.Fatalf("Gemini 2.5 request was changed: %#v", gemini25)+ }+}+func TestGeminiThoughtSignatureTransportRoundTrip(t *testing.T) {const (existingCallID = "call-existing"@@ -82,7 +126,8 @@ func TestGeminiThoughtSignatureTransportRoundTrip(t *testing.T) {state := NewGeminiThoughtSignatureState()state.Set(existingCallID, existingSignature)ctx := ContextWithGeminiThoughtSignatureState(context.Background(), state)- body := `{"model":"gemini-3.5-flash","messages":[` ++ ctx = ContextWithGeminiThoughtSummaries(ctx)+ body := `{"model":"models/gemini-3.5-flash","reasoning_effort":"high","messages":[` +`{"role":"assistant","tool_calls":[` +`{"id":"` + existingCallID + `","type":"function","function":{"name":"document","arguments":"{}"}},` +`{"id":"` + legacyCallID + `","type":"","function":{"name":"block","arguments":"{}"}}]},` +@@ -113,6 +158,47 @@ func TestGeminiThoughtSignatureTransportRoundTrip(t *testing.T) {if got := state.Get(newCallID); got != newSignature {t.Fatalf("captured thought signature = %q, want %q", got, newSignature)}+ if _, exists := captured["reasoning_effort"]; exists {+ t.Fatal("reasoning_effort must be removed when Gemini thought summaries are enabled")+ }+ extraBody := captured["extra_body"].(map[string]any)+ google := extraBody["google"].(map[string]any)+ thinkingConfig := google["thinking_config"].(map[string]any)+ if thinkingConfig["include_thoughts"] != true || thinkingConfig["thinking_level"] != "high" {+ t.Fatalf("unexpected Gemini thinking config: %#v", thinkingConfig)+ }+ if !state.TaggedSummariesAvailable() {+ t.Fatal("Gemini tagged thought summaries were not enabled")+ }+}++func TestGeminiThoughtSummariesAreOptIn(t *testing.T) {+ var received []byte+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received, _ = io.ReadAll(r.Body)+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{}`)+ }))+ defer server.Close()++ body := `{"model":"models/gemini-3.5-flash","messages":[{"role":"user","content":"hello"}]}`+ state := NewGeminiThoughtSignatureState()+ ctx := ContextWithGeminiThoughtSignatureState(context.Background(), state)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, server.URL+"/v1/chat/completions", strings.NewReader(body))+ if err != nil {+ t.Fatal(err)+ }+ resp, err := WrapGeminiThoughtSignatureTransport(server.Client()).Do(req)+ if err != nil {+ t.Fatal(err)+ }+ _ = resp.Body.Close()+ if string(received) != body {+ t.Fatalf("request without summary opt-in changed: %s", received)+ }+ if state.TaggedSummariesAvailable() {+ t.Fatal("Gemini tagged thought summaries were enabled without opt-in")+ }}func TestGeminiThoughtSignatureTransportWithoutStatePassesThrough(t *testing.T) {