Error code: 404 - {'error': {'message': 'Invalid URL (POST /v1/messages/chat/com...

2026年01月16日 14:19 processing

错误信息

openai.NotFoundError: Error code: 404 - {'error': {'message': 'Invalid URL (POST /v1/messages/chat/completions)', 'type': 'invalid_request_error', 'code': ''}}

AI 解决方案

错误分析

1.翻译


原文:Invalid URL (POST /v1/messages/chat/completions)
译文:无效的URL (POST /v1/messages/chat/completions)

2 原因分析


这个404错误表明使用了错误的API端点URL。主要原因是:
  • 端点路径错误:使用了 /v1/messages/chat/completions,但OpenAI的正确端点应该是 /v1/chat/completions

  • URL拼接错误:可能是URL构建时路径拼写错误,或者使用了过时的API文档
  • 解决方案


    将API端点URL更正为OpenAI官方的正确格式:

    # 错误示例(不要使用):
    # response = openai.ChatCompletion.create(
    #     model="gpt-3.5-turbo",
    #     messages=[{"role": "user", "content": "Hello"}]
    # )
    
    # 正确使用方式:
    import openai
    
    openai.api_key = "your-api-key-here"
    
    # 如果使用openai包的直接调用
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Hello"}]
    )
    
    # 如果使用requests库手动调用API
    import requests
    
    headers = {
        "Authorization": f"Bearer your-api-key-here",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Hello"}]
    }
    
    response = requests.post(
        "https://api.openai.com/v1/chat/completions",  # ✅ 正确端点
        headers=headers,
        json=data
    )
    

    4.措施

    ###:

  • 使用官方文档:始终参考[OpenAI官方API文档](https://platform.openai.com/docs/api-reference/chat),避免使用过时的示例代码

  • 库版本检查:确保使用最新版的OpenAI Python包,旧版本可能有不同的API调用方式
  • 工具推荐:

  • 使用OpenAI官方Python库:pip install openai

  • API测试工具:Postman或curl命令快速验证端点

  • 版本兼容性检查:pip show openai 查看当前安装版本
  • 如果仍有问题,请提供更详细的代码片段,我会帮您进一步分析。