How to fix openai version problem / error

I’m trying to execute this code in order to get some funny sentence related to a topic which is in a column in an excel file withe the name temas.xlsx. However, when executing it I get an error.

import pandas as pd
import openai

# Configuración de la clave API de OpenAI
openai.api_key = API_KEY

# Función para generar frases usando el modelo GPT-4
def generar_frases(tema):
        response = openai.Completion.create(
            engine="gpt-4",  # Asegúrate de utilizar el identificador correcto del modelo GPT-4
            prompt=f"Genera una frase divertida e ingeniosa de no más de 10 palabras sobre el tema '{tema}'.",
        return response.choices[0].text.strip()
    except Exception as e:
        print(f"Error al generar frase: {e}")
        return None

# Leer temas desde un archivo Excel
def frases_desde_excel(ruta_archivo):
    df = pd.read_excel(ruta_archivo)
    if 'Tema' in df.columns:
        df['Frase'] = df['Tema'].apply(generar_frases)
        return df
        print("La columna 'Tema' no se encuentra en el archivo Excel.")
        return None

# Ejecutar la función y mostrar o guardar los resultados
if __name__ == "__main__":
    archivo_excel = 'temas.xlsx'
    resultado = frases_desde_excel(archivo_excel)
    if resultado is not None:
        # Opcional: guardar los resultados en un nuevo archivo Excel
        resultado.to_excel('frases_generadas.xlsx', index=False)

And the error I receive is this one:

You tried to access openai.Completion, but this is no longer supported in openai>=1.0.0 - see the README at github / openai/openai-python for the API. (removed the https and .com to avoid issues when posting as it’s being detected as a link and I’m not allowed to share any…)

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: a link which I can't add because of posting limitations... but is in github [openai/openai-python/discussions/742]

How can I fix it?


That’s quite a comprehensive error message with background information and potential solutions suggestions!
What exactly is the question you are asking?

The code you show was likely written by an AI. It has old API parameters such as “engine” which are legacy. You’ll have to write your own code for making the requests, as the method for interacting with the AI has changed often, faster than AI training.

Here’s an example taken from the API reference, how to talk with a chat API model such as GPT-4:

from openai import OpenAI
client = OpenAI()

completion =
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}


Note the use of individual messages.