mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
fix: Messages API 兼容 messages 内联 system role (Claude Code)
Claude Code 等客户端会在 messages 数组中注入 role="system" (mid-conversation system instruction),当前 convertAnthropicMessages 直接拒绝,导致 /v1/messages 返回 400,无法在 Claude Code 中使用。 - convertAnthropicMessages: 抽取 messages 中的 system 消息文本, 与顶层 system 合并到 instructions,而非报错 - anthropicErrorJSON: 透传上游错误的 type/code, 替代笼统的 "Upstream request failed" - 新增 3 个单测覆盖内联 system、仅内联 system、未知 role 拒绝 Fixes #595
This commit is contained in:
1 parent
f55ca5a0c1
commit
982e27bc92
3 files changed
+106
-14
No files matched your search
@@ -73,6 +73,67 @@ func TestConvertAnthropicMessagesRequestToResponses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertAnthropicMessagesInlineSystemRole(t *testing.T) {
|
||||
// Claude Code 会在 messages 中注入 role="system"(mid-conversation system)。
|
||||
// 该 system 消息应被提取并合并到顶层 instructions,而不是报 400。
|
||||
body := []byte(`{
|
||||
"model":"public-chat","max_tokens":1024,
|
||||
"system":"Top-level rules.",
|
||||
"messages":[
|
||||
{"role":"system","content":"Inline directive."},
|
||||
{"role":"system","content":[{"type":"text","text":"Inline block."}]},
|
||||
{"role":"user","content":"hi"}
|
||||
]
|
||||
}`)
|
||||
converted, err := ConvertRequest(body, "grok-chat-fast", OperationMessages)
|
||||
if err != nil {
|
||||
t.Fatalf("inline system role should not fail: %v", err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(converted, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instructions, _ := payload["instructions"].(string); instructions != "Top-level rules.\n\nInline directive.\n\nInline block." {
|
||||
t.Fatalf("instructions = %q", instructions)
|
||||
}
|
||||
input := payload["input"].([]any)
|
||||
if len(input) != 1 {
|
||||
t.Fatalf("input should only contain the user message, got %#v", input)
|
||||
}
|
||||
if role := input[0].(map[string]any)["role"]; role != "user" {
|
||||
t.Fatalf("remaining input role = %v", role)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertAnthropicMessagesInlineSystemOnly(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model":"public-chat","max_tokens":256,
|
||||
"messages":[
|
||||
{"role":"system","content":"Only inline."},
|
||||
{"role":"user","content":"go"}
|
||||
]
|
||||
}`)
|
||||
converted, err := ConvertRequest(body, "grok-chat-fast", OperationMessages)
|
||||
if err != nil {
|
||||
t.Fatalf("inline-only system should not fail: %v", err)
|
||||
}
|
||||
var payload map[string]any
|
||||
_ = json.Unmarshal(converted, &payload)
|
||||
if payload["instructions"] != "Only inline." {
|
||||
t.Fatalf("instructions = %#v", payload["instructions"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertAnthropicMessagesRejectsUnknownRole(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model":"public-chat","max_tokens":256,
|
||||
"messages":[{"role":"tool","content":"nope"}]
|
||||
}`)
|
||||
if _, err := ConvertRequest(body, "grok-chat-fast", OperationMessages); err == nil {
|
||||
t.Fatal("unknown role should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertResponsesJSONToChatAndMessages(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"id":"resp_1","object":"response","created_at":123,"model":"grok-4.5","status":"completed",
|
||||
|
||||
@@ -249,7 +249,7 @@ func convertMessagesRequest(body []byte, model string) ([]byte, error) {
|
||||
if len(request.Messages) == 0 {
|
||||
return nil, errors.New("messages 必须是非空数组")
|
||||
}
|
||||
input, err := convertAnthropicMessages(request.Messages)
|
||||
input, inlineSystem, err := convertAnthropicMessages(request.Messages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -257,9 +257,19 @@ func convertMessagesRequest(body []byte, model string) ([]byte, error) {
|
||||
"model": model, "input": input, "stream": request.Stream,
|
||||
"max_output_tokens": request.MaxTokens,
|
||||
}
|
||||
if system, err := anthropicSystemText(request.System); err != nil {
|
||||
system, err := anthropicSystemText(request.System)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if system != "" {
|
||||
}
|
||||
// 合并顶层 system 与 messages 中内联的 system(Claude Code 会注入后者)。
|
||||
if inlineSystem != "" {
|
||||
if system != "" {
|
||||
system = system + "\n\n" + inlineSystem
|
||||
} else {
|
||||
system = inlineSystem
|
||||
}
|
||||
}
|
||||
if system != "" {
|
||||
target["instructions"] = system
|
||||
}
|
||||
copyOptionalNumber(target, "temperature", request.Temperature)
|
||||
@@ -333,12 +343,26 @@ type anthropicToolChoice struct {
|
||||
DisableParallelToolUse bool `json:"disable_parallel_tool_use"`
|
||||
}
|
||||
|
||||
func convertAnthropicMessages(messages []anthropicMessage) ([]any, error) {
|
||||
func convertAnthropicMessages(messages []anthropicMessage) ([]any, string, error) {
|
||||
input := make([]any, 0, len(messages))
|
||||
systemTexts := make([]string, 0)
|
||||
for _, message := range messages {
|
||||
role := strings.ToLower(strings.TrimSpace(message.Role))
|
||||
if role != "user" && role != "assistant" {
|
||||
return nil, fmt.Errorf("Messages API 不支持 role=%q", message.Role)
|
||||
// Claude Code 等客户端会在 messages 中注入 role="system"
|
||||
// (mid-conversation system)。抽取其文本,合并到顶层 instructions,
|
||||
// 而不是直接拒绝。
|
||||
if role == "system" {
|
||||
text, err := anthropicSystemText(message.Content)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if text != "" {
|
||||
systemTexts = append(systemTexts, text)
|
||||
}
|
||||
continue
|
||||
}
|
||||
return nil, "", fmt.Errorf("Messages API 不支持 role=%q", message.Role)
|
||||
}
|
||||
var text string
|
||||
if json.Unmarshal(message.Content, &text) == nil {
|
||||
@@ -347,7 +371,7 @@ func convertAnthropicMessages(messages []anthropicMessage) ([]any, error) {
|
||||
}
|
||||
var blocks []map[string]json.RawMessage
|
||||
if json.Unmarshal(message.Content, &blocks) != nil {
|
||||
return nil, errors.New("Messages content 必须是字符串或内容块数组")
|
||||
return nil, "", errors.New("Messages content 必须是字符串或内容块数组")
|
||||
}
|
||||
messageParts := make([]any, 0, len(blocks))
|
||||
flushMessage := func() {
|
||||
@@ -363,13 +387,13 @@ func convertAnthropicMessages(messages []anthropicMessage) ([]any, error) {
|
||||
case "text":
|
||||
var value string
|
||||
if json.Unmarshal(block["text"], &value) != nil {
|
||||
return nil, errors.New("text block 无效")
|
||||
return nil, "", errors.New("text block 无效")
|
||||
}
|
||||
messageParts = append(messageParts, map[string]any{"type": "input_text", "text": value})
|
||||
case "image":
|
||||
imageURL, err := anthropicImageURL(block["source"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
messageParts = append(messageParts, map[string]any{"type": "input_image", "image_url": imageURL})
|
||||
case "tool_use":
|
||||
@@ -380,7 +404,7 @@ func convertAnthropicMessages(messages []anthropicMessage) ([]any, error) {
|
||||
Input map[string]any `json:"input"`
|
||||
}
|
||||
if encoded, _ := json.Marshal(block); json.Unmarshal(encoded, &value) != nil || value.ID == "" || value.Name == "" {
|
||||
return nil, errors.New("tool_use block 无效")
|
||||
return nil, "", errors.New("tool_use block 无效")
|
||||
}
|
||||
arguments, _ := json.Marshal(value.Input)
|
||||
input = append(input, map[string]any{"type": "function_call", "call_id": value.ID, "name": value.Name, "arguments": string(arguments)})
|
||||
@@ -389,20 +413,20 @@ func convertAnthropicMessages(messages []anthropicMessage) ([]any, error) {
|
||||
var toolUseID string
|
||||
_ = json.Unmarshal(block["tool_use_id"], &toolUseID)
|
||||
if toolUseID == "" {
|
||||
return nil, errors.New("tool_result 缺少 tool_use_id")
|
||||
return nil, "", errors.New("tool_result 缺少 tool_use_id")
|
||||
}
|
||||
output, err := anthropicToolResult(block["content"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
input = append(input, map[string]any{"type": "function_call_output", "call_id": toolUseID, "output": output})
|
||||
default:
|
||||
return nil, fmt.Errorf("当前不支持 Anthropic content.type=%q", typeName)
|
||||
return nil, "", fmt.Errorf("当前不支持 Anthropic content.type=%q", typeName)
|
||||
}
|
||||
}
|
||||
flushMessage()
|
||||
}
|
||||
return input, nil
|
||||
return input, strings.Join(systemTexts, "\n\n"), nil
|
||||
}
|
||||
|
||||
func anthropicSystemText(raw json.RawMessage) (string, error) {
|
||||
|
||||
@@ -189,11 +189,18 @@ func anthropicUsage(value responseUsage) map[string]any {
|
||||
|
||||
func anthropicErrorJSON(value any) []byte {
|
||||
message := "Upstream request failed"
|
||||
errorType := "api_error"
|
||||
if object, ok := value.(map[string]any); ok {
|
||||
if text, ok := object["message"].(string); ok && text != "" {
|
||||
message = text
|
||||
}
|
||||
// 透传上游错误类型/代码,便于定位(限流、鉴权、转换失败等)。
|
||||
if text, ok := object["type"].(string); ok && text != "" {
|
||||
errorType = text
|
||||
} else if text, ok := object["code"].(string); ok && text != "" {
|
||||
errorType = text
|
||||
}
|
||||
}
|
||||
data, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": "api_error", "message": message}})
|
||||
data, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": errorType, "message": message}})
|
||||
return data
|
||||
}
|
||||
Reference in new issue
Block a user