Invalid API Key 401 Error in VSCode, but it shows the correct API Key?

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

Initialize the OpenAI client with your API key

client = OpenAI(
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)

df

1 Like

Welcome to the forum @georgemasterson. :slight_smile: 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.

  1. 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"))
    
  2. Check API Key Permissions:

    • Make sure that the API key has the necessary permissions to access the OpenAI services you are trying to use.
  3. 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)
    
  4. Check Network and Proxy Settings:

    • Ensure that there are no network issues or proxy settings that might be blocking the API request.
  5. Review OpenAI API Status:

    • Check the OpenAI API status page to ensure there are no ongoing issues with the service.
  6. 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.

Did this help or still the same problems occur

1 Like

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?

1 Like

You do not need to put an API key environment variable “get” in the client creation. The OpenAI API automatically gets it.

It also gets from key files, so ensure you don’t have any extra file API keys around.

I suspect the API key is “invalid” because it is long and didn’t get set as an environment variable properly.

You can check what your code is using after making a call attempt:

To troubleshoot just print your environment to a log file or console to see if it’s set or not.

BTW, I recommend using LangChain for everything. That way your code will also work with any other LLM provider as well.