Search code examples
pythonpython-3.xopenai-apichatgpt-api

OpenAI Chat Completions API error: "Invalid URL (POST /v1/engines/gpt-3.5-turbo/chat/completions)"


I'm using OpenAI to learn more about API integration, but I keep running into this code when running the Python program. I asked ChatGPT about the Invalid URL (POST /v1/engines/gpt-3.5-turbo/chat/completions) error, but it didn't seem to give me the right solutions.

Note: I do have the latest OpenAI package installed (i.e., 0.27.4).

Code:

import os
import openai
openai.api_key = "sk-xxxxxxxxxxxxxxxxxxxx"

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Tell me a joke."}
]

response = openai.ChatCompletion.create(
    engine="gpt-3.5-turbo",
    messages=messages,
    max_tokens=50,
    n=1,
    stop=None,
    temperature=0.7,
)

joke = response.choices[0].text.strip()
print(joke)

Solution

  • Problem

    The ChatGPT API (i.e., the GPT-3.5 API) has a model parameter (required). The engine parameter is not a valid parameter for the /v1/chat/completions API endpoint. See the official OpenAI documentation.

    Solution

    Change this...

    engine = "gpt-3.5-turbo"
    

    ...to this.

    model = "gpt-3.5-turbo"
    

    Also, change this...

    joke = response.choices[0].text.strip()
    

    ...to this.

    joke = response['choices'][0]['message']['content']