Skip to content

Commit 5d7e547

Browse files
authored
fix: reorder tool and user messages for OpenAI API compatibility (#168) (#177)
Fixes #168 OpenAI requires that an assistant message with tool_calls be immediately followed by tool messages. Previously, convertInternalUserMessage output user content before tool results, causing 400 errors. Now tool messages are pushed first.
1 parent 4e1e681 commit 5d7e547

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

src/services/api/openai/convertMessages.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,15 @@ function convertInternalUserMessage(
9292
}
9393
}
9494

95+
// CRITICAL: tool messages must come BEFORE any user message in the result.
96+
// OpenAI API requires that a tool message immediately follows the assistant
97+
// message with tool_calls. If we emit a user message first, the API will
98+
// reject the request with "insufficient tool messages following tool_calls".
99+
// See: https://github.com/anthropics/claude-code/issues/xxx
100+
for (const tr of toolResults) {
101+
result.push(convertToolResult(tr))
102+
}
103+
95104
// 如果有图片,构建多模态 content 数组
96105
if (imageParts.length > 0) {
97106
const multiContent: Array<{ type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }> = []
@@ -109,10 +118,6 @@ function convertInternalUserMessage(
109118
content: textParts.join('\n'),
110119
} satisfies ChatCompletionUserMessageParam)
111120
}
112-
113-
for (const tr of toolResults) {
114-
result.push(convertToolResult(tr))
115-
}
116121
}
117122

118123
return result

0 commit comments

Comments
 (0)