You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GPT-3迁移至GPT-3.5 API触发Invalid URL错误,请求技术排查

问题分析

错误Invalid URL (POST /v1/engines/gpt-3.5-turbo/chat/completions)的核心原因是:你混用了OpenAI的两种API接口——gpt-3.5-turbo是聊天模型,必须使用ChatCompletion接口,但你代码里用的是给文本补全模型(如text-davinci-003)设计的Completion接口,两者的API端点、参数格式完全不兼容。

修复代码

替换原来的ai_chat.py内容:

import asyncio
import openai
import functools
from concurrent.futures import ThreadPoolExecutor

openai.api_key = "AI KEY GOES HERE"
loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor()

def _generate_response_sync(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": prompt}
        ],
        max_tokens=150,
        n=1,
        temperature=0.5,
    )
    return response.choices[0].message['content'].strip()

async def generate_response(prompt):
    response = await loop.run_in_executor(executor, functools.partial(_generate_response_sync, prompt))
    return response
核心修改说明
  • 接口替换:把openai.Completion.create()改成openai.ChatCompletion.create()
  • 参数调整:
    • 用model参数指定模型(聊天模型不再用engine)
    • 移除prompt参数,改用messages数组,按[{"role": "角色", "content": "内容"}]的格式传递对话内容
  • 结果提取:从response.choices[0].text改为response.choices[0].message['content'],因为聊天模型的返回结构和文本补全模型不同
额外优化建议
  • 不要硬编码API密钥,改用环境变量:
    import os
    openai.api_key = os.getenv("OPENAI_API_KEY")
    
    然后在服务器上设置环境变量export OPENAI_API_KEY="你的密钥"
  • 如果使用OpenAI Python库v0.27.0+,可以直接用官方异步接口,省去线程池的麻烦:
    async def generate_response(prompt):
        response = await openai.ChatCompletion.acreate(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=150,
            n=1,
            temperature=0.5,
        )
        return response.choices[0].message['content'].strip()
    

内容的提问来源于stack exchange,提问作者caressgents

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:54:57