Error from Custom OpenAI: AI_TypeValidationError: Type validation failed: Value:...

2025年12月30日 23:53 状态: processing

🚨 错误信息

API Error: Error from Custom OpenAI: AI_TypeValidationError: Type validation failed: Value: {"type":"message_start","message":{"id":"msg_01RzQ5q32HLYvkNYqT6RzkCs","type":"message","model":"claude-sonnet-4-5-20250929","usage":{"input_tokens":85,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"claude_cache_creation_5_m_tokens":0,"claude_cache_creation_1_h_tokens":0},"role":"assistant","content":[]}}. Error message: [{"code":"invalid_union","errors":[[{"expected":"array","code":"invalid_type","path":["choices"],"message":"Invalid input: expected array, received undefined"}],[{"expected":"object","code":"invalid_type","path":["error"],"message":"Invalid input: expected object, received undefined"}]],"path":[],"message":"Invalid input"}]

🤖 AI解决方案

代码糕手 - 专业报错分析助理

错误翻译

原文: invalid_union with errors: Invalid input: expected array, received undefined for choices and Invalid input: expected object, received undefined for error

译文: 无效的联合类型验证失败:choices 字段期望是数组类型,但接收到的是 undefinederror 字段期望是对象类型,但接收到的是 undefined

原因分析

这是一个 API 响应格式验证错误,根本原因是:

  • 类型验证失败:AI 服务返回的数据结构不符合预期的联合类型(union type)要求

  • 字段缺失

  • - choices 字段应该是数组类型,但实际返回为 undefined
    - error 字段应该是对象类型,但实际返回为 undefined
  • 数据源问题:从返回的原始数据看,Claude API 返回的是 message_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 兼容性检查


  • 在使用第三方 API 时,务必确认返回格式是否符合你的类型定义

  • 对于流式响应(如 Claude),需要特殊的事件流处理逻辑,不能直接套用 OpenAI 的格式
  • 2. 防御性编程


  • 在类型验证前添加空值检查

  • 使用 TypeScript 或类似的类型系统时,为可选字段添加 ? 标记

  • 实现更灵活的类型适配器来处理不同 API 的响应格式
  • 推荐工具:


  • PostmanInsomnia:用于测试 API 响应格式

  • ZodJoi:用于运行时类型验证,提供更详细的错误信息

  • TypeScript:编译时类型检查,提前发现类型不匹配问题