Error: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable". How to Fix

import openai
import pandas as pd
import time
openai.api_key = ‘sk-’ # Replace with your actual API key

file_path = ‘/Users/apple/Desktop/Automation/Untitled 2.xlsx’
df = pd.read_excel(file_path)

words = df[‘Table 1’].dropna().tolist()[0:800]

def get_cefr_level(word):
client = openai.OpenAI()
response = client.completions.create(
model=“gpt-3.5”, # Update model name if needed (consider using GPT-4 if available)
prompt=f"You are a helpful assistant knowledgeable about CEFR levels. What is the CEFR level of the word ‘{word}’?",
max_tokens=100, # Adjust max_tokens as needed
n=1, # Set number of desired responses to 1
stop=None # Optional stop sequences to control response generation
)

Access response content from the first choice

return response.choices[0].content.strip()

Get CEFR levels for the words

word_cefr_levels =
for word in words:
try:
cefr_level = get_cefr_level(word)
word_cefr_levels.append((word, cefr_level))
time.sleep(1) # Delay for 1 second between calls
except Exception as e:
print(f"An error occurred for word ‘{word}’: {e}")
word_cefr_levels.append((word, ‘Error’))

Create a DataFrame

cefr_df = pd.DataFrame(word_cefr_levels, columns=[‘Word’, ‘CEFR Level’])

Save to a new Excel file

output_file_path = ‘/Users/apple/Desktop/cefr_sorted_words.xlsx’ # Update this path
cefr_df.to_excel(output_file_path, index=False)

print(f’CEFR levels sorted and saved to {output_file_path}')