How to fix openai.AuthenticationError: Error code: 401

Nicolás Bonder 10 Reputation points
2024-12-05T12:12:38.03+00:00

Hi, I am working in a shared project using Azure OpenAI.

I was testing some code individually and all the keys were working. Then we build a repository, the rest of the team can send requests to Azure, but when I try to do it I get the error:

File "C:\Users\njbonder\Mettler\requirements_project\requirements_scoring_app\env\Lib\site-packages\openai_base_client.py", line 1061, in _request
raise self._make_status_error_from_response(err.response) from None

openai.AuthenticationError: Error code: 401 - {'statusCode': 401, 'message': 'Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired.'}

I moved my code, the one that was working ok when I worked individually, I put it into the shared project and it is also returning the same error.

To create the model we have:


class Config(BaseSettings):

    model_config = SettingsConfigDict(
        case_sensitive=False,
        env_file=".env",
        extra="ignore",
        str_strip_whitespace=True,
    )

    # Azure OpenAI API settings
    OPENAI_API_KEY: str
    OPENAI_API_VERSION: str
    AZURE_OPENAI_ENDPOINT: str
    AZURE_OPENAI_DEPLOYMENT: str
    AZURE_OPENAI_EMBEDDING_DEPLOYMENT: str
    AZURE_DEV_TOKEN: Optional[str] = None


config = Config()

To create the llm object:


llm = AzureChatOpenAI(
        deployment_name=config.AZURE_OPENAI_DEPLOYMENT,
        openai_api_key=config.OPENAI_API_KEY,
        openai_api_version=config.OPENAI_API_VERSION,
        azure_endpoint=config.AZURE_OPENAI_ENDPOINT,
        temperature=0.0
)

We already checked:

  • We have the same code
  • the keys are still valid
  • We have the same values in all the keys we have in the .env
  • There is not any whitespace in the values
  • I tried using a virtual environment and using Poetry

Can you help me to understand which can be the issue and how can I solve it?

Thanks.

Azure OpenAI Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
4,101 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Nicolás Bonder 10 Reputation points
    2024-12-05T16:50:54.48+00:00

    The problem was that I had a system environment variable that has priority over the variable created in the .env file.

    I removed that system variable and the problem is solved.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.