Http Status 401 Unauthorized, Response: {"error":{"message":"model or provider n...

2026年10月22日 15:05 23.73 秒 success

错误信息

调用Embedding失败: EmbedBatch API error: Http Status 401 Unauthorized, Response: {"error":{"message":"model or provider not exist","type":"bad_response_status_code","param":"","code":"bad_response_status_code"}}

AI 解决方案

🔍 报错分析

1. 🌐 错误翻译


原文:EmbedBatch API error: Http Status 401 Unauthorized, Response: {"error":{"message":"model or provider not exist","type":"bad_response_status_code","param":"","code":"bad_response_status_code"}}
译文:EmbedBatch API 错误:HTTP 状态码 401 未授权,响应:{"error":{"message":"模型或服务提供商不存在","type":"响应状态码异常","param":"","code":"响应状态码异常"}}

2. 🎯 原因分析


该错误的核心问题是模型或服务提供商配置无效,401未授权状态码表明请求未通过身份校验,结合“model or provider not exist”提示,具体原因通常为:
  • 调用Embedding时指定的模型名称不存在或未在当前平台注册

  • 使用的服务提供商未正确配置或未开通对应服务权限

  • 请求中未携带有效的鉴权信息,导致平台无法识别合法用户
  • 3. 💡 解决方案


    // 修复后的代码
    const { Embeddings } = require('@langchain/core/embeddings');
    
    // 1. 确认模型名称为平台支持的有效值(如 openai/text-embedding-3-small)
    // 2. 确保已配置正确的API密钥和服务提供商
    class CustomEmbeddings extends Embeddings {
      constructor({ apiKey, model = 'openai/text-embedding-3-small', baseUrl }) {
        super({ apiKey, model, baseUrl });
        // 验证配置完整性
        if (!apiKey || !model || !baseUrl) {
          throw new Error('Embedding配置缺失:需提供有效的apiKey、model、baseUrl');
        }
      }
    
      async embedDocuments(texts) {
        const response = await fetch(`${this.baseUrl}/v1/embeddings`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.apiKey}`, // 关键:正确携带鉴权信息
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: this.model, // 确保模型名与平台支持的一致
            input: texts
          })
        });
    
        if (response.status === 401) {
          throw new Error('鉴权失败或模型/服务商不存在,请检查配置');
        }
        const result = await response.json();
        return result.data.map(item => item.embedding);
      }
    }
    
    // 使用示例(确保参数为平台支持的有效值)
    const embeddings = new CustomEmbeddings({
      apiKey: 'your-valid-api-key', // 替换为有效的API密钥
      model: 'openai/text-embedding-3-small', // 替换为平台支持的模型名
      baseUrl: 'https://api.dmxapi.com' // 替换为平台提供的合法BaseURL
    });
    

    4. 🛡️ 预防措施


  • 配置校验前置:在初始化Embedding服务时,通过断言或工具函数校验模型名、服务商、API密钥的有效性,避免无效配置流入运行时。

  • 文档对照检查:调用前对照平台官方文档,确认支持的模型列表、服务商列表及鉴权方式,使用平台明确支持的配置项。
  • 推荐使用环境变量管理密钥(如process.env.DMXAPI_KEY),配合API调试工具(如Postman)先验证接口调用是否成功,再集成到业务代码中。