diff --git a/backend/docs/RESPONSES_MODELINPUT_NOTES.md b/backend/docs/RESPONSES_MODELINPUT_NOTES.md deleted file mode 100644 index 51bfd65d..00000000 --- a/backend/docs/RESPONSES_MODELINPUT_NOTES.md +++ /dev/null @@ -1,287 +0,0 @@ -# Grok Build Responses / ModelInput 注意事项 - -> 适用:Codex / OpenAI Responses 客户端 → `grok2api` → Grok Build `POST /v1/responses` -> 现象:首轮常成功,后续多轮历史回放时 422 -> 错误: -> -> ```text -> unexpected status 422 Unprocessable Entity: -> {"error":"Failed to deserialize the JSON body into the target type: -> data did not match any variant of untagged enum ModelInput"} -> ``` - -## 1. 结论(先看这个) - -Grok Build 0.2.99 的 `input[]` 使用 **Rust 风格 untagged enum `ModelInput`**,对历史 item 形状很严格: - -1. **不要原样透传 Codex 历史** -2. **必须白名单重建**每个 `input[]` item / content part -3. **禁止输出 `null` 字段**(尤其是 `reasoning`) -4. **禁止保留 Codex 私有字段** - -相关实现主要在: - -- `backend/internal/infra/provider/cli/responses_history.go` -- `backend/internal/infra/provider/cli/responses_input.go` -- `backend/internal/infra/provider/cli/responses_codex_tools.go` -- `backend/internal/infra/provider/cli/responses_tool_state.go` -- `backend/internal/infra/provider/cli/responses_tool_declarations.go` -- `backend/internal/infra/provider/cli/responses_tool_choice.go` - -## 2. 已确认会 422 的形状 - -### 2.1 `reasoning` 带 null 字段(高频,会话已复现) - -Codex 第二轮经常带回: - -```json -{ - "type": "reasoning", - "id": "rs_xxx", - "summary": [{"type": "summary_text", "text": "..."}], - "content": null, - "encrypted_content": null, - "internal_chat_message_metadata_passthrough": {"turn_id": "..."} -} -``` - -错误处理: - -```json -{ - "type": "reasoning", - "id": "rs_xxx", - "summary": [...], - "content": null, - "encrypted_content": null -} -``` - -正确处理: - -- 有可用 `encrypted_content`:只保留非 null 白名单字段回放 -- `encrypted_content` 缺失 / null / 空:降级为 developer boundary,保留 summary 文本 - **绝不要回放带 null 的 reasoning 对象** - -复现会话:`019f64fa-984d-73e2-be0e-c732978d3321` -(首轮 200,第二轮带 null reasoning 后 422) - -### 2.2 Codex 私有字段 - -几乎每条 Codex history 都会带: - -- `internal_chat_message_metadata_passthrough` -- `phase` - -这些字段不能进入上游 `input[]`。 - -### 2.3 assistant 文本类型写错 - -| role | 正确 content part type | -|---|---| -| `assistant` / `model` | `output_text` | -| `user` / `developer` / `system` | `input_text` | - -**错误做法:** 把 assistant 的 `output_text` 全改成 `input_text` -**正确做法:** 按 role 选择类型(对齐 CLIProxyAPI 的 construction 路径) - -### 2.4 function 历史字段过多 - -`function_call` 只允许: - -```json -{"type":"function_call","call_id":"...","name":"...","arguments":"..."} -``` - -`function_call_output` 只允许: - -```json -{"type":"function_call_output","call_id":"...","output":"..."} -``` - -不要带: - -- `id` -- `status` -- `namespace` -- `internal_chat_message_metadata_passthrough` -- 其他私有/扩展字段 - -`output` 必须是 **字符串**;对象要先 `json.Marshal` 成字符串。 - -### 2.5 未知 / 外部工具历史原样透传 - -以下类型不能原样发给 Grok Build,应改写成 developer boundary 或兼容 function 协议: - -- `web_search_call` -- 原始 `shell_call`(若上游不接受) -- 其他未知 `type` - -`GROK2API_STRIP_EXTERNAL_TOOLS=true` 时,还应剥离工具声明: - -- `web_search*` -- `computer_use_preview` - -保留 function-backed 工具:`function` / `apply_patch` / `tool_search` / `shell|local_shell`。 - -## 3. 推荐白名单模型 - -只向 Grok Build 发送这些 `input[]` 形态: - -### message - -```json -{ - "type": "message", - "role": "user|assistant|developer", - "content": [ - {"type": "input_text|output_text", "text": "..."}, - {"type": "input_image", "image_url": "..."}, - {"type": "input_file", "file_data": "...", "filename": "..."} - ] -} -``` - -注意: - -- 不带 `id` / `status` / `phase` / metadata -- content part 不带 `annotations` -- 有 `role` 但缺 `type` 时,先补 `"type":"message"` - -### function_call - -```json -{ - "type": "function_call", - "call_id": "call_xxx", - "name": "tool_name", - "arguments": "{}" -} -``` - -### function_call_output - -```json -{ - "type": "function_call_output", - "call_id": "call_xxx", - "output": "string only" -} -``` - -### reasoning - -```json -{ - "type": "reasoning", - "id": "rs_xxx", - "summary": [{"type":"summary_text","text":"..."}], - "encrypted_content": "non-empty cipher" -} -``` - -规则: - -- 只保留非 null 字段 -- 没有可用 `encrypted_content` 时,不要发 `type=reasoning`,改发 developer boundary - -### shell_call_output(如需保留) - -- `output` 必须是结构化数组块 -- outcome 使用 `exit_code`(不是 `exitCode`) -- 去掉未知块字段(如 `command`) - -### 其他未知类型 - -```json -{ - "type": "message", - "role": "developer", - "content": [ - { - "type": "input_text", - "text": "A prior Responses history item was omitted ..." - } - ] -} -``` - -## 4. 实现原则 - -1. **白名单重建,不要 clone 后删字段** - clone 容易把 `null` / 私有字段带回去。 - -2. **JSON 里不要出现 `null` 值** - Go 里 `map[string]any{"content": nil}` 会编码成 `"content":null`,对 untagged enum 很危险。 - -3. **对齐 CLIProxyAPI 的 construction,而不是它的 Responses passthrough** - CLIProxyAPI 没有 Grok 专用 adapter;它从 Chat/Claude/Gemini 构造 Codex input 时才会发出干净 item。 - Responses→Codex 本身几乎是 top-level 清洗,历史深字段不会帮你修。 - -4. **多轮问题优先查第二轮历史** - 典型模式: - - 第 1 轮:只有 user/developer message → 200 - - 第 2 轮:附带 assistant + reasoning(+null) / tool history → 422 - -5. **修完后要替换正在运行的 Docker 二进制** - 只改源码不重建容器,Codex 仍打旧逻辑。 - -## 5. 排查清单 - -遇到新的 ModelInput 422 时: - -1. 从 Docker 日志拿 `request_id` 与时间点 -2. 找到对应 Codex session rollout(`~/.codex/sessions/...jsonl`) -3. 统计第二轮 `response_item` 的 `type` 与额外字段 -4. 特别检查: - - `reasoning.content` / `reasoning.encrypted_content` 是否为 null - - 是否残留 `internal_chat_message_metadata_passthrough` / `phase` - - assistant content 是否不是 `output_text` - - `function_call*` 是否多了 `id/status` -5. 用 normalize 单测 / 临时 fixture 验证清洗结果里: - - 无 `null` - - 无私有字段 - - item 类型都在白名单 -6. `go test ./internal/infra/provider/cli/` -7. 编译 Linux 二进制并替换容器: - -```bash -cd backend -GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ../out/grok2api ./cmd/grok2api -docker cp ../out/grok2api grok2api:/app/grok2api -docker restart grok2api -curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8000/healthz -docker commit grok2api grok2api:local -``` - -8. **新开 Codex 任务验证**(旧会话可能已污染) - -## 6. 相关测试 - -优先看 / 补充这些回归: - -- `TestAssistantOutputMessageHistoryKeepsOutputText` -- `TestNullEncryptedReasoningBecomesBoundary` -- `TestCodexPrivateMetadataIsStrippedFromHistory` -- `TestFunctionCallOutputHistoryEncodesStructuredOutput` -- `TestStripExternalClientToolHistory` -- `TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted` - -## 7. 环境变量 - -| 变量 | 作用 | -|---|---| -| `GROK2API_STRIP_EXTERNAL_TOOLS=true` | 剥离 Grok Build 难托管的外部工具声明与对应历史,保留 function-backed 工具 | - -Docker Compose override 示例见仓库根目录 `docker-compose.override.yml`。 - -## 8. 参考会话 - -| Session ID | 现象 | -|---|---| -| `019f5ed1-ebd0-7183-8229-ae0bdaf88c9e` | 多轮 Codex 历史复杂,首次系统性排查 ModelInput 422 | -| `019f64fa-984d-73e2-be0e-c732978d3321` | 首轮 200,第二轮因 null `reasoning.encrypted_content` 422 | - -## 9. 一句话记住 - -> **Codex 历史不能透传;按白名单重建,role 决定 text 类型,reasoning 没有 cipher 就降级,任何 null / 私有字段都不要发给 Grok Build。** diff --git a/backend/internal/infra/provider/cli/responses_codex_tools.go b/backend/internal/infra/provider/cli/responses_codex_tools.go index 085e3279..6e58d3fa 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools.go @@ -19,7 +19,7 @@ func (c *responsesToolCompatibility) normalizeShellTool(tool map[string]any, par return c.normalizeNativeTool(tool, param) } -// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.99 原生 local shell 环境。 +// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.101 原生 local shell 环境。 func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[string]any, param string) ([]any, error) { if c.nativeShell || c.legacyLocalShell { return nil, &responsesRequestError{ @@ -27,13 +27,8 @@ func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[stri Param: param + ".type", Code: "invalid_parameter", } } - for key := range tool { - if key != "type" { - return nil, &responsesRequestError{ - Message: "旧版 local_shell 不支持额外配置字段", - Param: param + "." + key, Code: "unsupported_parameter", - } - } + if len(tool) > 1 { + c.addWarning("legacy_local_shell_controls_ignored") } c.legacyLocalShell = true c.changed = true @@ -45,20 +40,9 @@ func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[stri } // normalizeApplyPatchTool 将客户端执行的 apply_patch 包装为严格 function。 -func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, namespace, param string) ([]any, error) { - if namespace != "" { - return nil, &responsesRequestError{ - Message: "namespace 内暂不支持 apply_patch", - Param: param + ".type", Code: "unsupported_parameter", - } - } - for key := range tool { - if key != "type" { - return nil, &responsesRequestError{ - Message: "apply_patch 不接受自定义字段", - Param: param + "." + key, Code: "unsupported_parameter", - } - } +func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, param string) ([]any, error) { + if len(tool) > 1 { + c.addWarning("apply_patch_controls_ignored") } identity := responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"} c.changed = true @@ -100,17 +84,11 @@ func (c *responsesToolCompatibility) normalizeApplyPatchCallInput(item map[strin if err != nil { return nil, err } - converted := map[string]any{ + return map[string]any{ "type": "function_call", "call_id": callID, "name": c.alias(responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"}), "arguments": string(arguments), - } - for _, key := range []string{"id", "status"} { - if value, exists := item[key]; exists { - converted[key] = cloneJSONValue(value) - } - } - return converted, nil + }, nil } func normalizeApplyPatchOutputInput(item map[string]any, param string) (map[string]any, error) { @@ -202,7 +180,7 @@ func legacyShellAction(value any, param string) (map[string]any, error) { return nil, &responsesRequestError{Message: "local_shell_call.action 必须是对象", Param: param, Code: "invalid_parameter"} } if kind := strings.TrimSpace(stringField(action, "type")); kind != "" && kind != "exec" { - return nil, &responsesRequestError{Message: "local_shell_call.action.type 只支持 exec", Param: param + ".type", Code: "unsupported_parameter"} + return nil, &responsesRequestError{Message: "local_shell_call.action.type 必须是 exec", Param: param + ".type", Code: "invalid_parameter"} } command, err := legacyShellCommand(action, param) if err != nil { @@ -292,7 +270,7 @@ func normalizeLegacyLocalShellOutputInput(item map[string]any, param string) (ma return nil, &responsesRequestError{Message: "local_shell_call_output.output 必须是字符串或数组", Param: param + ".output", Code: "invalid_parameter"} } converted := map[string]any{"type": "shell_call_output", "call_id": callID, "output": output} - if value, exists := item["max_output_length"]; exists { + if value, exists := item["max_output_length"]; exists && value != nil { converted["max_output_length"] = cloneJSONValue(value) } return converted, nil @@ -308,7 +286,7 @@ func normalizeShellCallOutputInput(item map[string]any, param string) (map[strin return nil, err } converted := map[string]any{"type": "shell_call_output", "call_id": callID, "output": output} - if value, exists := item["max_output_length"]; exists { + if value, exists := item["max_output_length"]; exists && value != nil { converted["max_output_length"] = cloneJSONValue(value) } return converted, nil @@ -323,7 +301,7 @@ func normalizeFunctionCallOutputInput(item map[string]any, param string) (map[st if err != nil { return nil, err } - // Allowlist only. CLIProxyAPI builds function_call_output without id/status. + // 按官方 Build 回放结构重建,不携带输出态 id/status。 return map[string]any{"type": "function_call_output", "call_id": callID, "output": output}, nil } @@ -458,7 +436,7 @@ func validEnvironmentName(value string) bool { func (c *responsesToolCompatibility) normalizeAdditionalToolsInput(item map[string]any, param string) (map[string]any, []any, []any, error) { if role := strings.TrimSpace(stringField(item, "role")); role != "" && role != "developer" { - return nil, nil, nil, &responsesRequestError{Message: "additional_tools.role 只支持 developer", Param: param + ".role", Code: "unsupported_parameter"} + c.addWarning("additional_tools_role_approximated") } tools, ok := item["tools"].([]any) if !ok { diff --git a/backend/internal/infra/provider/cli/responses_codex_tools_test.go b/backend/internal/infra/provider/cli/responses_codex_tools_test.go index e536d58a..08d90be0 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools_test.go @@ -121,9 +121,10 @@ func TestFunctionCallOutputHistoryEncodesStructuredOutput(t *testing.T) { } } -func TestAssistantOutputMessageHistoryKeepsOutputText(t *testing.T) { +func TestAssistantOutputMessageHistoryUsesEasyMessageText(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ + {"type":"message","role":"system","content":"system instruction"}, {"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[ {"type":"output_text","text":"Hi there","annotations":[]} ]}, @@ -138,15 +139,18 @@ func TestAssistantOutputMessageHistoryKeepsOutputText(t *testing.T) { t.Fatal(err) } items := request["input"].([]any) - first := items[0].(map[string]any) - second := items[1].(map[string]any) - firstContent := first["content"].([]any)[0].(map[string]any) - secondContent := second["content"].([]any)[0].(map[string]any) - if first["id"] != nil || first["status"] != nil || firstContent["type"] != "output_text" || firstContent["annotations"] != nil { - t.Fatalf("assistant message history = %#v", first) + system := items[0].(map[string]any) + assistant := items[1].(map[string]any) + user := items[2].(map[string]any) + userContent := user["content"].([]any)[0].(map[string]any) + if system["role"] != "system" || system["content"] != "system instruction" { + t.Fatalf("system message history = %#v", system) } - if secondContent["type"] != "input_text" { - t.Fatalf("user message history = %#v", second) + if assistant["id"] != nil || assistant["status"] != nil || assistant["content"] != "Hi there" { + t.Fatalf("assistant message history = %#v", assistant) + } + if userContent["type"] != "input_text" { + t.Fatalf("user message history = %#v", user) } } @@ -169,7 +173,7 @@ func TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted(t *testing.T) user := items[0].(map[string]any) call := items[1].(map[string]any) output := items[2].(map[string]any) - if user["type"] != "message" || user["content"].([]any)[0].(map[string]any)["type"] != "input_text" { + if user["type"] != "message" || user["content"] != "hello" { t.Fatalf("user history = %#v", user) } if call["type"] != "function_call" || call["id"] != nil || call["status"] != nil || call["internal_chat_message_metadata_passthrough"] != nil { @@ -180,12 +184,13 @@ func TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted(t *testing.T) } } -func TestUnsupportedResponsesHistoryItemsBecomeBoundaries(t *testing.T) { +func TestNativeBuildHistoryItemsArePreservedAndSanitized(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ - {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"kept summary"}],"encrypted_content":"cipher"}, - {"type":"web_search_call","id":"ws_1","status":"completed"}, - {"type":"shell_call","call_id":"call_1","status":"completed","action":{"type":"exec","commands":["pwd"]}}, + {"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"Grok Build","sources":null},"phase":"commentary"}, + {"type":"shell_call","id":null,"call_id":"call_1","status":"completed","action":{"commands":["pwd"],"timeout_ms":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}}, + {"type":"shell_call_output","call_id":"call_1","output":[{"stdout":"/workspace\n","stderr":"","outcome":{"type":"exit","exit_code":0}}]}, + {"type":"code_interpreter_call","id":"ci_1","container_id":"container_1","status":"completed","code":"print(1)","outputs":null}, {"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]} ] }`), "grok-4.5") @@ -197,25 +202,28 @@ func TestUnsupportedResponsesHistoryItemsBecomeBoundaries(t *testing.T) { t.Fatal(err) } items := request["input"].([]any) - if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" { - t.Fatalf("reasoning history = %#v", items[0]) + webSearch := items[0].(map[string]any) + searchAction := webSearch["action"].(map[string]any) + if webSearch["type"] != "web_search_call" || webSearch["phase"] != nil || searchAction["sources"] != nil { + t.Fatalf("web search history = %#v", webSearch) } - for index, raw := range items[1:3] { - item := raw.(map[string]any) - text := item["content"].([]any)[0].(map[string]any)["text"].(string) - if item["type"] != "message" || item["role"] != "developer" || !strings.Contains(text, "Type: ") { - t.Fatalf("item %d was not downgraded: %#v", index+1, item) - } + shellCall := items[1].(map[string]any) + shellAction := shellCall["action"].(map[string]any) + if shellCall["type"] != "shell_call" || shellCall["id"] != nil || shellAction["timeout_ms"] != nil || shellAction["internal_chat_message_metadata_passthrough"] != nil { + t.Fatalf("shell call history = %#v", shellCall) } - if items[3].(map[string]any)["role"] != "user" { - t.Fatalf("user message changed unexpectedly: %#v", items[3]) + if items[2].(map[string]any)["type"] != "shell_call_output" || items[3].(map[string]any)["type"] != "code_interpreter_call" || items[3].(map[string]any)["outputs"] != nil { + t.Fatalf("native tool history = %#v", items[2:4]) + } + if items[4].(map[string]any)["role"] != "user" { + t.Fatalf("user message changed unexpectedly: %#v", items[4]) } } -func TestNullEncryptedReasoningBecomesBoundary(t *testing.T) { +func TestReasoningWithoutEncryptedContentRemainsNative(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ - {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}, {"type":"message","role":"user","content":[{"type":"input_text","text":"嗯"}]} ] @@ -229,22 +237,66 @@ func TestNullEncryptedReasoningBecomesBoundary(t *testing.T) { } items := request["input"].([]any) first := items[0].(map[string]any) - text := first["content"].([]any)[0].(map[string]any)["text"].(string) - if first["type"] != "message" || first["role"] != "developer" || first["encrypted_content"] != nil || first["content"] == nil { - t.Fatalf("null reasoning should become boundary: %#v", first) + if first["type"] != "reasoning" || first["status"] != nil || first["encrypted_content"] != nil || first["content"] != nil { + t.Fatalf("reasoning history = %#v", first) } - if !strings.Contains(text, "who am I") || strings.Contains(text, "null") { - t.Fatalf("boundary text = %q", text) + summary := first["summary"].([]any)[0].(map[string]any) + if summary["text"] != "who am I" { + t.Fatalf("reasoning summary = %#v", first["summary"]) } - if items[1].(map[string]any)["content"].([]any)[0].(map[string]any)["type"] != "output_text" { + if items[1].(map[string]any)["content"] != "hi" { t.Fatalf("assistant history = %#v", items[1]) } } +func TestUnsupportedResponsesHistoryItemBecomesBoundary(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"type":"future_codex_item","id":"future_1","status":"completed"}, + {"type":"message","role":"user","content":"continue"} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + boundary := items[0].(map[string]any) + text := boundary["content"].([]any)[0].(map[string]any)["text"].(string) + if boundary["role"] != "developer" || !strings.Contains(text, "future_codex_item") || items[1].(map[string]any)["role"] != "user" { + t.Fatalf("normalized history = %#v", items) + } +} + +func TestMessageImageAndFileNullFieldsAreRemoved(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[{"type":"message","role":"user","content":[ + {"type":"input_image","image_url":"https://example.com/image.png","detail":null,"file_id":null}, + {"type":"input_file","file_id":"file_1","file_url":null,"filename":null} + ]}] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + content := request["input"].([]any)[0].(map[string]any)["content"].([]any) + image := content[0].(map[string]any) + file := content[1].(map[string]any) + if image["image_url"] == nil || image["detail"] != nil || image["file_id"] != nil || file["file_id"] != "file_1" || file["file_url"] != nil || file["filename"] != nil { + t.Fatalf("message content = %#v", content) + } +} + func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ - {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}],"encrypted_content":"cipher","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"plan"}],"encrypted_content":"cipher","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"function_call","id":"fc_1","call_id":"call_1","name":"shell_command","arguments":"{}","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"function_call_output","id":"fco_1","call_id":"call_1","output":"ok","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"custom_tool_call","id":"ctc_1","call_id":"call_2","name":"apply_patch","input":"patch","status":"completed","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, @@ -266,7 +318,7 @@ func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { } } items := request["input"].([]any) - if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" { + if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" || items[0].(map[string]any)["status"] != nil { t.Fatalf("reasoning history = %#v", items[0]) } if items[1].(map[string]any)["type"] != "function_call" || items[3].(map[string]any)["type"] != "function_call" { @@ -277,107 +329,6 @@ func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { } } -func TestStripExternalClientToolsKeepsFunctionBackedTools(t *testing.T) { - t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") - normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ - "model":"public","input":"hello", - "tools":[ - {"type":"function","name":"read_file","parameters":{"type":"object"}}, - {"type":"apply_patch"}, - {"type":"tool_search","execution":"client"}, - {"type":"web_search","external_web_access":false}, - {"type":"local_shell"} - ], - "tool_choice":{"type":"apply_patch"} - }`), "grok-4.5") - if err != nil { - t.Fatal(err) - } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "external_tools_omitted") { - t.Fatalf("compatibility warnings = %#v", compatibility) - } - var request map[string]any - if err := json.Unmarshal(normalized, &request); err != nil { - t.Fatal(err) - } - tools := request["tools"].([]any) - if len(tools) != 4 { - t.Fatalf("normalized tools = %#v choice=%#v", tools, request["tool_choice"]) - } - seen := map[string]bool{} - for _, rawTool := range tools { - tool := rawTool.(map[string]any) - switch tool["type"] { - case "function": - seen[tool["name"].(string)] = true - case "shell": - seen["shell"] = true - } - if tool["type"] == "web_search" { - t.Fatalf("web_search should be omitted: %#v", tools) - } - } - choice := request["tool_choice"].(map[string]any) - if !seen["read_file"] || !seen["grok2api_apply_patch"] || !seen["grok2api_tool_search"] || !seen["shell"] || - choice["type"] != "function" || choice["name"] != "grok2api_apply_patch" { - t.Fatalf("normalized tools = %#v choice=%#v", tools, request["tool_choice"]) - } - input := request["input"].([]any) - if input[0].(map[string]any)["role"] != "developer" || input[1].(map[string]any)["role"] != "user" { - t.Fatalf("input boundary = %#v", input) - } -} - -func TestStripExternalClientToolsRemovesStringToolChoice(t *testing.T) { - t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") - normalized, _, err := normalizeResponsesRequest([]byte(`{ - "model":"public","input":"hello", - "tools":[{"type":"web_search","external_web_access":false}], - "tool_choice":"auto" - }`), "grok-4.5") - if err != nil { - t.Fatal(err) - } - var request map[string]any - if err := json.Unmarshal(normalized, &request); err != nil { - t.Fatal(err) - } - if request["tools"] != nil || request["tool_choice"] != nil { - t.Fatalf("tools/tool_choice should be omitted: %#v", request) - } -} - -func TestStripExternalClientToolHistory(t *testing.T) { - t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") - normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ - "model":"public","input":[ - {"type":"web_search_call","id":"ws_1","status":"completed"}, - {"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}, - {"type":"function_call_output","call_id":"call_1","output":"done"}, - {"type":"message","role":"user","content":"next"} - ] - }`), "grok-4.5") - if err != nil { - t.Fatal(err) - } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "external_tool_history_omitted") { - t.Fatalf("compatibility warnings = %#v", compatibility) - } - var request map[string]any - if err := json.Unmarshal(normalized, &request); err != nil { - t.Fatal(err) - } - items := request["input"].([]any) - if items[0].(map[string]any)["role"] != "developer" { - t.Fatalf("input[0] = %#v", items[0]) - } - if items[1].(map[string]any)["type"] != "function_call" || - items[2].(map[string]any)["type"] != "function_call_output" || - items[3].(map[string]any)["role"] != "user" { - t.Fatalf("function history should be preserved: %#v", items) - } -} - func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) { _, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"hello", @@ -389,6 +340,33 @@ func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) { } } +func TestOptionalCompatibilityControlsAreIgnored(t *testing.T) { + normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ + "model":"public", + "tools":[{"type":"local_shell","display_width":120},{"type":"apply_patch","mode":"auto"}], + "input":[{"type":"additional_tools","role":"user","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]}] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + if compatibility == nil { + t.Fatal("兼容字段未触发归一化") + } + warnings := compatibility.warningHeader() + for _, expected := range []string{"legacy_local_shell_controls_ignored", "apply_patch_controls_ignored", "additional_tools_role_approximated"} { + if !strings.Contains(warnings, expected) { + t.Fatalf("warnings = %q", warnings) + } + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + if len(request["tools"].([]any)) != 3 { + t.Fatalf("tools = %#v", request["tools"]) + } +} + func TestApplyPatchToolRequestHistoryAndJSONResponse(t *testing.T) { normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"edit file", @@ -445,7 +423,7 @@ func TestApplyPatchToolRequestHistoryAndJSONResponse(t *testing.T) { t.Fatal(err) } items := request["input"].([]any) - if items[0].(map[string]any)["type"] != "function_call" || !strings.Contains(items[0].(map[string]any)["arguments"].(string), `"delete_file"`) { + if items[0].(map[string]any)["type"] != "function_call" || items[0].(map[string]any)["id"] != nil || items[0].(map[string]any)["status"] != nil || !strings.Contains(items[0].(map[string]any)["arguments"].(string), `"delete_file"`) { t.Fatalf("apply patch call history = %#v", items[0]) } if items[1].(map[string]any)["type"] != "function_call_output" || !strings.Contains(items[1].(map[string]any)["output"].(string), "failed") { diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index fb8b13d9..555d1c4c 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -20,8 +20,8 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] } param := fmt.Sprintf("input[%d]", index) itemType := strings.TrimSpace(stringField(item, "type")) - // Codex/OpenAI may omit type on role-bearing message items. Force a - // known type before rewrite so untyped objects never reach ModelInput. + // Codex/OpenAI 可能省略带 role 消息的 type;在重建前补成明确消息, + // 避免无类型对象直接进入 ModelInput。 if itemType == "" && strings.TrimSpace(stringField(item, "role")) != "" { itemType = "message" } @@ -48,10 +48,15 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] c.changed = true rewritten = append(rewritten, converted) case "reasoning": - converted, changed := sanitizeReasoningInput(item) - if changed { - c.changed = true - } + converted := sanitizeReasoningInput(item) + c.changed = true + rewritten = append(rewritten, converted) + case "file_search_call", "web_search_call", "image_generation_call", "code_interpreter_call", + "shell_call", "mcp_list_tools", "mcp_approval_request", "mcp_approval_response", "mcp_call", "compaction": + // 这些类型已进入 Grok Build 0.2.101 的 Responses InputItem 契约。 + // 仅清理 Codex 私有字段和 null,不能把原生调用降级成文本边界。 + converted := sanitizeNativeHistoryInput(item, itemType) + c.changed = true rewritten = append(rewritten, converted) case "tool_search_call": callID := strings.TrimSpace(stringField(item, "call_id")) @@ -189,10 +194,6 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] rewritten = append(rewritten, marker) default: if kind := strings.TrimSpace(stringField(item, "type")); kind != "" { - if c.stripExternal { - rewritten = append(rewritten, c.externalHistoryBoundary(item, kind)) - continue - } c.changed = true c.addWarning("unsupported_input_history_omitted") rewritten = append(rewritten, unsupportedInputHistoryBoundary(item, kind)) @@ -221,8 +222,8 @@ func (c *responsesToolCompatibility) normalizeFunctionCallInput(item map[string] if namespace != "" { name = c.alias(responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}) } - // CLIProxyAPI constructs function_call with only type/call_id/name/arguments. - // Extra fields (id/status/namespace/metadata) break Grok's untagged ModelInput. + // 按官方 Build 回放结构仅保留四个输入字段,避免输出态字段和私有元数据 + // 干扰 Grok 的 untagged ModelInput 反序列化。 return map[string]any{"type": "function_call", "call_id": callID, "name": name, "arguments": arguments}, nil } @@ -251,67 +252,98 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin }, nil } -func sanitizeReasoningInput(item map[string]any) (map[string]any, bool) { - // Grok Build's untagged ModelInput rejects null-valued fields and Codex - // private metadata. Only keep portable non-null reasoning fields. - // - // Codex may emit reasoning items with summary text but null - // encrypted_content (common when the model returns a summary-only item). - // Replaying that shape 422s, so fall back to a developer boundary that - // preserves the visible summary without claiming encrypted state. - encrypted, hasEncrypted := nonNullJSONValue(item["encrypted_content"]) - if !hasEncrypted || strings.TrimSpace(fmt.Sprint(encrypted)) == "" { - summary := reasoningSummaryText(item["summary"]) - text := "A prior model reasoning item was omitted because it has no portable encrypted_content for Grok Build." - if summary != "" { - text += "\nSummary:\n" + summary - } - return compatibilityBoundaryMessage(text), true +func sanitizeReasoningInput(item map[string]any) map[string]any { + // 官方 Grok Build 回放 reasoning 时会删除 output-only status,但会保留 + // id、summary、content 和可选 encrypted_content。密文不是回放的前置条件。 + converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") + converted["type"] = "reasoning" + if !hasPortableReasoningContent(converted) { + return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.") } - - converted := map[string]any{"type": "reasoning", "encrypted_content": cloneJSONValue(encrypted)} - for _, key := range []string{"id", "summary", "content", "status"} { - if value, ok := nonNullJSONValue(item[key]); ok { - converted[key] = cloneJSONValue(value) - } - } - return converted, true + return converted } -func nonNullJSONValue(value any) (any, bool) { - if value == nil { - return nil, false +func hasPortableReasoningContent(item map[string]any) bool { + if encrypted, ok := item["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" { + return true } - return value, true -} - -func reasoningSummaryText(raw any) string { - items, ok := raw.([]any) - if !ok { - return "" - } - parts := make([]string, 0, len(items)) - for _, rawItem := range items { - item, ok := rawItem.(map[string]any) - if !ok { - continue - } - if text := strings.TrimSpace(stringField(item, "text")); text != "" { - parts = append(parts, text) - } - } - return strings.Join(parts, "\n") -} - -func hasPrivateInputFields(item map[string]any) bool { - for _, key := range []string{"internal_chat_message_metadata_passthrough", "phase"} { - if _, exists := item[key]; exists { + for _, key := range []string{"summary", "content"} { + if values, ok := item[key].([]any); ok && len(values) > 0 { return true } } return false } +// sanitizeNativeHistoryInput 按 Grok Build 0.2.101 的原生 InputItem 字段重建历史, +// 避免 Codex 扩展元数据干扰 Rust untagged enum 的反序列化。 +func sanitizeNativeHistoryInput(item map[string]any, itemType string) map[string]any { + var fields []string + switch itemType { + case "file_search_call": + fields = []string{"id", "queries", "status", "results"} + case "web_search_call": + fields = []string{"action", "id", "status"} + case "image_generation_call": + fields = []string{"id", "result", "status"} + case "code_interpreter_call": + fields = []string{"code", "container_id", "id", "outputs", "status"} + case "shell_call": + fields = []string{"id", "call_id", "action", "status", "environment"} + case "mcp_list_tools": + fields = []string{"id", "server_label", "tools", "error"} + case "mcp_approval_request": + fields = []string{"arguments", "id", "name", "server_label"} + case "mcp_approval_response": + fields = []string{"approval_request_id", "approve", "id", "reason"} + case "mcp_call": + fields = []string{"arguments", "id", "name", "server_label", "approval_request_id", "error", "output", "status"} + case "compaction": + fields = []string{"id", "encrypted_content"} + } + converted := copyNonNullHistoryFields(item, fields...) + converted["type"] = itemType + return converted +} + +func copyNonNullHistoryFields(item map[string]any, fields ...string) map[string]any { + converted := make(map[string]any, len(fields)+1) + for _, key := range fields { + if value, ok := sanitizeHistoryJSONValue(item[key]); ok { + converted[key] = value + } + } + return converted +} + +func sanitizeHistoryJSONValue(value any) (any, bool) { + switch typed := value.(type) { + case nil: + return nil, false + case map[string]any: + cleaned := make(map[string]any, len(typed)) + for key, nested := range typed { + if key == "phase" || key == "internal_chat_message_metadata_passthrough" { + continue + } + if normalized, ok := sanitizeHistoryJSONValue(nested); ok { + cleaned[key] = normalized + } + } + return cleaned, true + case []any: + cleaned := make([]any, 0, len(typed)) + for _, nested := range typed { + if normalized, ok := sanitizeHistoryJSONValue(nested); ok { + cleaned = append(cleaned, normalized) + } + } + return cleaned, true + default: + return cloneJSONValue(value), true + } +} + func unsupportedInputHistoryBoundary(item map[string]any, kind string) map[string]any { parts := []string{"A prior Responses history item was omitted because Grok Build cannot deserialize this Codex item type.", "Type: " + kind} for _, key := range []string{"id", "call_id", "name", "status"} { diff --git a/backend/internal/infra/provider/cli/responses_input.go b/backend/internal/infra/provider/cli/responses_input.go index e680177c..23e77e33 100644 --- a/backend/internal/infra/provider/cli/responses_input.go +++ b/backend/internal/infra/provider/cli/responses_input.go @@ -63,38 +63,57 @@ func normalizeMessageInput(item map[string]any, param string) (map[string]any, e if role == "" { role = "assistant" } - if role == "system" { - role = "developer" + if role == "model" { + role = "assistant" } content, err := normalizeMessageContent(item["content"], role, param+".content") if err != nil { return nil, err } - // Rebuild with an allowlist only. Codex private fields (phase, metadata - // passthrough, status/id) are intentionally dropped for Grok ModelInput. + // 仅按白名单重建,避免 Codex 的 phase、metadata、status、id 等 + // 非输入字段进入 Grok ModelInput。 return map[string]any{"type": "message", "role": role, "content": content}, nil } -func messageTextPartType(role string) string { - switch strings.ToLower(strings.TrimSpace(role)) { - case "assistant", "model": - // Match CLIProxyAPI / OpenAI Responses construction: assistant history - // uses output_text; user/developer use input_text. - return "output_text" - default: - return "input_text" - } -} - func normalizeMessageContent(value any, role, param string) (any, error) { - textPartType := messageTextPartType(role) if text, ok := value.(string); ok { - return []any{map[string]any{"type": textPartType, "text": text}}, nil + return text, nil } items, ok := value.([]any) if !ok { return nil, &responsesRequestError{Message: param + " 必须是字符串或数组", Param: param, Code: "invalid_parameter"} } + // 官方 Grok CLI 会把 assistant 的多个输出文本合并为 EasyInputMessage + // 字符串,既保留语义,也绕开 OutputMessage 对 id/status 的输入限制。 + if role == "assistant" { + texts := make([]string, 0, len(items)) + for _, raw := range items { + item, isObject := raw.(map[string]any) + if !isObject { + texts = nil + break + } + switch stringField(item, "type") { + case "text", "input_text", "output_text": + texts = append(texts, stringField(item, "text")) + case "refusal": + texts = append(texts, stringField(item, "refusal")) + default: + texts = nil + } + if texts == nil { + break + } + } + if texts != nil { + return strings.Join(texts, "\n"), nil + } + } + + textPartType := "input_text" + if role == "assistant" { + textPartType = "output_text" + } normalized := make([]any, 0, len(items)) for index, raw := range items { item, ok := raw.(map[string]any) @@ -103,7 +122,7 @@ func normalizeMessageContent(value any, role, param string) (any, error) { } switch stringField(item, "type") { case "text", "input_text", "output_text": - // Role-aware typing: do not coerce assistant output_text into input_text. + // 按角色重建文本类型,不能把 assistant 的 output_text 改成 input_text。 normalized = append(normalized, map[string]any{"type": textPartType, "text": stringField(item, "text")}) case "refusal": normalized = append(normalized, map[string]any{"type": textPartType, "text": stringField(item, "refusal")}) @@ -112,7 +131,7 @@ func normalizeMessageContent(value any, role, param string) (any, error) { case "input_file": normalized = append(normalized, normalizeInputFilePart(item)) default: - return nil, &responsesRequestError{Message: "Grok Build 0.2.99 不支持该 message.content 类型", Param: fmt.Sprintf("%s[%d].type", param, index), Code: "unsupported_parameter"} + return nil, &responsesRequestError{Message: "Grok Build 0.2.101 不支持该 message.content 类型", Param: fmt.Sprintf("%s[%d].type", param, index), Code: "unsupported_parameter"} } } return normalized, nil @@ -120,13 +139,13 @@ func normalizeMessageContent(value any, role, param string) (any, error) { func normalizeInputImagePart(item map[string]any) map[string]any { converted := map[string]any{"type": "input_image"} - if value, exists := item["image_url"]; exists { + if value, exists := item["image_url"]; exists && value != nil { converted["image_url"] = cloneJSONValue(value) - } else if value, exists := item["url"]; exists { + } else if value, exists := item["url"]; exists && value != nil { converted["image_url"] = cloneJSONValue(value) } for _, key := range []string{"detail", "file_id"} { - if value, exists := item[key]; exists { + if value, exists := item[key]; exists && value != nil { converted[key] = cloneJSONValue(value) } } @@ -136,7 +155,7 @@ func normalizeInputImagePart(item map[string]any) map[string]any { func normalizeInputFilePart(item map[string]any) map[string]any { converted := map[string]any{"type": "input_file"} for _, key := range []string{"file_data", "file_id", "filename", "file_url"} { - if value, exists := item[key]; exists { + if value, exists := item[key]; exists && value != nil { converted[key] = cloneJSONValue(value) } } diff --git a/backend/internal/infra/provider/cli/responses_tool_choice.go b/backend/internal/infra/provider/cli/responses_tool_choice.go index 94cb96d2..fbbb2492 100644 --- a/backend/internal/infra/provider/cli/responses_tool_choice.go +++ b/backend/internal/infra/provider/cli/responses_tool_choice.go @@ -11,11 +11,6 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json if isEmptyJSON(raw) { return nil } - if c.stripExternal && len(normalizedTools) == 0 { - delete(payload, "tool_choice") - c.changed = true - return nil - } if len(normalizedTools) == 0 { delete(payload, "tool_choice") c.changed = true @@ -39,12 +34,6 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json return nil } kind := stringField(object, "type") - if c.stripExternal && isExternalClientToolKind(kind) { - delete(payload, "tool_choice") - c.changed = true - c.addWarning("external_tool_choice_omitted") - return nil - } if c.webSearchDisabled && normalizeHostedToolChoiceKind(kind) == "web_search" && !hasToolType(normalizedTools, "web_search") { payload["tool_choice"] = mustJSON("none") c.changed = true diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 49905f08..2e2e7ec5 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -69,9 +69,6 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil { return nil, err } - if err := compatibility.addDroppedToolsBoundary(payload); err != nil { - return nil, err - } if !compatibility.changed { return nil, nil } @@ -155,10 +152,6 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl return nil, &responsesRequestError{Message: param + " 必须是对象", Param: param, Code: "invalid_parameter"} } kind := strings.TrimSpace(stringField(tool, "type")) - if c.stripExternal && isExternalClientToolKind(kind) { - c.dropExternalTool(tool, namespace) - return nil, nil - } switch kind { case "function": name := strings.TrimSpace(stringField(tool, "name")) @@ -251,7 +244,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl case "local_shell": return c.normalizeLegacyLocalShellTool(tool, param) case "apply_patch": - return c.normalizeApplyPatchTool(tool, namespace, param) + return c.normalizeApplyPatchTool(tool, param) case "x_search", "image_generation", "collections_search", "file_search", "code_execution", "code_interpreter": return c.normalizeNativeTool(tool, param) case "computer_use_preview": @@ -311,4 +304,3 @@ func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any "parameters": cloneJSONValue(parameters), }, nil } - diff --git a/backend/internal/infra/provider/cli/responses_tool_state.go b/backend/internal/infra/provider/cli/responses_tool_state.go index c8789199..015576d2 100644 --- a/backend/internal/infra/provider/cli/responses_tool_state.go +++ b/backend/internal/infra/provider/cli/responses_tool_state.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "os" "strings" ) @@ -49,8 +48,6 @@ type responsesToolCompatibility struct { warnings []string warningSet map[string]struct{} changed bool - stripExternal bool - droppedTools []string } // responsesRequestError 表示可直接映射为 OpenAI 错误结构的 Provider 请求错误。 @@ -68,99 +65,9 @@ func newResponsesToolCompatibility() *responsesToolCompatibility { identityAliases: make(map[string]string), streamCalls: make(map[string]*responsesStreamCall), warningSet: make(map[string]struct{}), - stripExternal: stripExternalClientTools(), } } - -func stripExternalClientTools() bool { - switch strings.ToLower(strings.TrimSpace(os.Getenv("GROK2API_STRIP_EXTERNAL_TOOLS"))) { - case "1", "true", "yes", "on": - return true - default: - return false - } -} - -func isExternalClientToolKind(kind string) bool { - switch strings.TrimSpace(kind) { - case "computer_use_preview", - "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26": - return true - default: - return false - } -} - -func (c *responsesToolCompatibility) dropExternalTool(tool map[string]any, namespace string) { - name := strings.TrimSpace(stringField(tool, "name")) - if name == "" { - name = strings.TrimSpace(stringField(tool, "server_label")) - } - if name == "" { - name = strings.TrimSpace(stringField(tool, "type")) - } - if namespace != "" && name != "" { - name = namespace + "." + name - } - if name != "" { - c.droppedTools = append(c.droppedTools, name) - } - c.changed = true - c.addWarning("external_tools_omitted") -} - -func (c *responsesToolCompatibility) externalHistoryBoundary(item map[string]any, label string) map[string]any { - c.changed = true - c.addWarning("external_tool_history_omitted") - name := strings.TrimSpace(stringField(item, "name")) - if name == "" { - name = strings.TrimSpace(stringField(item, "type")) - } - callID := strings.TrimSpace(stringField(item, "call_id")) - text := "External tool history omitted for Grok Build compatibility." - if label != "" { - text += "\nKind: " + label - } - if name != "" { - text += "\nName: " + name - } - if callID != "" { - text += "\nCall ID: " + callID - } - return compatibilityBoundaryMessage(text) -} - -func (c *responsesToolCompatibility) addDroppedToolsBoundary(payload map[string]json.RawMessage) error { - if !c.stripExternal || len(c.droppedTools) == 0 { - return nil - } - text := "Client-side external tools are not available through this Grok Build upstream. Continue without calling those tools." - boundary := compatibilityBoundaryMessage(text) - raw := payload["input"] - if isEmptyJSON(raw) { - payload["input"] = mustJSON([]any{boundary}) - return nil - } - var input any - if err := json.Unmarshal(raw, &input); err != nil { - return &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"} - } - switch typed := input.(type) { - case string: - payload["input"] = mustJSON([]any{ - boundary, - map[string]any{"type": "message", "role": "user", "content": typed}, - }) - case []any: - payload["input"] = mustJSON(append([]any{boundary}, typed...)) - default: - return &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"} - } - c.changed = true - return nil -} - func (c *responsesToolCompatibility) alias(identity responsesToolIdentity) string { key := identity.key() if alias, exists := c.identityAliases[key]; exists {