From 1c149e36579dea699e7015148e94c01bf6a61edd Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Sat, 15 Aug 2026 02:52:28 +0800 Subject: [PATCH] fix: normalize Anthropic tool thinking history --- README.md | 4 +++ convert.go | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ gateway.go | 16 ++++++++- 3 files changed, 114 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e0436a..57945fe 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,10 @@ SOCKS5 代理示例: 模型同时存在于 Zen 与 Go 时按 `prefer` 配置选择:值为 `go` 时优先 Go,值为 `zen` 时优先 Zen(默认 `go`)。仅存在于某一池时才使用该池的 key。 +### Thinking 工具历史兼容 + +通过 Anthropic Messages API 调用 DeepSeek、Kimi/Moonshot 或 MiMo 模型时,代理会在转发前规范化包含 `tool_use` 的 assistant 历史:保留有效 thinking 文本、为缺失或空的 thinking 补充兼容占位内容、将 `redacted_thinking` 转为普通 thinking,并移除这些兼容端点不接受的 `signature`。该处理仅作用于已知需要此兼容行为的模型或上游地址,普通 Claude/Anthropic 请求不会被修改。 + ### `performance` | 字段 | 含义 | diff --git a/convert.go b/convert.go index a044564..a1e1f9e 100644 --- a/convert.go +++ b/convert.go @@ -8,6 +8,13 @@ import ( "time" ) +const ( + anthropicThinkingPlaceholder = "tool call" + anthropicRedactedThinkingPlaceholder = "[redacted thinking]" +) + +var reasoningVendorHints = [...]string{"moonshot", "kimi", "deepseek", "mimo", "xiaomimimo"} + type bridgeBlock struct { Kind string Text string @@ -87,6 +94,94 @@ func convertRequest(from, to Protocol, input map[string]any) (map[string]any, er return encodeBridgeRequest(to, request) } +// shouldNormalizeAnthropicToolThinkingHistory identifies providers whose +// Anthropic-compatible endpoints require a plain thinking block before an +// assistant tool_use is replayed. Model names cover the normal OpenCode route; +// the upstream URL also supports deployments that alias those models. +func shouldNormalizeAnthropicToolThinkingHistory(model, upstreamURL string) bool { + return isReasoningVendorIdentifier(model) || isReasoningVendorIdentifier(upstreamURL) +} + +func isReasoningVendorIdentifier(value string) bool { + value = strings.ToLower(value) + for _, hint := range reasoningVendorHints { + if strings.Contains(value, hint) { + return true + } + } + return false +} + +// normalizeAnthropicToolThinkingHistory repairs only assistant turns that +// contain tool_use. DeepSeek, Kimi/Moonshot and MiMo reject signed, redacted, +// empty or missing thinking history on those turns even though Anthropic +// clients can legitimately send each of those shapes. +func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { + messages, ok := input["messages"].([]any) + if !ok { + return false + } + + changed := false + for _, rawMessage := range messages { + message, ok := rawMessage.(map[string]any) + if !ok || stringAt(message, "role") != "assistant" { + continue + } + content, ok := message["content"].([]any) + if !ok || !anthropicContentHasType(content, "tool_use") { + continue + } + + hasThinking := false + for i, rawBlock := range content { + block, ok := rawBlock.(map[string]any) + if !ok { + continue + } + switch stringAt(block, "type") { + case "thinking": + hasThinking = true + if _, exists := block["signature"]; exists { + delete(block, "signature") + changed = true + } + thinking, ok := block["thinking"].(string) + if !ok || strings.TrimSpace(thinking) == "" { + block["thinking"] = anthropicThinkingPlaceholder + changed = true + } + case "redacted_thinking": + hasThinking = true + content[i] = map[string]any{ + "type": "thinking", + "thinking": anthropicRedactedThinkingPlaceholder, + } + changed = true + } + } + if !hasThinking { + content = append([]any{map[string]any{ + "type": "thinking", + "thinking": anthropicThinkingPlaceholder, + }}, content...) + message["content"] = content + changed = true + } + } + return changed +} + +func anthropicContentHasType(content []any, kind string) bool { + for _, rawBlock := range content { + block, _ := rawBlock.(map[string]any) + if stringAt(block, "type") == kind { + return true + } + } + return false +} + func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) { request := bridgeRequest{ Model: stringAt(input, "model"), diff --git a/gateway.go b/gateway.go index f0db24d..d75971b 100644 --- a/gateway.go +++ b/gateway.go @@ -226,12 +226,26 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { return } encoded := body + upstreamPayload := payload + needsEncoding := false + if external == ProtocolAnthropic { + upstreamURL := g.cfg.Upstream.Zen + if route.Tier == TierGo { + upstreamURL = g.cfg.Upstream.Go + } + if shouldNormalizeAnthropicToolThinkingHistory(model, upstreamURL) { + needsEncoding = normalizeAnthropicToolThinkingHistory(upstreamPayload) + } + } if external != route.Protocol { - upstreamPayload, err := convertRequest(external, route.Protocol, payload) + upstreamPayload, err = convertRequest(external, route.Protocol, upstreamPayload) if err != nil { writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "") return } + needsEncoding = true + } + if needsEncoding { encoded, err = json.Marshal(upstreamPayload) if err != nil { writeAPIError(w, external, http.StatusBadRequest, "request contains unsupported JSON values", "invalid_request_error", "")