I am working on a project in VSCode, this code used to work back in October. I am using a “sk-proj-” API key. When I run the code I am getting a 401 error, but when I check the API key it is showing the right one? Here is my code for reference: import os
import pandas as pd
from openai import OpenAI
from tqdm.auto import tqdm
import csv
tqdm.pandas(desc=“Processing Company Descriptions”)
def extract_company_overview(description, max_tokens=4096):
“”“Extracts useful company information by processing text via OpenAI API.”“”
if len(description) > 20480: # Truncate to fit our estimated token limit
description = description[:20480]
try:
chat_completion = client.chat.completions.create(
messages=[
{
“role”: “user”,
“content”: f"Extract the useful information from this text: {description}“,
}
],
model=“gpt-3.5-turbo”,
)
response_text = chat_completion.choices[0].message.content.strip()
except Exception as e:
response_text = f"Error processing text: {str(e)}”
return response_text
Check for existing ‘Company Overview’ column and print structure before modification
print(“Before modification:”, df.columns)
Apply the function to the ‘Company Description’ column, appending the result to a new ‘Company Overview’ column
Welcome to the forum @georgemasterson. Happy new year 2025 to you.
Maybe you’re encountering a 401 error when trying to use your API key in VSCode, even though the key appears to be correct because of a wrong authentication, potentially?
Let’s troubleshoot this step by step.
Verify API Key:
Ensure that your API key is correctly set in your environment variables. You can check this by printing the API key in your code (be cautious not to expose it publicly).
print(os.environ.get("OPENAI_API_KEY"))
Check API Key Permissions:
Make sure that the API key has the necessary permissions to access the OpenAI services you are trying to use.
Update OpenAI Client Initialization:
Ensure that the OpenAI client is initialized correctly. Here is a slightly modified version of your code to include some debug prints:
import os
import pandas as pd
from openai import OpenAI
from tqdm.auto import tqdm
import csv
# Initialize the OpenAI client with your API key
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)
# Print the API key to verify it's being read correctly
print("API Key:", os.environ.get("OPENAI_API_KEY"))
# Set up tqdm for pandas integration
tqdm.pandas(desc="Processing Company Descriptions")
def extract_company_overview(description, max_tokens=4096):
"""Extracts useful company information by processing text via OpenAI API."""
if len(description) > 20480: # Truncate to fit our estimated token limit
description = description[:20480]
try:
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": f"Extract the useful information from this text: {description}",
}
],
model="gpt-3.5-turbo",
)
response_text = chat_completion.choices[0].message.content.strip()
except Exception as e:
response_text = f"Error processing text: {str(e)}"
return response_text
# Check for existing 'Company Overview' column and print structure before modification
print("Before modification:", df.columns)
# Apply the function to the 'Company Description' column, appending the result to a new 'Company Overview' column
df['Company Overview'] = df['Company Description'].progress_apply(extract_company_overview)
Check Network and Proxy Settings:
Ensure that there are no network issues or proxy settings that might be blocking the API request.
Review OpenAI API Status:
Check the OpenAI API status page to ensure there are no ongoing issues with the service.
Update OpenAI Package:
Make sure you are using the latest version of the OpenAI package. You can update it using:
pip install --upgrade openai
If you’ve tried all these steps and are still encountering issues, please provide any error messages or additional context so we can assist you further.
by the way are you using API in a way so you’d need to pay per use? Then you should check your balance.
Thank you for the reply, happy 2025 to you too. Sadly, I just went through the steps you provided and still returning the same error. Do you or anyone else know of other potential solutions?