Error from Custom OpenAI: AI_TypeValidationError: Type validation failed: Value:...
🚨 错误信息
🤖 AI解决方案
代码糕手 - 专业报错分析助理
错误翻译
原文: invalid_union with errors: Invalid input: expected array, received undefined for choices and Invalid input: expected object, received undefined for error
译文: 无效的联合类型验证失败:choices 字段期望是数组类型,但接收到的是 undefined;error 字段期望是对象类型,但接收到的是 undefined
原因分析
这是一个 API 响应格式验证错误,根本原因是:
-
choices 字段应该是数组类型,但实际返回为 undefined-
error 字段应该是对象类型,但实际返回为 undefinedmessage_start 事件格式,而不是标准的 OpenAI 兼容格式解决方案
根据错误信息,需要调整 API 调用或数据处理逻辑:
javascript
// 方案1:如果是调用 OpenAI 兼容接口,确保返回正确的格式
const correctResponseFormat = {
choices: [
{
message: {
role: "assistant",
content: "这里是AI的回复内容"
}
}
],
// 或者如果有错误
error: {
message: "错误描述",
type: "错误类型"
}
};// 方案2:如果是处理 Claude API 的事件流,需要特殊处理
async function handleClaudeStreamResponse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
// Claude 的事件流格式与 OpenAI 不同
if (parsed.type === 'message_start') {
// 处理 message_start 事件
console.log('Message started:', parsed.message.id);
} else if (parsed.type === 'content_block_delta') {
// 处理内容块增量
console.log('Content delta:', parsed.delta.text);
}
} catch (e) {
console.error('Parse error:', e);
}
}
}
}
}
##️ 预防措施
1. API 兼容性检查
2. 防御性编程
? 标记