Cannot migrate and having issues with chatcompletion

Hi there, im very new to programming and ai and am trying to write an app but seems like my code is right but something is wrong and whenever I try and use openai migrate the download fails.

I get this
Error with OpenAI API:

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at GitHub - openai/openai-python: The official Python library for the OpenAI API 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: v1.0.0 Migration Guide · openai/openai-python · Discussion #742 · GitHub

I have searched here and read the documentation but still cant figure out where my code is wrong even though it appears to be right (even chatgpt says its right haha)

this is the piece of code that I am pulling my hair out over

            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": f"Analyze this text: {content}"}
                ],
                max_tokens=50
            )
            ai_result = response.choices[0].message.content.strip()
            print("AI Analysis Result:", ai_result)  # Debugging output```


if I follow the suggestion and try anf migrate I get a download error.

Im so confiused

1 Like

Welcome to the community!

What version of the library do you have installed?

You’ll either need to install and pin the older version (not recommended) or change your code to work with the new library.

# before
import json
import openai

completion = openai.Completion.create(model='curie')
print(completion['choices'][0]['text'])
print(completion.get('usage'))
print(json.dumps(completion, indent=2))

# after
from openai import OpenAI

client = OpenAI()

completion = client.completions.create(model='curie')
print(completion.choices[0].text)
print(dict(completion).get('usage'))
print(completion.model_dump_json(indent=2))
2 Likes

Hi Paul, thanks for trying to assist

Name: openai
Version: 1.53.0

so I have tried to change the code, bearing in mind I am like brand new to coding and am using ai to try and help me, but no matter how many times I give it the “fix” the code it gives me back always gives me errors and I just keep going round in circles.

One would think that chatgpt would be able to know it’s way around changes to openai’s api stuff which is seriously beyond my comprehension.

this is the app.

from flask import Flask, request, render_template, redirect, url_for, flash
import psycopg2
import os
from config import API_KEY
import openai  
from openai import OpenAI

app = Flask(__name__)
app.secret_key = 'supersecretkey'  # Used to allow flash messages

# Set up OpenAI API key
openai.api_key = API_KEY  # Set the API key directly in the openai library

# Database connection details
db_config = {
    'database': 'xxx',
    'user': 'xxx',
    'password': 'xxx',  # Replace with your PostgreSQL password
    'host': 'localhost',
    'port': '5432'
}

# Define upload folders
UPLOAD_FOLDER = 'uploads'
AUDIO_FOLDER = os.path.join(UPLOAD_FOLDER, 'audio')
IMAGE_FOLDER = os.path.join(UPLOAD_FOLDER, 'images')
VIDEO_FOLDER = os.path.join(UPLOAD_FOLDER, 'videos')

# Ensure folders exist
os.makedirs(AUDIO_FOLDER, exist_ok=True)
os.makedirs(IMAGE_FOLDER, exist_ok=True)
os.makedirs(VIDEO_FOLDER, exist_ok=True)

@app.route('/')
def index():
    """Renders the main form for uploading text, audio, image, and video files."""
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    """Handles the form submission and file uploads, and optionally processes text with AI."""
    title = request.form['title']
    content = request.form.get('content', '')  # Default to empty string if no content is provided
    process_with_ai = 'process_with_ai' in request.form  # Checkbox for AI processing

    # Only save files if they were uploaded
    audio_path = None
    if 'audio' in request.files and request.files['audio'].filename != '':
        audio_file = request.files['audio']
        audio_path = os.path.join(AUDIO_FOLDER, audio_file.filename)
        audio_file.save(audio_path)

    image_path = None
    if 'image' in request.files and request.files['image'].filename != '':
        image_file = request.files['image']
        image_path = os.path.join(IMAGE_FOLDER, image_file.filename)
        image_file.save(image_path)

    video_path = None
    if 'video' in request.files and request.files['video'].filename != '':
        video_file = request.files['video']
        video_path = os.path.join(VIDEO_FOLDER, video_file.filename)
        video_file.save(video_path)

    # Connect to the database and insert data
    connection = psycopg2.connect(**db_config)
    cursor = connection.cursor()
    cursor.execute(
        "INSERT INTO media_data (title, content, audio_path, image_path, video_path) VALUES (%s, %s, %s, %s, %s)",
        (title, content, audio_path, image_path, video_path)
    )
    connection.commit()
    cursor.close()
    connection.close()

    ai_result = None  # Placeholder for AI result

    # Process content with OpenAI if checkbox was selected
    if process_with_ai and content:
        try:
            # Sending text content to OpenAI for processing
            prompt = f"Analyze this text: {content}"
            response = openai.Completion.create(
                model="gpt-4",
                prompt=prompt,
                max_tokens=50
            )
            ai_result = response.choices[0].text.strip()
            print("AI Analysis Result:", ai_result)  # Debugging output
        except Exception as e:
            print("Error with OpenAI API:", e)
            flash("There was an error with the OpenAI API. Please try again later.")

    # Redirect to the results page with the AI result
    return redirect(url_for('results', ai_result=ai_result))

@app.route('/results')
def results():
    """Displays the AI analysis result."""
    ai_result = request.args.get('ai_result', None)
    return render_template('results.html', ai_result=ai_result)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

We are seeing this issue everywhere.

Migration tool is not helping.

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at …github link

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: github … link
Please provide a resolution.