OpenAI API error: "You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0"
Asked Answered
S

4

15

I am currently working on a chatbot, and as I am using Windows 11 it does not let me migrate to newer OpenAI library or downgrade it. Could I replace the ChatCompletion function with something else to work on my version?

This is the code:

import openai

openai.api_key = "private"

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

if __name__ == "__main__":
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["quit", "exit", "bye"]:
            break
        response = chat_gpt(user_input)
        print("Bot:", response)

And this is the full error:

... You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. <pip install openai==0.28>

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742

I tried both upgrading and downgrading through pip.

Sanative answered 17/11, 2023 at 23:9 Comment(1)
Have you tried the migration guide? github.com/openai/openai-python/discussions/742Paulo
E
28

Try updating to the latest and using:

from openai import OpenAI

client = OpenAI(
    # defaults to os.environ.get("OPENAI_API_KEY")
    api_key="private",
)

def chat_gpt(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content.strip()

Link

EDIT: message.['content'] -> message.content on the return of this function, as a message object is not subscriptable error is thrown while using message.['content']. Also, update link from pointing to the README (subject to change) to migration guide specific to this code.

Epos answered 17/11, 2023 at 23:15 Comment(0)
D
8

Problem

The method you're trying to use doesn't work with the OpenAI Python SDK >=v1.0.0 (if you're using Python) or OpenAI Node.js SDK >=v4.0.0 (if you're using Node.js). See the Python SDK migration guide or the Node.js SDK migration guide.

Python

The old SDK (i.e., v0.28.1) works with the following method:

client.ChatCompletion.create()

The new SDK (i.e., >=v1.0.0) works with the following method:

client.chat.completions.create()

Note: Be careful because the API is case-sensitive (i.e., client.Chat.Completions.create() will not work with the new SDK version).

Node.js

The old SDK (i.e., v3.3.0) works with the following method:

client.createChatCompletion()

The new SDK (i.e., >=v4.0.0) works with the following method:

client.chat.completions.create()

Note: Be careful because the API is case-sensitive (i.e., client.Chat.Completions.create() will not work with the new SDK version).

Solution

Python SDK v1.0.0 working example

If you run test.py, the OpenAI API will return the following completion:

Hello! How can I assist you today?

test.py

import os
from openai import OpenAI

client = OpenAI(
    api_key = os.getenv("OPENAI_API_KEY"),
)

completion = client.chat.completions.create(
  model = "gpt-3.5-turbo",
  messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"},
  ]
)

print(completion.choices[0].message.content.strip())

Node.js SDK v4.0.0 working example

If you run test.js, the OpenAI API will return the following completion:

Hello! How can I assist you today?

test.js

const OpenAI = require("openai");

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function main() {
  const completion = await client.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Hello!" },
    ],
  });

  console.log(completion.choices[0].message.content.trim());
}

main();
Demagnetize answered 18/11, 2023 at 8:55 Comment(4)
not working: OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variableLyell
client = OpenAI(api_key=key)Lyell
@Lyell I'll take a look at it and update my answer if necessary.Demagnetize
@Lyell You did something wrong. Take a look at your code. I tested the code I posted in the answer above with the latest OpenAI Python SDK version (i.e., 1.6.1) right now, and I received the response as expected (i.e., Hello! How can I assist you today?).Demagnetize
G
0

The cod below, with API, works super, I just test it. Try to figure how is done, to avoid that error of pip.

import os
import re
from openai import OpenAI

# pip install openai==0.28
# pip install --upgrade openai

# Configurare OpenAI API
client = OpenAI(api_key='YOUR-API-KEY')

def summarize_text(text):
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Rezumă următorul text în 5-7 cuvinte:"},
                {"role": "user", "content": text}
            ]
        )
        summary = response.choices[0].message.content.strip()
        
        # Verifică și ajustează lungimea rezumatului
        words = summary.split()
        if len(words) > 7:
            summary = ' '.join(words[:7])
        
        return summary
    except Exception as e:
        print(f"Eroare la generarea rezumatului: {e}")
        return "Rezumat temporar indisponibil"

def process_file(file_path, summaries):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # Extrage conținutul tag-urilor h3
    h3_tags = re.findall(r'<h3>(.*?)</h3>', content, re.DOTALL)

    file_summaries = []
    for tag in h3_tags:
        summary = summarize_text(tag)
        file_summaries.append(summary)

    # Adaugă rezumatele în dicționar
    summaries[os.path.basename(file_path)] = file_summaries

    # Înlocuiește YYY cu rezumatele
    summary_html = '\n'.join([f'<p class="text_obisnuit">{s}</p>' for s in file_summaries])
    new_content = content.replace('YYY', summary_html)

    # Scrie conținutul modificat înapoi în fișier
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(new_content)

    return new_content != content  # Returnează True dacă s-a făcut o modificare

def main():
    folder_path = 'd:\\1\\'
    summaries = {}
    modified_files = []

    # Procesează toate fișierele HTML din folder
    for filename in sorted(os.listdir(folder_path)):
        if filename.endswith('.html'):
            file_path = os.path.join(folder_path, filename)
            was_modified = process_file(file_path, summaries)
            if was_modified:
                modified_files.append(file_path)

    # Scrie rezumatele și link-urile modificate în api+rezumat.txt
    with open('api+rezumat.txt', 'w', encoding='utf-8') as file:
        for filename, file_summaries in summaries.items():
            file.write(f"{filename}\n")
            for i, summary in enumerate(file_summaries, 1):
                file.write(f"Tag {i}: {summary}\n")
            file.write("\n")
        
        file.write("\nFișiere modificate:\n")
        for modified_file in modified_files:
            file.write(f"{modified_file}\n")

if __name__ == "__main__":
    main()
Gymnast answered 17/11, 2023 at 23:9 Comment(0)
P
0

Since ChatCompletion.create() is no longer supported, use chat.completions.create(). Below is the redefined code:

def chat_gpt(prompt):
    response = openai.chat.completions.create(
        model="gpt-4-turbo",
        messages=[{"role": "user", "content": prompt}]
Piercing answered 21/7 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.