Translation Script not working

Hi there
I am writing a POC Python script that should use the most up to date ChatGPT model for translating text from English to Polish.
Here’s the script and the partial error.
I already did pip install openai --upgrade and I’m getting “Requirement already satisfied:”,
What should I change please to make sure I’m translating with the latest model and not 3.5 etc.

SCRIPT:

*import openai*

*# Set your OpenAI API key*
*openai.api_key = 'sk-proj-XYZ_UA'*

*def translate_text(text, target_language='Polish'):*
*    prompt = f"Translate the following text to {target_language}:\n\n{text}"*
*    response = openai.ChatCompletion.create(*
*        model="gpt-4o-mini-2024-07-18",  # Using the new model*
*        messages=[*
*            {"role": "system", "content": "You are a helpful assistant that translates text."},*
*            {"role": "user", "content": prompt}*
*        ]*
*    )*
*    return response.choices[0]['message']['content'].strip()*

*# Example usage*
*text_to_translate = "Hello World"*
*translated_text = translate_text(text_to_translate, target_language='Polish')*
*print(f"Translated text: {translated_text}")*

ERROR:
"Exception has occurred: APIRemovedInV1

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

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

VERSION OF openai:

pip show openai
Name: openai
Version: 1.40.0
Summary: The official Python library for the openai API

Welcome to the community!

Unfortunately, ChatGPT isn’t the best resource for generating openai api code.

This is how it should look nowadays

from openai import OpenAI
client = OpenAI()

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

print(completion.choices[0].message)

reference: https://platform.openai.com/docs/api-reference/chat/create?lang=python

make sure you have the API key set as OPENAI_API_KEY in your environment variables.

here’s a guide on that: https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key

(man, the docs keep getting more and more confusing)

Happy translatin though!

2 Likes