Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Preserve Gemini thought signatures in agent tool calls https://github.com/siyuan-note/siyuan/issues/18817

Danield61b6df283b0
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 7c7e39d1d8..b2bab5abfb 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -105,7 +105,12 @@ type SessionEntry =
arguments: Record<string, unknown>;
argumentsJSON?: string;
result?: string;
- state?: string
+ state?: string;
+ providerData?: {
+ google?: {
+ thoughtSignature?: string
+ }
+ }
}>;
timestamp?: number
})
diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.ts
index e270751b79..e732508db7 100644
--- a/app/src/layout/dock/agent/SessionStore.ts
+++ b/app/src/layout/dock/agent/SessionStore.ts
@@ -88,7 +88,12 @@ export interface AgentSession {
arguments?: Record<string, unknown>;
argumentsJSON?: string;
result?: string;
- state?: string
+ state?: string;
+ providerData?: {
+ google?: {
+ thoughtSignature?: string
+ }
+ }
}>;
duration?: number;
timestamp?: number;
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 72ba7f254a..9bba80c332 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -356,13 +356,22 @@ type AgentMessage struct {
}
type AgentToolCall struct {
- ID string `json:"id,omitempty"`
- Name string `json:"name"`
- Arguments map[string]any `json:"arguments"`
- ArgumentsJSON string `json:"argumentsJSON,omitempty"`
- Result string `json:"result,omitempty"`
- State string `json:"state,omitempty"`
- Attachments []AgentAttachment `json:"attachments,omitempty"`
+ ID string `json:"id,omitempty"`
+ Name string `json:"name"`
+ Arguments map[string]any `json:"arguments"`
+ ArgumentsJSON string `json:"argumentsJSON,omitempty"`
+ Result string `json:"result,omitempty"`
+ State string `json:"state,omitempty"`
+ Attachments []AgentAttachment `json:"attachments,omitempty"`
+ ProviderData *AgentToolCallProviderData `json:"providerData,omitempty"`
+}
+
+type AgentToolCallProviderData struct {
+ Google *AgentGoogleToolCallProviderData `json:"google,omitempty"`
+}
+
+type AgentGoogleToolCallProviderData struct {
+ ThoughtSignature string `json:"thoughtSignature,omitempty"`
}
type AgentAttachment struct {
@@ -489,6 +498,8 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag
logging.LogErrorf("agent chat panic: %v\n%s", r, logging.ShortStack())
}
}()
+ thoughtSignatureState := util.NewGeminiThoughtSignatureState()
+ ctx = util.ContextWithGeminiThoughtSignatureState(ctx, thoughtSignatureState)
if kernelModel.Conf.AI.MCP != nil {
mcpclient.EnsureMCPConnected(kernelModel.Conf.AI.MCP.Servers)
@@ -615,6 +626,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag
checkpointMsgs = []AgentMessage{newAgentUserMessage(userMessage, userEntryID, references, editorCtx)}
messages = buildInitialMessages(userMessage, language, references, editorCtx, capabilities)
}
+ restoreGeminiThoughtSignatures(thoughtSignatureState, checkpointMsgs)
turnBaseIndex := len(checkpointMsgs)
turn := &agentRuntimeTurn{
@@ -1088,6 +1100,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag
Arguments: args,
ArgumentsJSON: tc.Function.Arguments,
State: "pending",
+ ProviderData: geminiToolCallProviderData(thoughtSignatureState.Get(tc.ID)),
})
}
checkpointMsgs = append(checkpointMsgs, checkpointMsg)
@@ -2082,6 +2095,26 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {
return msgs
}
+func restoreGeminiThoughtSignatures(state *util.GeminiThoughtSignatureState, messages []AgentMessage) {
+ for _, message := range messages {
+ for _, toolCall := range message.ToolCalls {
+ if toolCall.ProviderData == nil || toolCall.ProviderData.Google == nil {
+ continue
+ }
+ state.Set(toolCall.ID, toolCall.ProviderData.Google.ThoughtSignature)
+ }
+ }
+}
+
+func geminiToolCallProviderData(signature string) *AgentToolCallProviderData {
+ if signature == "" {
+ return nil
+ }
+ return &AgentToolCallProviderData{
+ Google: &AgentGoogleToolCallProviderData{ThoughtSignature: signature},
+ }
+}
+
func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet) []openai.ChatCompletionMessage {
return checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, nil)
}
diff --git a/kernel/agent/assistant_context_test.go b/kernel/agent/assistant_context_test.go
index 65b856959e..0985abf04b 100644
--- a/kernel/agent/assistant_context_test.go
+++ b/kernel/agent/assistant_context_test.go
@@ -24,6 +24,7 @@ import (
kernelConf "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/mcp/tools"
kernelModel "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestResponsesContextPreservesEncryptedReasoningAndToolOutput(t *testing.T) {
@@ -322,6 +323,7 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
const (
toolName = "test_assistant_context"
toolCallID = "call-original"
+ thoughtSignature = "gemini-thought-signature"
argumentsJSON = "{\n \"action\": \"list\",\n \"limit\": 9007199254740993\n}"
toolReasoning = "I need to call the test tool."
firstFinalReasoning = "The tool result is sufficient."
@@ -378,8 +380,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,"type":"function","function":{"name":%q,"arguments":%q}}]},"finish_reason":"tool_calls"}]}`+"\n\n",
- toolReasoning, toolCallID, toolName, argumentsJSON,
+ `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,"type":"function","function":{"name":%q,"arguments":%q},"extra_content":{"google":{"thought_signature":%q}}}]},"finish_reason":"tool_calls"}]}`+"\n\n",
+ toolReasoning, toolCallID, toolName, argumentsJSON, thoughtSignature,
)
if _, err = io.WriteString(w, chunk); err != nil {
t.Errorf("write tool response failed: %v", err)
@@ -388,9 +390,11 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
flusher.Flush()
writeTestStreamDone(t, w, flusher)
case 2:
+ assertGeminiThoughtSignatureInRequest(t, body, toolCallID, thoughtSignature)
assertRestoredAssistantContext(t, request.Messages, toolName, toolCallID, argumentsJSON, toolReasoning, "")
writeAssistantContextStream(t, w, firstFinalReasoning, "first answer")
case 3:
+ assertGeminiThoughtSignatureInRequest(t, body, toolCallID, thoughtSignature)
assertRestoredAssistantContext(
t, request.Messages, toolName, toolCallID, argumentsJSON, toolReasoning, firstFinalReasoning,
)
@@ -403,7 +407,8 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
firstTurnID := ""
events := AgentChat(
- context.Background(), newTestOpenAIClient(server.URL), "openai", "test-model", "", 0, testSessionID, "user-1", 1,
+ context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "test-model", "", 0,
+ testSessionID, "user-1", 1,
"use the tool", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
)
for event := range events {
@@ -428,6 +433,13 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
if err != nil || revision != 2 {
t.Fatalf("commit first agent turn failed: revision=%d, err=%v", revision, err)
}
+ canonicalJSON, err := json.Marshal(canonical)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(canonicalJSON), `"thoughtSignature":"`+thoughtSignature+`"`) {
+ t.Fatalf("thought signature was not persisted: %s", canonicalJSON)
+ }
entries := canonical["entries"].([]any)
canonical["entries"] = append(entries, map[string]any{
@@ -440,7 +452,8 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
}
events = AgentChat(
- context.Background(), newTestOpenAIClient(server.URL), "openai", "test-model", "", 0, testSessionID, "user-2", 3,
+ context.Background(), newTestGeminiOpenAIClient(server.URL), "openai", "test-model", "", 0,
+ testSessionID, "user-2", 3,
"continue", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
)
for event := range events {
@@ -462,6 +475,43 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
}
}
+func newTestGeminiOpenAIClient(serverURL string) *openai.Client {
+ config := openai.DefaultConfig("test-key")
+ config.BaseURL = serverURL + "/v1"
+ config.HTTPClient = util.WrapGeminiThoughtSignatureTransport(http.DefaultClient)
+ return openai.NewClientWithConfig(config)
+}
+
+func assertGeminiThoughtSignatureInRequest(t *testing.T, body []byte, callID, want string) {
+ t.Helper()
+ var payload map[string]any
+ if err := json.Unmarshal(body, &payload); err != nil {
+ t.Fatal(err)
+ }
+ messages, _ := payload["messages"].([]any)
+ for _, rawMessage := range messages {
+ message, _ := rawMessage.(map[string]any)
+ toolCalls, _ := message["tool_calls"].([]any)
+ for _, rawToolCall := range toolCalls {
+ toolCall, _ := rawToolCall.(map[string]any)
+ if toolCall["id"] == callID {
+ if got := geminiThoughtSignatureForTest(toolCall); got != want {
+ t.Fatalf("thought signature = %q, want %q", got, want)
+ }
+ return
+ }
+ }
+ }
+ t.Fatalf("tool call %q was not found in request", callID)
+}
+
+func geminiThoughtSignatureForTest(toolCall map[string]any) string {
+ extraContent, _ := toolCall["extra_content"].(map[string]any)
+ google, _ := extraContent["google"].(map[string]any)
+ signature, _ := google["thought_signature"].(string)
+ return signature
+}
+
func assertRestoredAssistantContext(
t *testing.T,
messages []openai.ChatCompletionMessage,
diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.go
index 82d47cf0b6..d145f24e48 100644
--- a/kernel/agent/prompt_test.go
+++ b/kernel/agent/prompt_test.go
@@ -158,6 +158,9 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {
ArgumentsJSON: argumentsJSON,
Result: "search result",
State: "finished",
+ ProviderData: &AgentToolCallProviderData{
+ Google: &AgentGoogleToolCallProviderData{ThoughtSignature: "thought-signature"},
+ },
}},
}}
@@ -167,9 +170,16 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {
t.Fatalf("assistant reasoning was not restored into checkpoint: %#v", checkpoint)
}
if len(checkpoint[0].ToolCalls) != 1 || checkpoint[0].ToolCalls[0].ID != "call-original" ||
- checkpoint[0].ToolCalls[0].ArgumentsJSON != argumentsJSON {
+ checkpoint[0].ToolCalls[0].ArgumentsJSON != argumentsJSON ||
+ checkpoint[0].ToolCalls[0].ProviderData == nil || checkpoint[0].ToolCalls[0].ProviderData.Google == nil ||
+ checkpoint[0].ToolCalls[0].ProviderData.Google.ThoughtSignature != "thought-signature" {
t.Fatalf("assistant tool call was not restored exactly: %#v", checkpoint[0].ToolCalls)
}
+ state := util.NewGeminiThoughtSignatureState()
+ restoreGeminiThoughtSignatures(state, checkpoint)
+ if got := state.Get("call-original"); got != "thought-signature" {
+ t.Fatalf("thought signature was not restored into request state: %q", got)
+ }
messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)
if len(messages) != 3 {
@@ -189,7 +199,9 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {
if len(roundTripped) != 1 || roundTripped[0].ReasoningCont != entries[0].ReasoningCont ||
roundTripped[0].RoundID != entries[0].RoundID ||
len(roundTripped[0].ToolCalls) != 1 || roundTripped[0].ToolCalls[0].ID != "call-original" ||
- roundTripped[0].ToolCalls[0].ArgumentsJSON != argumentsJSON {
+ roundTripped[0].ToolCalls[0].ArgumentsJSON != argumentsJSON ||
+ roundTripped[0].ToolCalls[0].ProviderData == nil || roundTripped[0].ToolCalls[0].ProviderData.Google == nil ||
+ roundTripped[0].ToolCalls[0].ProviderData.Google.ThoughtSignature != "thought-signature" {
t.Fatalf("assistant context changed during checkpoint round trip: %#v", roundTripped)
}
}
diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.go
index 6e74c51a25..0b29f279fd 100644
--- a/kernel/agent/runtime.go
+++ b/kernel/agent/runtime.go
@@ -531,6 +531,9 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeT
if len(call.Attachments) > 0 {
persistedCall["attachments"] = call.Attachments
}
+ if call.ProviderData != nil {
+ persistedCall["providerData"] = call.ProviderData
+ }
calls = append(calls, persistedCall)
}
entry["toolCalls"] = calls
diff --git a/kernel/util/openai.go b/kernel/util/openai.go
index 4e96ea113e..457674fad1 100644
--- a/kernel/util/openai.go
+++ b/kernel/util/openai.go
@@ -215,17 +215,24 @@ func (t *extraBodyTransport) Do(req *http.Request) (*http.Response, error) {
return t.base.Do(req)
}
-// NewOpenAIClientWithModel 创建 OpenAI client,并按模型名匹配内置清单注入额外请求参数。
-// 绝大多数模型无匹配,走 NewOpenAIClient 老路径(不包中间件,零开销);
-// 命中清单的模型(如 MiniMax)会注入厂商专属参数(如 reasoning_split)。
+// NewOpenAIClientWithModel 创建 OpenAI client,并按模型与端点启用兼容适配。
+// 绝大多数模型走 NewOpenAIClient 路径;命中清单的模型会注入额外参数,官方 Gemini 端点会保留工具调用签名。
func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string) *openai.Client {
extra := ExtraBodyForModel(model)
- if len(extra) == 0 {
+ geminiThoughtSignatures := isGoogleGeminiOpenAICompatibleEndpoint(apiBaseURL, model)
+ if len(extra) == 0 && !geminiThoughtSignatures {
return NewOpenAIClient(apiKey, apiBaseURL)
}
config := openai.DefaultConfig(apiKey)
config.BaseURL = apiBaseURL
- config.HTTPClient = &extraBodyTransport{base: httpclient.NewUserAgentClient(nil), extraBody: extra}
+ var transport openai.HTTPDoer = httpclient.NewUserAgentClient(nil)
+ if len(extra) > 0 {
+ transport = &extraBodyTransport{base: transport, extraBody: extra}
+ }
+ if geminiThoughtSignatures {
+ transport = WrapGeminiThoughtSignatureTransport(transport)
+ }
+ config.HTTPClient = transport
return openai.NewClientWithConfig(config)
}
diff --git a/kernel/util/openai_gemini.go b/kernel/util/openai_gemini.go
new file mode 100644
index 0000000000..3704b14855
--- /dev/null
+++ b/kernel/util/openai_gemini.go
@@ -0,0 +1,340 @@
+// 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 util
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+const (
+ // Google 允许没有原始签名的历史函数调用使用该占位值跳过校验。
+ geminiThoughtSignatureValidatorSkip = "skip_thought_signature_validator"
+ maxGeminiStreamLineBytes = 32 * 1024 * 1024
+)
+
+type geminiThoughtSignatureContextKey struct{}
+
+// GeminiThoughtSignatureState 保存同一次 Agent 请求中的 Gemini 工具调用签名。
+// 签名是不透明值,只按工具调用 ID 写入和读取,不进行解码或修改。
+type GeminiThoughtSignatureState struct {
+ mu sync.RWMutex
+ signatures map[string]string
+}
+
+func NewGeminiThoughtSignatureState() *GeminiThoughtSignatureState {
+ return &GeminiThoughtSignatureState{signatures: map[string]string{}}
+}
+
+func ContextWithGeminiThoughtSignatureState(ctx context.Context, state *GeminiThoughtSignatureState) context.Context {
+ if state == nil {
+ return ctx
+ }
+ return context.WithValue(ctx, geminiThoughtSignatureContextKey{}, state)
+}
+
+func (s *GeminiThoughtSignatureState) Set(callID, signature string) {
+ if s == nil || callID == "" || signature == "" {
+ return
+ }
+ s.mu.Lock()
+ if s.signatures == nil {
+ s.signatures = map[string]string{}
+ }
+ s.signatures[callID] = signature
+ s.mu.Unlock()
+}
+
+func (s *GeminiThoughtSignatureState) Get(callID string) string {
+ if s == nil || callID == "" {
+ return ""
+ }
+ s.mu.RLock()
+ signature := s.signatures[callID]
+ s.mu.RUnlock()
+ return signature
+}
+
+func geminiThoughtSignatureStateFromContext(ctx context.Context) *GeminiThoughtSignatureState {
+ state, _ := ctx.Value(geminiThoughtSignatureContextKey{}).(*GeminiThoughtSignatureState)
+ return state
+}
+
+func isGoogleGeminiOpenAICompatibleEndpoint(apiBaseURL, model string) bool {
+ parsed, err := url.Parse(strings.TrimSpace(apiBaseURL))
+ if err != nil || !strings.EqualFold(parsed.Hostname(), "generativelanguage.googleapis.com") {
+ return false
+ }
+ if !strings.Contains(strings.ToLower(parsed.Path), "/openai") {
+ return false
+ }
+ return strings.HasPrefix(strings.ToLower(strings.TrimSpace(model)), "gemini-")
+}
+
+// WrapGeminiThoughtSignatureTransport 为 Google OpenAI 兼容端点补充工具调用签名往返支持。
+// 该函数导出仅用于 Agent 集成测试构造本地上游,生产代码通过 NewOpenAIClientWithModel 使用。
+func WrapGeminiThoughtSignatureTransport(base openai.HTTPDoer) openai.HTTPDoer {
+ return &geminiThoughtSignatureTransport{base: base}
+}
+
+type geminiThoughtSignatureTransport struct {
+ base openai.HTTPDoer
+}
+
+func (t *geminiThoughtSignatureTransport) Do(req *http.Request) (*http.Response, error) {
+ state := geminiThoughtSignatureStateFromContext(req.Context())
+ isChatRequest := req.Method == http.MethodPost && strings.Contains(req.URL.Path, "chat/completions")
+ if state != nil && isChatRequest {
+ injectGeminiThoughtSignatures(req, state)
+ }
+
+ resp, err := t.base.Do(req)
+ if err != nil || state == nil || !isChatRequest || resp == nil || resp.Body == nil {
+ return resp, err
+ }
+ resp.Body = &geminiThoughtSignatureReadCloser{
+ ReadCloser: resp.Body,
+ state: state,
+ callIDs: map[string]string{},
+ pendingSigs: map[string]string{},
+ }
+ return resp, nil
+}
+
+func injectGeminiThoughtSignatures(req *http.Request, state *GeminiThoughtSignatureState) {
+ if req.Body == nil {
+ return
+ }
+ body, err := io.ReadAll(req.Body)
+ if err != nil {
+ return
+ }
+ if err = req.Body.Close(); err != nil {
+ restoreOpenAIRequestBody(req, body)
+ return
+ }
+
+ var payload map[string]any
+ if err = json.Unmarshal(body, &payload); err != nil {
+ restoreOpenAIRequestBody(req, body)
+ return
+ }
+ messages, _ := payload["messages"].([]any)
+ changed := false
+ for _, rawMessage := range messages {
+ message, _ := rawMessage.(map[string]any)
+ if message["role"] != openai.ChatMessageRoleAssistant {
+ continue
+ }
+ toolCalls, _ := message["tool_calls"].([]any)
+ for _, rawToolCall := range toolCalls {
+ toolCall, _ := rawToolCall.(map[string]any)
+ if toolCall["type"] != string(openai.ToolTypeFunction) {
+ continue
+ }
+ if geminiThoughtSignatureFromToolCall(toolCall) != "" {
+ continue
+ }
+ callID, _ := toolCall["id"].(string)
+ signature := state.Get(callID)
+ if signature == "" {
+ signature = geminiThoughtSignatureValidatorSkip
+ }
+ setGeminiThoughtSignature(toolCall, signature)
+ changed = true
+ }
+ }
+ if !changed {
+ restoreOpenAIRequestBody(req, body)
+ return
+ }
+ merged, err := json.Marshal(payload)
+ if err != nil {
+ restoreOpenAIRequestBody(req, body)
+ return
+ }
+ restoreOpenAIRequestBody(req, merged)
+}
+
+func restoreOpenAIRequestBody(req *http.Request, body []byte) {
+ req.Body = io.NopCloser(bytes.NewReader(body))
+ req.ContentLength = int64(len(body))
+ req.GetBody = func() (io.ReadCloser, error) {
+ return io.NopCloser(bytes.NewReader(body)), nil
+ }
+}
+
+func geminiThoughtSignatureFromToolCall(toolCall map[string]any) string {
+ extraContent, _ := toolCall["extra_content"].(map[string]any)
+ google, _ := extraContent["google"].(map[string]any)
+ signature, _ := google["thought_signature"].(string)
+ return signature
+}
+
+func setGeminiThoughtSignature(toolCall map[string]any, signature string) {
+ extraContent, _ := toolCall["extra_content"].(map[string]any)
+ if extraContent == nil {
+ extraContent = map[string]any{}
+ toolCall["extra_content"] = extraContent
+ }
+ google, _ := extraContent["google"].(map[string]any)
+ if google == nil {
+ google = map[string]any{}
+ extraContent["google"] = google
+ }
+ google["thought_signature"] = signature
+}
+
+type geminiThoughtSignatureReadCloser struct {
+ io.ReadCloser
+ state *GeminiThoughtSignatureState
+ pending []byte
+ discardUntilLine bool
+ callIDs map[string]string
+ pendingSigs map[string]string
+}
+
+func (r *geminiThoughtSignatureReadCloser) Read(p []byte) (n int, err error) {
+ n, err = r.ReadCloser.Read(p)
+ if n > 0 {
+ r.consume(p[:n])
+ }
+ if err == io.EOF && len(r.pending) > 0 && !r.discardUntilLine {
+ r.captureLine(r.pending)
+ r.pending = nil
+ }
+ return
+}
+
+func (r *geminiThoughtSignatureReadCloser) consume(data []byte) {
+ for len(data) > 0 {
+ newline := bytes.IndexByte(data, '\n')
+ if newline < 0 {
+ if r.discardUntilLine {
+ return
+ }
+ if len(r.pending)+len(data) > maxGeminiStreamLineBytes {
+ r.pending = nil
+ r.discardUntilLine = true
+ return
+ }
+ r.pending = append(r.pending, data...)
+ return
+ }
+
+ part := data[:newline]
+ data = data[newline+1:]
+ if r.discardUntilLine {
+ r.discardUntilLine = false
+ continue
+ }
+ if len(r.pending)+len(part) > maxGeminiStreamLineBytes {
+ r.pending = nil
+ continue
+ }
+ r.pending = append(r.pending, part...)
+ r.captureLine(r.pending)
+ r.pending = r.pending[:0]
+ }
+}
+
+func (r *geminiThoughtSignatureReadCloser) captureLine(line []byte) {
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ return
+ }
+ if bytes.HasPrefix(line, []byte("data:")) {
+ line = bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:")))
+ }
+ if len(line) == 0 || bytes.Equal(line, []byte("[DONE]")) {
+ return
+ }
+ if !bytes.Contains(line, []byte(`"tool_calls"`)) {
+ return
+ }
+
+ var response geminiChatResponse
+ if json.Unmarshal(line, &response) != nil {
+ return
+ }
+ for _, choice := range response.Choices {
+ r.captureToolCalls(choice.Index, choice.Delta.ToolCalls)
+ r.captureToolCalls(choice.Index, choice.Message.ToolCalls)
+ }
+}
+
+func (r *geminiThoughtSignatureReadCloser) captureToolCalls(choiceIndex int, toolCalls []geminiChatToolCall) {
+ for position, toolCall := range toolCalls {
+ toolIndex := position
+ if toolCall.Index != nil {
+ toolIndex = *toolCall.Index
+ }
+ key := strconv.Itoa(choiceIndex) + ":" + strconv.Itoa(toolIndex)
+ if toolCall.ID != "" {
+ r.callIDs[key] = toolCall.ID
+ if signature := r.pendingSigs[key]; signature != "" {
+ r.state.Set(toolCall.ID, signature)
+ delete(r.pendingSigs, key)
+ }
+ }
+
+ signature := toolCall.ExtraContent.Google.ThoughtSignature
+ if signature == "" {
+ continue
+ }
+ callID := toolCall.ID
+ if callID == "" {
+ callID = r.callIDs[key]
+ }
+ if callID == "" {
+ r.pendingSigs[key] = signature
+ continue
+ }
+ r.state.Set(callID, signature)
+ }
+}
+
+type geminiChatResponse struct {
+ Choices []struct {
+ Index int `json:"index"`
+ Delta geminiChatMessage `json:"delta"`
+ Message geminiChatMessage `json:"message"`
+ } `json:"choices"`
+}
+
+type geminiChatMessage struct {
+ ToolCalls []geminiChatToolCall `json:"tool_calls"`
+}
+
+type geminiChatToolCall struct {
+ Index *int `json:"index,omitempty"`
+ ID string `json:"id,omitempty"`
+ ExtraContent struct {
+ Google struct {
+ ThoughtSignature string `json:"thought_signature,omitempty"`
+ } `json:"google,omitempty"`
+ } `json:"extra_content,omitempty"`
+}
diff --git a/kernel/util/openai_gemini_test.go b/kernel/util/openai_gemini_test.go
new file mode 100644
index 0000000000..63aa949f53
--- /dev/null
+++ b/kernel/util/openai_gemini_test.go
@@ -0,0 +1,140 @@
+// 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 util
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestIsGoogleGeminiOpenAICompatibleEndpoint(t *testing.T) {
+ tests := []struct {
+ baseURL string
+ model string
+ want bool
+ }{
+ {"https://generativelanguage.googleapis.com/v1beta/openai", "gemini-3.5-flash", true},
+ {"https://GENERATIVELANGUAGE.GOOGLEAPIS.COM/v1beta/openai/", "GEMINI-3-pro", true},
+ {"https://generativelanguage.googleapis.com/v1beta", "gemini-3.5-flash", false},
+ {"https://example.com/v1beta/openai", "gemini-3.5-flash", false},
+ {"https://generativelanguage.googleapis.com/v1beta/openai", "gpt-5", false},
+ {"not a URL", "gemini-3.5-flash", false},
+ }
+ for _, test := range tests {
+ if got := isGoogleGeminiOpenAICompatibleEndpoint(test.baseURL, test.model); got != test.want {
+ t.Errorf("isGoogleGeminiOpenAICompatibleEndpoint(%q, %q) = %v, want %v",
+ test.baseURL, test.model, got, test.want)
+ }
+ }
+}
+
+func TestGeminiThoughtSignatureTransportRoundTrip(t *testing.T) {
+ const (
+ existingCallID = "call-existing"
+ existingSignature = "existing-signature"
+ legacyCallID = "call-legacy"
+ newCallID = "call-new"
+ newSignature = "new-signature"
+ )
+
+ var captured map[string]any
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("read request failed: %v", err)
+ return
+ }
+ if err = json.Unmarshal(body, &captured); err != nil {
+ t.Errorf("decode request failed: %v", err)
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = io.WriteString(w,
+ `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"`+newCallID+
+ `","type":"function","function":{"name":"document","arguments":"{}"}}]}}]}`+"\n\n")
+ _, _ = io.WriteString(w,
+ `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"extra_content":{"google":`+
+ `{"thought_signature":"`+newSignature+`"}}}]}}]}`+"\n\n")
+ _, _ = io.WriteString(w, "data: [DONE]\n\n")
+ }))
+ defer server.Close()
+
+ state := NewGeminiThoughtSignatureState()
+ state.Set(existingCallID, existingSignature)
+ ctx := ContextWithGeminiThoughtSignatureState(context.Background(), state)
+ body := `{"model":"gemini-3.5-flash","messages":[` +
+ `{"role":"assistant","tool_calls":[` +
+ `{"id":"` + existingCallID + `","type":"function","function":{"name":"document","arguments":"{}"}},` +
+ `{"id":"` + legacyCallID + `","type":"function","function":{"name":"block","arguments":"{}"}}]},` +
+ `{"role":"tool","tool_call_id":"` + existingCallID + `","content":"ok"}]}`
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, server.URL+"/v1/chat/completions", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ transport := WrapGeminiThoughtSignatureTransport(server.Client())
+ resp, err := transport.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = io.Copy(io.Discard, resp.Body); err != nil {
+ t.Fatal(err)
+ }
+ if err = resp.Body.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ toolCalls := captured["messages"].([]any)[0].(map[string]any)["tool_calls"].([]any)
+ if got := geminiThoughtSignatureFromToolCall(toolCalls[0].(map[string]any)); got != existingSignature {
+ t.Fatalf("actual thought signature = %q, want %q", got, existingSignature)
+ }
+ if got := geminiThoughtSignatureFromToolCall(toolCalls[1].(map[string]any)); got != geminiThoughtSignatureValidatorSkip {
+ t.Fatalf("legacy thought signature = %q, want fallback", got)
+ }
+ if got := state.Get(newCallID); got != newSignature {
+ t.Fatalf("captured thought signature = %q, want %q", got, newSignature)
+ }
+}
+
+func TestGeminiThoughtSignatureTransportWithoutStatePassesThrough(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 := `{"messages":[{"role":"assistant","tool_calls":[{"id":"call-1","type":"function",` +
+ `"function":{"name":"document","arguments":"{}"}}]}]}`
+ req, err := http.NewRequest(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 state changed: %s", received)
+ }
+}