] API错误 (400 ): { "error": { "message": "Invalid param: Message format error, in...
🚨 错误信息
🤖 AI解决方案
1. 错误翻译
原文:Invalid param: Message format error, index[6] should be [tool] but is [user]
译文:参数无效:消息格式错误,索引[6]处的消息角色应为[tool]但实际是[user]
2. 原因分析
根本原因: 您向LLM API发送的消息数组(messages)中,第7条消息(索引从0开始)的角色(role)字段不正确。API期望这是一个tool角色的消息(通常指函数调用或工具调用的响应),但实际发送的是user角色的消息。
错误位置:
C:\Users\SOMA\Desktop\my-neuro-6.0.6\live-2d\js\ai\llm-client.js:81:17LLMClient.chatCompletion上下文分析:
这是典型的OpenAI API(或兼容API)函数调用/工具调用工作流程中的格式错误。当AI模型请求调用工具(tool_call)后,您需要以tool角色的消息回复工具执行结果。
3. 解决方案
修复代码示例
javascript
// 错误示例:
const messages = [
{ role: "user", content: "查询天气" },
{ role: "assistant", content: null, tool_calls: [{...}] }, // AI请求调用工具
{ role: "user", content: "工具执行结果..." } // ❌ 错误:应该是tool角色
];// 正确修复:
const messages = [
{ role: "user", content: "查询天气" },
{ role: "assistant", content: null, tool_calls: [{...}] },
{ role: "tool", content: "工具执行结果...", tool_call_id: "call_xxx" } // ✅ 正确:使用tool角色
];
// 在llm-client.js或相关文件中:
async function chatCompletion(messages) {
// 确保工具调用回复格式正确
const formattedMessages = messages.map((msg, index) => {
if (index > 0 &&
messages[index-1].role === "assistant" &&
messages[index-1].tool_calls &&
messages[index-1].tool_calls.length > 0) {
// 如果上一条是助手且有工具调用,这条应该是tool角色
return {
role: "tool",
content: msg.content,
tool_call_id: msg.tool_call_id || determineToolCallId(messages[index-1])
};
}
return msg;
});
// 使用formattedMessages调用API
// ...
}
快速修复步骤:
chatCompletion时传递的messages数组- 如果这是一条工具执行结果的回复,将
role从"user"改为"tool"- 添加必要的
tool_call_id字段,该ID应与助手消息中的tool_calls.id对应4. ️ 预防措施
最佳实践建议:
``
javascript
function validateMessages(messages) {
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
if (msg.role === "tool") {
if (!msg.tool_call_id) {
console.warn(Warning: tool message at index ${i} missing tool_call_id);
}
if (i === 0 || messages[i-1].role !== "assistant" ||
!messages[i-1].tool_calls) {
console.warn(Warning: tool message at index ${i} may be misplaced);
}
}
}
}
使用类型检查工具:如果使用TypeScript,定义严格的接口
typescript
interface Message {
role: "system" | "user" | "assistant" | "tool";
content: string | null;
tool_call_id?: string; // 仅当role="tool"时必需
tool_calls?: ToolCall[]; // 仅当role="assistant"时可能存在
}
` 推荐工具:
API调试工具:使用Postman或curl直接测试API调用,验证消息格式
日志增强:在 llm-client.js`中添加详细的请求日志,记录完整的消息数组结构---
关键点:OpenAI的聊天