From efda6f6fb0f187668cb5fa9b52ff1791f2376d98 Mon Sep 17 00:00:00 2001 From: William Drake Date: Fri, 27 Nov 2026 16:21:34 -0700 Subject: [PATCH] fix(openai): add Gemini thought signatures to AI Studio tool-call history Google AI Studio rejects replayed function calls without a thought signature (400 "Function call is missing a thought_signature in functionCall parts"). The signature arrives in tool_calls[].extra_content.google, which Codex Responses history cannot preserve, so follow-up turns after tool calls fail when routed to AI Studio. Before a Chat Completions request goes to generativelanguage.googleapis.com, give each assistant tool call without an existing thought_signature the dummy value skip_thought_signature_validator (matching the native Gemini path). Signatures embedded in Unity/LiteLLM "__thought__" call-id suffixes are not reused because they are issued by a different Google backend and fail with INVALID_THOUGHT_SIGNATURE; the call id itself is kept intact so tool outputs still match. Other upstreams are byte-for-byte unchanged. --- .../service/openai_gateway_cc_pipeline.go | 2 + ...openai_gateway_gemini_thought_signature.go | 69 ++++++++++++++++++ ...i_gateway_gemini_thought_signature_test.go | 72 +++++++++++++++++++ 3 files changed, 143 insertions(+) create mode 100644 backend/internal/service/openai_gateway_gemini_thought_signature.go create mode 100644 backend/internal/service/openai_gateway_gemini_thought_signature_test.go diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index dcebc37ee2..09eb7d9598 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -217,6 +217,8 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( // 字段,上游 400 "The `reasoning_content` in the thinking mode must be // passed back to the API"。在共用出站点补空格占位,真实明文不覆盖。 body = ensureDeepSeekChatReasoningPlaceholders(account, body) + // AI Studio rejects replayed tool calls without a Gemini thought signature. + body = ensureGeminiChatThoughtSignatures(account, body) upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) upstreamReq, err := http.NewRequestWithContext(upstreamCtx, http.MethodPost, targetURL, bytes.NewReader(body)) releaseUpstreamCtx() diff --git a/backend/internal/service/openai_gateway_gemini_thought_signature.go b/backend/internal/service/openai_gateway_gemini_thought_signature.go new file mode 100644 index 0000000000..0cf9c5a140 --- /dev/null +++ b/backend/internal/service/openai_gateway_gemini_thought_signature.go @@ -0,0 +1,69 @@ +package service + +import ( + "net/url" + "strconv" + "strings" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const geminiAIStudioHost = "generativelanguage.googleapis.com" + +// targetsGeminiAIStudio reports whether the account's Chat Completions +// upstream is Google AI Studio's OpenAI-compatible endpoint. +func targetsGeminiAIStudio(account *Account) bool { + if account == nil { + return false + } + u, err := url.Parse(strings.TrimSpace(account.GetOpenAIBaseURL())) + if err != nil { + return false + } + return strings.EqualFold(u.Hostname(), geminiAIStudioHost) +} + +// ensureGeminiChatThoughtSignatures gives every replayed assistant tool call a +// Gemini thought signature before the request goes to AI Studio. +// +// Gemini returns the signature in tool_calls[].extra_content.google, but the +// Responses items Codex keeps have no place for it, so history comes back +// without one and AI Studio answers 400 "Function call is missing a +// thought_signature in functionCall parts". Missing signatures get the +// documented skip_thought_signature_validator value, the same one the native +// Gemini path uses. The "__thought__" suffix that Unity's LiteLLM +// puts in call ids is deliberately not reused: it comes from a different +// Google backend and AI Studio rejects it as "Corrupted thought signature". +// Existing signatures are kept, and other upstreams get the body unchanged. +func ensureGeminiChatThoughtSignatures(account *Account, body []byte) []byte { + if !targetsGeminiAIStudio(account) { + return body + } + messages := gjson.GetBytes(body, "messages") + if !messages.IsArray() { + return body + } + updated := body + for i, msg := range messages.Array() { + if msg.Get("role").String() != "assistant" { + continue + } + calls := msg.Get("tool_calls") + if !calls.IsArray() { + continue + } + for j, call := range calls.Array() { + if call.Get("extra_content.google.thought_signature").String() != "" { + continue + } + path := "messages." + strconv.Itoa(i) + ".tool_calls." + strconv.Itoa(j) + ".extra_content.google.thought_signature" + next, err := sjson.SetBytes(updated, path, geminiDummyThoughtSignature) + if err != nil { + return body + } + updated = next + } + } + return updated +} diff --git a/backend/internal/service/openai_gateway_gemini_thought_signature_test.go b/backend/internal/service/openai_gateway_gemini_thought_signature_test.go new file mode 100644 index 0000000000..33e807f870 --- /dev/null +++ b/backend/internal/service/openai_gateway_gemini_thought_signature_test.go @@ -0,0 +1,72 @@ +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func aiStudioOpenAIAccount() *Account { + return &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", + }, + } +} + +// Codex history comes back through the Responses bridge without Gemini's +// extra_content.google.thought_signature, and AI Studio rejects any replayed +// function call that has none with 400 "Function call is missing a +// thought_signature in functionCall parts". +func TestEnsureGeminiChatThoughtSignatures_FillsMissing(t *testing.T) { + body := []byte(`{"model":"gemini-4-neon","messages":[` + + `{"role":"user","content":"run"},` + + `{"role":"assistant","tool_calls":[` + + `{"id":"call_a","type":"function","function":{"name":"exec_command","arguments":"{}"}},` + + `{"id":"call_b","type":"function","function":{"name":"exec_command","arguments":"{}"}}]},` + + `{"role":"tool","tool_call_id":"call_a","content":"ok"},` + + `{"role":"tool","tool_call_id":"call_b","content":"ok"}]}`) + + out := ensureGeminiChatThoughtSignatures(aiStudioOpenAIAccount(), body) + + calls := gjson.GetBytes(out, "messages.1.tool_calls") + require.Len(t, calls.Array(), 2) + for _, call := range calls.Array() { + require.Equal(t, geminiDummyThoughtSignature, call.Get("extra_content.google.thought_signature").String()) + } + require.Equal(t, "call_a", calls.Get("0.id").String()) + require.Equal(t, "call_a", gjson.GetBytes(out, "messages.2.tool_call_id").String()) +} + +// Unity's LiteLLM carries a signature in the call id, but it was issued by a +// different Google backend: AI Studio rejects it with 400 "Corrupted thought +// signature" (INVALID_THOUGHT_SIGNATURE). Such a call gets the placeholder and +// keeps the id it was answered under. +func TestEnsureGeminiChatThoughtSignatures_IgnoresLiteLLMIDSuffix(t *testing.T) { + body := []byte(`{"model":"gemini-4-neon","messages":[` + + `{"role":"assistant","tool_calls":[{"id":"call_a__thought__REALSIG","type":"function","function":{"name":"x","arguments":"{}"}}]},` + + `{"role":"tool","tool_call_id":"call_a__thought__REALSIG","content":"ok"}]}`) + + out := ensureGeminiChatThoughtSignatures(aiStudioOpenAIAccount(), body) + + require.Equal(t, geminiDummyThoughtSignature, gjson.GetBytes(out, "messages.0.tool_calls.0.extra_content.google.thought_signature").String()) + require.Equal(t, "call_a__thought__REALSIG", gjson.GetBytes(out, "messages.0.tool_calls.0.id").String()) +} + +func TestEnsureGeminiChatThoughtSignatures_KeepsExistingAndOtherUpstreams(t *testing.T) { + withSig := []byte(`{"model":"gemini-4-neon","messages":[{"role":"assistant","tool_calls":[{"id":"call_a","type":"function","function":{"name":"x","arguments":"{}"},"extra_content":{"google":{"thought_signature":"REAL"}}}]}]}`) + require.Equal(t, string(withSig), string(ensureGeminiChatThoughtSignatures(aiStudioOpenAIAccount(), withSig))) + + noCalls := []byte(`{"model":"gemini-4-neon","messages":[{"role":"user","content":"hi"}]}`) + require.Equal(t, string(noCalls), string(ensureGeminiChatThoughtSignatures(aiStudioOpenAIAccount(), noCalls))) + + other := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-test", "base_url": "https://uai-litellm.internal.unity.com:8443", + }} + missing := []byte(`{"model":"gemini-4-neon","messages":[{"role":"assistant","tool_calls":[{"id":"call_a","type":"function","function":{"name":"x","arguments":"{}"}}]}]}`) + require.Equal(t, string(missing), string(ensureGeminiChatThoughtSignatures(other, missing))) +}