Failed to call Azure OpenAI API: failed with error:invalid_api_key

Liwei Yin 0 Reputation points Microsoft Employee
2024-06-28T23:43:02.87+00:00

Here is my code

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
string openAiApiKey= "xxxxx";
Kernel kernel=Kernel.CreateBuilder().AddOpenAIChatCompletion("gpt-3.5-turbo", "https://xxx.openai.azure.com/", openAiApiKey).Build();
Console.WriteLine("Build successfully");
while (true)
{
    Console.WriteLine("Q:");
      Console.WriteLine(await kernel.InvokePromptAsync(Console.ReadLine()));
}

I got the key and endpoint from the 'Keys and Endpoint', but always run into below error:

Any suggestions would be appreciated.

Build successfully
Q:
Hello
Unhandled exception. Microsoft.SemanticKernel.HttpOperationException: Incorrect API key provided: https://************************com/. You can find your API key at https://platform.openai.com/account/api-keys.
Status: 401 (Unauthorized)
ErrorCode: invalid_api_key

Content:
{
    "error": {
        "message": "Incorrect API key provided: https://************************com/. You can find your API key at https://platform.openai.com/account/api-keys.",
        "type": "invalid_request_error",
        "param": null,
        "code": "invalid_api_key"
    }
}


Headers:
Date: Fri, 28 Jun 2024 23:36:53 GMT
Connection: keep-alive
Vary: REDACTED
X-Request-ID: REDACTED
Strict-Transport-Security: REDACTED
CF-Cache-Status: REDACTED
Set-Cookie: REDACTED
Server: cloudflare
CF-RAY: REDACTED
Alt-Svc: REDACTED
Content-Type: application/json; charset=utf-8
Content-Length: 286

User's image

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,896 questions
Azure OpenAI Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
2,522 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. hossein jalilian 4,690 Reputation points
    2024-06-28T23:55:10.02+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    • Ensure that the API key (openAiApiKey) and the endpoint ("https://xxx.openai.azure.com/") you are using are correct and match what OpenAI expects.
    • Make sure that the API key you obtained has the necessary permissions to access the gpt-3.5-turbo model and other resources you are trying to invoke. Sometimes, keys are restricted to certain models or environments.

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful

    0 comments No comments