HTTP 404: Invalid URL (POST /v1/chat/completions/chat/completions)

2026年02月23日 18:04 processing

错误信息

HTTP 404: Invalid URL (POST /v1/chat/completions/chat/completions)

AI 解决方案

代码报错分析报告


原文:HTTP 404: Invalid URL (POST /v1/chat/completions/chat/completions)
译文:HTTP 404:无效的URL(POST请求路径为 /v1/chat/completions/chat/completions)

分析
这是一个典型的 HTTP 404 错误,表示客户端请求的资源在服务器上不存在。具体原因:

  • URL路径重复:请求路径 /v1/chat/completions/chat/completions 中出现了重复的 chat/completions 片段

  • API端点错误:正确的OpenAI API聊天完成端点应该是 /v1/chat/completions,而不是重复的路径

  • 客户端配置问题:可能是代码中拼接URL时出现了逻辑错误,导致路径 解决方案

  • 根据不同的技术栈,修复方法如下:

    Python (requests库)


    # ❌ 错误的代码
    url = "https://api.openai.com/v1/chat/completions/chat/completions"
    
    # ✅ 修复后的代码
    url = "https://api.openai.com/v1/chat/completions"
    
    # 完整的请求示例
    import requests
    import json
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer YOUR_API_KEY"
    }
    
    data = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Hello!"}]
    }
    
    response = requests.post(url, headers=headers, json=data)
    

    JavaScript/Node.js


    // ❌ 错误的代码
    const url = 'https://api.openai.com/v1/chat/completions/chat/completions';
    
    // ✅ 修复后的代码
    const url = 'https://api.openai.com/v1/chat/completions';
    
    // 使用fetch的示例
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer YOUR_API_KEY`
        },
        body: JSON.stringify({
            model: 'gpt-3.5-turbo',
            messages: [{ role: 'user', content: 'Hello!' }]
        })
    });
    

    ##### 1. 使用环境变量或配置文件
    将API端点URL存储在配置文件中,避免硬编码:

    # config.py
    API_BASE_URL = "https://api.openai.com/v1"
    CHAT_ENDPOINT = f"{API_BASE_URL}/chat/completions"
    

    2. URL构建最佳实践


  • 使用专门的URL构建函数

  • 添加日志记录,在发送请求前打印完整的URL

  • 使用API客户端库(如openai-python库)而不是手动构建URL

3. 推荐工具


  • Postman/Insomnia:先测试API端点再集成到代码中

  • API调试中间件:在开发环境中添加请求/响应日志中间件

  • 单元测试:编写测试验证URL构建的正确性

  • 错误是由于URL路径重复导致的404错误。检查代码中URL拼接逻辑,确保使用正确的API端点路径 /v1/chat/completions