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

Chris Grenier 0 Reputation points
2025-01-14T02:41:37.8933333+00:00

I am trying to run the following code. I have obtained the key and endpoint from my free azure subscription after creating openai resource (see image). I downloaded the code from microsoft page to access api and test it with code below. I checked that the key and endpoint are pulled correctly by printing them and they are. I keep getting the error "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 cant figure what is going wrong...

User's image

import os
from openai import AzureOpenAI
    
client = AzureOpenAI(
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),  
    api_version="2024-12-01-preview",
    azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
    )
    
deployment_name='gpt-35-turbo' #This will correspond to the custom name you chose for your deployment when you deployed a model. Use a gpt-35-turbo-instruct deployment. 
    
# Send a completion call to generate an answer
print('Sending a test completion job')
start_phrase = 'Write a tagline for an ice cream shop. '
response = client.completions.create(model=deployment_name, prompt=start_phrase, max_tokens=10)
print(start_phrase+response.choices[0].text)
Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,257 questions
Microsoft Authenticator
Microsoft Authenticator
A Microsoft app for iOS and Android devices that enables authentication with two-factor verification, phone sign-in, and code generation.
7,707 questions
Azure OpenAI Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
3,513 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel FANG 1,040 Reputation points MVP
    2025-01-14T10:39:57.01+00:00

    Hi Chris

    Your code looks correct. i tested it with my endpoint it works. And if I edit my apikey slightly, it gave same error as yours! So my only guess is that the key is wrong in your case. My suggestion is to put the key directly into the AzureOpenAI line to be 100% sure as as test, make sure no spaces.

    client = AzureOpenAI(
        api_key="put key here",  
        api_version="2024-12-01-preview",
        azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
        )
    
    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.