错误信息: Type validation failed: Value: {"id":"chatcmpl-d3340af5-e0c3-4996-9faf-036...

2025年12月15日 21:55 状态: processing

🚨 错误信息

错误名称: AI_TypeValidationError 错误信息: Type validation failed: Value: {"id":"chatcmpl-d3340af5-e0c3-4996-9faf-036dad058cab","object":"","created":0,"model":"Qwen/Qwen3-235B-A22B-Thinking-2507","system_fingerprint":"","choices":null,"usage":{"prompt_tokens":0,"completion_tokens":0,"total_tokens":0}}. Error message: [{"code":"invalid_union","errors":[[{"expected":"array","code":"invalid_type","path":["choices"],"message":"Invalid input"}],[{"expected":"object","code":"invalid_type","path":["error"],"message":"Invalid input"}]],"path":[],"message":"Invalid input"}] 堆栈信息: AI_TypeValidationError: Type validation failed: Value: {"id":"chatcmpl-d3340af5-e0c3-4996-9faf-036dad058cab","object":"","created":0,"model":"Qwen/Qwen3-235B-A22B-Thinking-2507","system_fingerprint":"","choices":null,"usage":{"prompt_tokens":0,"completion_tokens":0,"total_tokens":0}}. Error message: [{"code":"invalid_union","errors":[[{"expected":"array","code":"invalid_type","path":["choices"],"message":"Invalid input"}],[{"expected":"object","code":"invalid_type","path":["error"],"message":"Invalid input"}]],"path":[],"message":"Invalid input"}] at Object.validate (file:///C:/Users/OMEN/AppData/Local/Programs/Cherry%20Studio/resources/app.asar/out/renderer/assets/dist-gixTQuVo.js:4868:11) at async safeValidateTypes (file:///C:/Users/OMEN/AppData/Local/Programs/Cherry%20Studio/resources/app.asar/out/renderer/assets/dist-gixTQuVo.js:4894:18) at async safeParseJSON (file:///C:/Users/OMEN/AppData/Local/Programs/Cherry%20Studio/resources/app.asar/out/renderer/assets/dist-gixTQuVo.js:4943:10) at async Object.transform (file:///C:/Users/OMEN/AppData/Local/Programs/Cherry%20Studio/resources/app.asar/out/renderer/assets/dist-gixTQuVo.js:4969:22) 错误原因: [ { "code": "invalid_union", "errors": [ [ { "expected": "array", "code": "invalid_type", "path": [ "choices" ], "message": "Invalid input" } ], [ { "expected": "object", "code": "invalid_type", "path": [ "error" ], "message": "Invalid input" } ] ], "path": [], "message": "Invalid input" } ]

🤖 AI解决方案

报错分析报告

1. 错误翻译

原文:Type validation failed: Value: {...}
译文:类型验证失败:值:{...}

原文:Error message: [{"code":"invalid_union","errors":[[{"expected":"array","code":"invalid_type","path":["choices"],"message":"Invalid input"}],[{"expected":"object","code":"invalid_type","path":["error"],"message":"Invalid input"}]],"path":[],"message":"Invalid input"}]
译文:错误信息:[{"code":"无效联合类型","errors":[[{"expected":"数组","code":"无效类型","path":["choices"],"message":"无效输入"}],[{"expected":"对象","code":"无效类型","path":["error"],"message":"无效输入"}]],"path":[],"message":"无效输入"}]

2. 原因分析

根本原因:API响应数据结构不符合预期的类型验证要求。

具体分析

  • 系统期望 choices 字段是一个数组(array),但实际收到的值是 null

  • 系统期望 error 字段是一个对象(object),但实际响应中可能缺少此字段

  • 这是典型的数据验证失败,说明从AI服务(Qwen模型)返回的响应格式与客户端代码预期的OpenAI兼容格式不匹配
  • 错误位置:在Cherry Studio应用程序中处理AI API响应时发生的类型验证错误,具体在 transform 函数调用链中。

    3. 解决方案

    根据错误信息,需要确保API响应符合OpenAI兼容格式:
    // 预期的响应格式示例
    {
      "id": "chatcmpl-d3340af5-e0c3-4996-9faf-036dad058cab",
      "object": "chat.completion",
      "created": 1677652288,
      "model": "Qwen/Qwen3-235B-A22B-Thinking-2507",
      "system_fingerprint": "fp_123456",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "这里是AI的回复内容"
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 10,
        "completion_tokens": 20,
        "total_tokens": 30
      }
    }
    
    // 或者,如果发生错误,应该返回:
    {
      "error": {
        "message": "错误描述",
        "type": "api_error",
        "code": "error_code"
      }
    }

    修复步骤

  • 检查AI服务端:确保Qwen模型的API响应格式正确

  • 验证响应数据:在客户端添加响应验证逻辑

  • 修复代码示例
  • // 在API调用后添加验证逻辑
    async function callAIService(prompt) {
      try {
        const response = await fetch(apiEndpoint, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            model: 'Qwen/Qwen3-235B-A22B-Thinking-2507',
            messages: [{ role: 'user', content: prompt }],
            stream: false
          })
        });
    
        const data = await response.json();
        
        // 验证响应格式
        if (data.error) {
          // 错误响应格式
          throw new Error(`API Error: ${data.error.message}`);
        }
        
        if (!data.choices || !Array.isArray(data.choices) || data.choices.length === 0) {
          // 确保choices是有效数组
          throw new Error('Invalid response: choices must be a non-empty array');
        }
        
        return data;
      } catch (error) {
        console.error('API call failed:', error);
        throw error;
      }
    }

    4. ️ 预防措施

    最佳实践:

  • 使用TypeScript或类型检查
  •    interface OpenAIResponse {
         id: string;
         object: string;
         created: number;
         model: string;
         choices: Array<{
           index: number;
           message: {
             role: string;
             content: string;
           };
           finish_reason: string;
         }>;
         usage: {
           prompt_tokens: number;
           completion_tokens: number;
           total_tokens: number;
         };
       }
    
       interface OpenAIError {
         error: {
           message: string;
           type: string;
           code: string;
         };
       }
       

  • 实现响应验证中间件

  •    function validateAIResponse(response) {
         // 验证必需字段
         const requiredFields = ['id', 'model', 'choices'];
         for (const field of requiredFields) {
           if (!response[field]) {
             throw new Error(`Missing required field: ${field}`);
           }
         }
         
         // 验证choices是否为数组
         if (!Array.isArray(response.choices)) {
           throw new Error('choices must be an array');
         }
       }
       

    ️ 推荐工具:

  • Zod:用于运行时类型验证的TypeScript优先模式库
  • AJV:快速的JSON模式验证器
  • Joi:功能强大的对象模式验证库
  • 开发建议:

  • 在开发阶段启用严格的数据验证
  • 为API响应编写详细的接口定义
  • 使用try-catch包装所有外部API调用
  • 添加详细的日志记录,记录完整的请求和响应