Kaan Tiftikci
Kaan Tiftikci

Reputation: 141

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

I want to translate the texts in a csv file into English using the GPT 4 model, but I constantly get the following error. Even though I updated the version, I continue to get the same error.

import openai
import pandas as pd
import os
from tqdm import tqdm


openai.api_key = os.getenv("API")

def translate_text(text):
    response = openai.Completion.create(
        model="text-davinci-003",  # GPT-4 modeli
        prompt=f"Translate the following Turkish text to English: '{text}'",
        max_tokens=60
    )
    # Yeni API yapısına göre yanıtın alınması
    return response.choices[0].text.strip()

df = pd.read_excel('/content/3500-turkish-dataset-column-name.xlsx')

column_to_translate = 'review'

df[column_to_translate + '_en'] = ''

for index, row in tqdm(df.iterrows(), total=df.shape[0]):
    translated_text = translate_text(row[column_to_translate])
    df.at[index, column_to_translate + '_en'] = translated_text

df.to_csv('path/to/your/translated_csvfile.csv', index=False)

 0%|          | 0/3500 [00:00<?, ?it/s]
---------------------------------------------------------------------------
APIRemovedInV1                            Traceback (most recent call last)
<ipython-input-27-337b5b6f4d32> in <cell line: 29>()
     28 # Her satırdaki metni çevir ve yeni sütuna kaydet
     29 for index, row in tqdm(df.iterrows(), total=df.shape[0]):
---> 30     translated_text = translate_text(row[column_to_translate])
     31     df.at[index, column_to_translate + '_en'] = translated_text
     32 

3 frames
/usr/local/lib/python3.10/dist-packages/openai/lib/_old_api.py in __load__(self)

APIRemovedInV1: 

You tried to access openai.Completion, 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

Even though I updated the OpenAI package version, I get the same error.

Upvotes: 14

Views: 45848

Answers (2)

Rok Benko
Rok Benko

Reputation: 23078

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.Completion.create()

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

client.completions.create()

Note: Be careful because the API is case-sensitive (i.e., client.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.createCompletion()

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

client.completions.create()

Note: Be careful because the API is case-sensitive (i.e., client.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:

This is a test.

test.py

import os
from openai import OpenAI

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

completion = client.completions.create(
    model = "gpt-3.5-turbo-instruct",
    prompt = "Say this is a test",
    max_tokens = 7,
    temperature = 0,
)

print(completion.choices[0].text.strip())

Node.js SDK v4.0.0 working example

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

This is a test.

test.js

const OpenAI = require("openai");

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

async function main() {
  const completion = await client.completions.create({
    model: "gpt-3.5-turbo-instruct",
    prompt: "Say this is a test",
    max_tokens: 7,
    temperature: 0,
  });

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

main();

Upvotes: 17

Ratul Hasan
Ratul Hasan

Reputation: 600

1st of all, I'd recommend you to check the official doc for the current version. That said, the Completion method is no longer available.

2ndly, the da-vinci model you are using is deprecated, check the available models here

So after fixing the code with those review:

import openai
import pandas as pd
import os
from tqdm import tqdm


# lets initialize the API client 1st
client = openai.OpenAI(
    # This is the default and can be omitted
    api_key=os.getenv("API")
)

def translate_text(text):
    prompt=f"Translate the following Turkish text to English: '{text}'"
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",  # or gpt-4-turbo or gpt-4
        # yes, OpenAI recommends using roleplay like message system
        messages=[
            {
                "role": "user",
                "content": prompt,
            }
        ],
        max_tokens=60
    )
    # Yeni API yapısına göre yanıtın alınması
    return response.choices[0].message.content.strip()

df = pd.read_excel('/content/3500-turkish-dataset-column-name.xlsx')

column_to_translate = 'review'

df[column_to_translate + '_en'] = ''

for index, row in tqdm(df.iterrows(), total=df.shape[0]):
    translated_text = translate_text(row[column_to_translate])
    df.at[index, column_to_translate + '_en'] = translated_text

df.to_csv('path/to/your/translated_csvfile.csv', index=False)

Upvotes: 0

Related Questions