fix:解决使用claude code发起请求是422问题#224
Conversation
|
Thank you for your pull request and welcome to our community. We could not parse the GitHub identity of the following contributors: ryan.liu.
|
|
解决bug #190 |
根本原因: AnthropicMessage.role 字段被定义为 Literal["user", "assistant"],但 Claude Code 发送的请求在 messages 数组中包含了 role: "system" 的消息,触发了 FastAPI Pydantic 验证失败(422)。 修复内容: 1. models_anthropic.py:190 — 将 role: Literal["user", "assistant"] 改为 role: str,接受任意角色值(包括 system)。 2. converters_anthropic.py:453-478 — 在 anthropic_to_kiro() 中预处理消息数组,将 role: "system" 的消息提取出来,追加到 system prompt 末尾,其余消息正常转换。 这样 system 角色消息的内容会被正确合并到系统提示中,不会破坏 Kiro API 对消息格式的要求。
|
Thanks for the PR! 🎉 Before merge, we need a one-time CLA confirmation. Full CLA text: Please reply once with: You need to write once, all further messages from me can be ignored. |
|
I have read the CLA and I accept its terms |
I have read the CLA and I accept its terms |
|
Thanks for the PR! 🎉 Before merge, we need a one-time CLA confirmation. Full CLA text: Please reply once with: You need to write once, all further messages from me can be ignored. |
Claude Code 接入问题修复说明
问题1:Claude Code 发起请求返回 422
根本原因
AnthropicMessage.role字段被定义为:但 Claude Code 实际发送的请求中,
messages数组包含:{ "role": "system", "content": "..." }由于
system不在允许范围内,触发 FastAPI + Pydantic 参数校验失败,返回:422 Unprocessable Entity修复内容
1. models_anthropic.py
文件位置:
修改前:
修改后:
允许接收任意角色值(包括
system)。2. converters_anthropic.py
文件位置:
在
anthropic_to_kiro()中增加预处理逻辑:messagesrole == "system"的消息伪代码:
修复效果
system消息不再触发 422system内容能够正确合并到系统提示词中问题2:Claude Code Web Search 历史导致 422
问题描述
当 Claude Code 对话历史中包含 Anthropic 服务端工具(Web Search)的调用记录时,网关返回:
422 Unprocessable Entity请求无法继续处理。
根本原因
Claude Code 会在:
messages[].content中携带服务端工具相关内容块。
典型类型包括:
1. server_tool_use
助手发起 Web Search:
{ "type": "server_tool_use", "name": "web_search", ... }2. web_search_tool_result
搜索结果返回:
{ "type": "web_search_tool_result", ... }而当前模型定义:
ContentBlock仅支持以下类型:
即:
对于:
完全无法识别。
因此 Pydantic 在解析
ContentBlock Union时直接失败,最终返回:422修复内容
1. 新增服务端工具内容块模型
文件:
新增:
ServerToolUseContentBlock用于支持:
{ "type": "server_tool_use" }新增:
WebSearchToolResultContentBlock用于支持:
{ "type": "web_search_tool_result" }2. 增加未知类型兜底模型
新增:
UnknownContentBlock定义:
特点:
type3. 更新 ContentBlock Union
修改后:
其中:
UnknownContentBlock放在最后。
为什么不会丢失信息
转换逻辑:
本身采用:
进行显式匹配处理。
当前仅消费:
对于无法识别的类型:
continue直接忽略。
Claude Code 的特殊行为
在每个:
{ "type": "web_search_tool_result" }之后,Claude Code 还会附带:
{ "type": "text", "text": "搜索结果内容..." }因此:
text最终效果
修复后:
能够通过模型校验。
转换器继续读取后续:
内容。
因此:
测试覆盖
新增测试类:
TestServerToolContentBlocks覆盖内容:
1. 服务端工具块解析
验证:
能够正确通过校验。
2. UnknownContentBlock 兜底能力
验证未来新增类型,例如:
不会再次导致:
4223. 端到端验证
构造与 Claude Code 实际请求一致的 Payload:
{ "messages": [ ... ] }验证:
测试结果
通过:
共:
全部通过。
同时:
全部通过。
无新增失败用例。
注意事项
本次修复属于 Claude Code Payload 兼容性增强。
修复目标:
role: "system"消息兼容性: