|
| 1 | +package executor |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + |
| 6 | + "github.com/tidwall/gjson" |
| 7 | + "github.com/tidwall/sjson" |
| 8 | +) |
| 9 | + |
| 10 | +// DedupeRequestToolOutputs 在进入具体 provider executor 前清理请求历史中的重复工具结果。 |
| 11 | +// 多 key / 多 auth 重试会让同一个客户端请求被多次翻译和尝试;如果上游历史里已经带了重复的 |
| 12 | +// tool output,这里先按 call_id/tool_call_id/tool_use_id 保留最后一次,保证所有 provider 共用同一份干净历史。 |
| 13 | +func DedupeRequestToolOutputs(req Request, opts Options) (Request, Options) { |
| 14 | + req.Payload = DedupeToolOutputs(req.Payload) |
| 15 | + if len(opts.OriginalRequest) > 0 { |
| 16 | + opts.OriginalRequest = DedupeToolOutputs(opts.OriginalRequest) |
| 17 | + } |
| 18 | + return req, opts |
| 19 | +} |
| 20 | + |
| 21 | +// DedupeToolOutputs 移除常见 API 形态中的重复工具结果,保留最后一次出现的结果。 |
| 22 | +// 覆盖 Responses input[].call_id、Chat messages[].tool_call_id/call_id,以及 Claude tool_result.tool_use_id。 |
| 23 | +func DedupeToolOutputs(body []byte) []byte { |
| 24 | + if len(body) == 0 { |
| 25 | + return body |
| 26 | + } |
| 27 | + |
| 28 | + body = dedupeRootArray(body, "input", func(item gjson.Result) (string, bool) { |
| 29 | + itemType := strings.TrimSpace(item.Get("type").String()) |
| 30 | + if !isResponsesToolOutputType(itemType) { |
| 31 | + return "", false |
| 32 | + } |
| 33 | + id := strings.TrimSpace(item.Get("call_id").String()) |
| 34 | + return id, id != "" |
| 35 | + }) |
| 36 | + |
| 37 | + body = dedupeRootArray(body, "messages", func(item gjson.Result) (string, bool) { |
| 38 | + if strings.TrimSpace(item.Get("role").String()) != "tool" { |
| 39 | + return "", false |
| 40 | + } |
| 41 | + id := strings.TrimSpace(item.Get("tool_call_id").String()) |
| 42 | + if id == "" { |
| 43 | + id = strings.TrimSpace(item.Get("call_id").String()) |
| 44 | + } |
| 45 | + return id, id != "" |
| 46 | + }) |
| 47 | + |
| 48 | + body = dedupeClaudeToolResultParts(body) |
| 49 | + return body |
| 50 | +} |
| 51 | + |
| 52 | +func isResponsesToolOutputType(itemType string) bool { |
| 53 | + switch itemType { |
| 54 | + case "function_call_output", "tool_search_output", "web_search_call_output", "computer_call_output", "custom_tool_call_output", "local_shell_call_output": |
| 55 | + return true |
| 56 | + default: |
| 57 | + return strings.HasSuffix(itemType, "_call_output") |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func dedupeRootArray(body []byte, path string, keyFn func(gjson.Result) (string, bool)) []byte { |
| 62 | + arr := gjson.GetBytes(body, path) |
| 63 | + if !arr.IsArray() { |
| 64 | + return body |
| 65 | + } |
| 66 | + deduped, changed := dedupeJSONResults(arr.Array(), keyFn) |
| 67 | + if !changed { |
| 68 | + return body |
| 69 | + } |
| 70 | + updated, err := sjson.SetRawBytes(body, path, deduped) |
| 71 | + if err != nil { |
| 72 | + return body |
| 73 | + } |
| 74 | + return updated |
| 75 | +} |
| 76 | + |
| 77 | +func dedupeJSONResults(items []gjson.Result, keyFn func(gjson.Result) (string, bool)) ([]byte, bool) { |
| 78 | + lastIdxByKey := make(map[string]int, len(items)) |
| 79 | + candidateIdx := make([]int, 0, len(items)) |
| 80 | + for i, item := range items { |
| 81 | + key, ok := keyFn(item) |
| 82 | + if !ok { |
| 83 | + continue |
| 84 | + } |
| 85 | + candidateIdx = append(candidateIdx, i) |
| 86 | + lastIdxByKey[key] = i |
| 87 | + } |
| 88 | + |
| 89 | + if len(lastIdxByKey) == len(candidateIdx) { |
| 90 | + return nil, false |
| 91 | + } |
| 92 | + |
| 93 | + keep := make(map[int]struct{}, len(lastIdxByKey)) |
| 94 | + for _, idx := range lastIdxByKey { |
| 95 | + keep[idx] = struct{}{} |
| 96 | + } |
| 97 | + candidates := make(map[int]struct{}, len(candidateIdx)) |
| 98 | + for _, idx := range candidateIdx { |
| 99 | + candidates[idx] = struct{}{} |
| 100 | + } |
| 101 | + |
| 102 | + filtered := make([]byte, 0) |
| 103 | + filtered = append(filtered, '[') |
| 104 | + first := true |
| 105 | + for i, item := range items { |
| 106 | + if _, isCandidate := candidates[i]; isCandidate { |
| 107 | + if _, ok := keep[i]; !ok { |
| 108 | + continue |
| 109 | + } |
| 110 | + } |
| 111 | + if !first { |
| 112 | + filtered = append(filtered, ',') |
| 113 | + } |
| 114 | + filtered = append(filtered, item.Raw...) |
| 115 | + first = false |
| 116 | + } |
| 117 | + filtered = append(filtered, ']') |
| 118 | + return filtered, true |
| 119 | +} |
| 120 | + |
| 121 | +func dedupeClaudeToolResultParts(body []byte) []byte { |
| 122 | + messages := gjson.GetBytes(body, "messages") |
| 123 | + if !messages.IsArray() { |
| 124 | + return body |
| 125 | + } |
| 126 | + |
| 127 | + messageItems := messages.Array() |
| 128 | + type partRef struct { |
| 129 | + messageIdx int |
| 130 | + partIdx int |
| 131 | + } |
| 132 | + lastRefByID := make(map[string]partRef) |
| 133 | + candidateRefs := make([]partRef, 0) |
| 134 | + |
| 135 | + for msgIdx, msg := range messageItems { |
| 136 | + content := msg.Get("content") |
| 137 | + if !content.IsArray() { |
| 138 | + continue |
| 139 | + } |
| 140 | + for partIdx, part := range content.Array() { |
| 141 | + if strings.TrimSpace(part.Get("type").String()) != "tool_result" { |
| 142 | + continue |
| 143 | + } |
| 144 | + id := strings.TrimSpace(part.Get("tool_use_id").String()) |
| 145 | + if id == "" { |
| 146 | + continue |
| 147 | + } |
| 148 | + ref := partRef{messageIdx: msgIdx, partIdx: partIdx} |
| 149 | + candidateRefs = append(candidateRefs, ref) |
| 150 | + lastRefByID[id] = ref |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + if len(lastRefByID) == len(candidateRefs) { |
| 155 | + return body |
| 156 | + } |
| 157 | + |
| 158 | + keep := make(map[partRef]struct{}, len(lastRefByID)) |
| 159 | + for _, ref := range lastRefByID { |
| 160 | + keep[ref] = struct{}{} |
| 161 | + } |
| 162 | + drop := make(map[partRef]struct{}, len(candidateRefs)-len(lastRefByID)) |
| 163 | + for _, ref := range candidateRefs { |
| 164 | + if _, ok := keep[ref]; !ok { |
| 165 | + drop[ref] = struct{}{} |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + filteredMessages := make([]byte, 0, len(messages.Raw)) |
| 170 | + filteredMessages = append(filteredMessages, '[') |
| 171 | + firstMessage := true |
| 172 | + for msgIdx, msg := range messageItems { |
| 173 | + content := msg.Get("content") |
| 174 | + messageRaw := []byte(msg.Raw) |
| 175 | + if content.IsArray() { |
| 176 | + parts := content.Array() |
| 177 | + filteredParts := make([]byte, 0, len(content.Raw)) |
| 178 | + filteredParts = append(filteredParts, '[') |
| 179 | + firstPart := true |
| 180 | + for partIdx, part := range parts { |
| 181 | + if _, shouldDrop := drop[partRef{messageIdx: msgIdx, partIdx: partIdx}]; shouldDrop { |
| 182 | + continue |
| 183 | + } |
| 184 | + if !firstPart { |
| 185 | + filteredParts = append(filteredParts, ',') |
| 186 | + } |
| 187 | + filteredParts = append(filteredParts, part.Raw...) |
| 188 | + firstPart = false |
| 189 | + } |
| 190 | + filteredParts = append(filteredParts, ']') |
| 191 | + if len(gjson.ParseBytes(filteredParts).Array()) == 0 { |
| 192 | + continue |
| 193 | + } |
| 194 | + updated, err := sjson.SetRawBytes(messageRaw, "content", filteredParts) |
| 195 | + if err == nil { |
| 196 | + messageRaw = updated |
| 197 | + } |
| 198 | + } |
| 199 | + if !firstMessage { |
| 200 | + filteredMessages = append(filteredMessages, ',') |
| 201 | + } |
| 202 | + filteredMessages = append(filteredMessages, messageRaw...) |
| 203 | + firstMessage = false |
| 204 | + } |
| 205 | + filteredMessages = append(filteredMessages, ']') |
| 206 | + |
| 207 | + updated, err := sjson.SetRawBytes(body, "messages", filteredMessages) |
| 208 | + if err != nil { |
| 209 | + return body |
| 210 | + } |
| 211 | + return updated |
| 212 | +} |
0 commit comments