Openai migrate problem

someone help please, i can’t modify my python code normally for new openai version, can someone help and modify my code for 3.5-turbo version?:

import os
import sys
from openai import OpenAI
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Your existing API key setup code
client = OpenAI(
  api_key=os.environ['OPENAI_API_KEY'],  # this is also the default, it can be omitted
)
@app.route('/welcome')
def index():
    return render_template('login-signup.html')

@app.route('/main-chat')
def main_chat():
    return render_template('main-chat.html')

@app.route('/ask', methods=['POST'])
def ask():
    messages = request.json['messages']
    
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages
    )
    
    # Assuming the API returns a 'choices' field with a list, where you want to get the first item
    message_from_ai = response.choices[0].message['content']
    
    # Now, return this message in a JSON response
    return jsonify({'response': message_from_ai})


    # Process the `chat_completion` response and extract the message
    # Here I'm assuming the response has a 'choices' field with a text property



@app.route('/get-firebase-config', methods=['GET'])
def get_firebase_config():
    # Ensure there's a 'firebase' environment variable
    if 'firebase' not in os.environ:
      sys.stderr.write("...")# Or return a more specific error message

    firebase_config = {
        "apiKey": os.environ['firebase'],
        # Add the rest of your static Firebase config here
        "authDomain": "padawanai.firebaseapp.com",
        "projectId": "padawanai",
        "storageBucket": "padawanai.appspot.com",
        "messagingSenderId": "265704826546",
        "appId": "1:265704826546:web:881ac592399d94aca0cbab",
        "measurementId": "G-11HPQE36PF"
    }
    return jsonify(firebase_config)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

Hello @shkrtv!

You may have forgotten to create the homepage. You can change the code to:

import os
import sys
from openai import OpenAI
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Your existing API key setup code
client = OpenAI(
  api_key=os.environ['OPENAI_API_KEY'],  # this is also the default, it can be omitted
)
@app.route('/')
def homepage():
  return "your page content here"
@app.route('/welcome')
def index():
    return render_template('login-signup.html')

@app.route('/main-chat')
def main_chat():
    return render_template('main-chat.html')

@app.route('/ask', methods=['POST'])
def ask():
    messages = request.json['messages']
    
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages
    )
    
    # Assuming the API returns a 'choices' field with a list, where you want to get the first item
    message_from_ai = response.choices[0].message['content']
    
    # Now, return this message in a JSON response
    return jsonify({'response': message_from_ai})


    # Process the `chat_completion` response and extract the message
    # Here I'm assuming the response has a 'choices' field with a text property



@app.route('/get-firebase-config', methods=['GET'])
def get_firebase_config():
    # Ensure there's a 'firebase' environment variable
    if 'firebase' not in os.environ:
      sys.stderr.write("...")# Or return a more specific error message

    firebase_config = {
        "apiKey": os.environ['firebase'],
        # Add the rest of your static Firebase config here
        "authDomain": "padawanai.firebaseapp.com",
        "projectId": "padawanai",
        "storageBucket": "padawanai.appspot.com",
        "messagingSenderId": "265704826546",
        "appId": "1:265704826546:web:881ac592399d94aca0cbab",
        "measurementId": "G-11HPQE36PF"
    }
    return jsonify(firebase_config)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

do you know how to migrate this code:

import openai
import wikipedia
from textblob import TextBlob
import nltk

nltk.download('punkt')

# Set up your OpenAI API key
openai.api_key = 'MY KEY'


# Define some responses
greetings = ["hello", "hi", "hey", "howdy", "greetings"]
farewells = ["goodbye", "bye", "see you", "farewell", "take care"]
thanks = ["thank", "thanks", "thank you"]
youre_welcome = ["you're welcome", "my pleasure", "no problem", "happy to help"]

def simple_chatbot(prompt):
    print("Creative or Informational Chat bot")
    if prompt == 1:
        print("Welcome to the Informational Chatbot! You can start chatting. Type 'quit' to exit.")

        while True:
            user_input = input("You: ").lower()

            if user_input == "quit":
                print("Goodbye!")
                break

            response = generate_response(user_input)
            if response is not None:
                print("AI: " + response)

    elif prompt == 2:
        print("Welcome to the Creative Chatbot! You can start chatting. Type 'quit' to exit.")

        while True:
            user_input = input("You: ").strip()

            if user_input.lower() == "quit":
                print("Goodbye!")
                break

            response = generate_text(user_input)
            if response is not None:
                print("AI: " + response)

def generate_response(user_input):
    if any(word in user_input for word in greetings):
        return "Hello! How can I assist you?"
    elif any(word in user_input for word in farewells):
        return "Goodbye! Take care."
    elif any(word in user_input for word in thanks):
        return "You're welcome!"
    else:
        return summarize_wikipedia(user_input)

def summarize_wikipedia(query):
    try:
        # Try to search Wikipedia for the user query
        page = wikipedia.page(query)
        summary = page.summary
        return summarize_text(summary)
    except wikipedia.exceptions.DisambiguationError as e:
        # If there are multiple possible pages, suggest some options
        return "Did you mean one of the following? " + ", ".join(e.options[:3])
    except wikipedia.exceptions.PageError:
        # If no matching page is found, inform the user
        return "Sorry, I couldn't find information on that topic."

def summarize_text(text, max_sentences=2):
    blob = TextBlob(text)
    summary = blob.sentences[:max_sentences]
    return " ".join(str(sentence) for sentence in summary)

def generate_text(prompt):
    # Use OpenAI to generate text based on the provided prompt
    response = openai.Completion.create(
        engine="davinci",
        prompt=prompt,
        max_tokens=100
    )
    return response['choices'][0]['text'].strip()

# Run the chatbot
if __name__ == "__main__":
    prompt = int(input("Choose a chatbot: \n1. Informational Chatbot\n2. Creative Chatbot\nEnter your choice (1 or 2): "))
    simple_chatbot(prompt)