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

Liwei Yin 20 Reputation points Microsoft Employee
2024-06-28T23:46:59.79+00:00

Here is my c# code(.net 8.0)

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;


string openAiApiKey= "xxxxxxxxxxxxxxx";
Kernel kernel=Kernel.CreateBuilder().AddOpenAIChatCompletion("gpt-3.5-turbo", "https://xxxxxx.openai.azure.com/", openAiApiKey).Build();
Console.WriteLine("Build successfully");
while (true)
{
    Console.WriteLine("Q:");
      Console.WriteLine(await kernel.InvokePromptAsync(Console.ReadLine()));
}


It fails with below error

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

I got the key and endpoint from 'Keys and Endpoint'

User's image


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

Accepted answer
  1. navba-MSFT 20,530 Reputation points Microsoft Employee
    2024-07-03T03:32:52.11+00:00

    @Liwei Yin I'm glad to see you were able to resolve your issue. Thanks for posting your solution so that others experiencing the same thing can easily reference this. Since the Microsoft Q&A community has a policy that the question author cannot accept their own answer, they can only accept answers by others, I'll repost your solution in case you'd like to Accept the answer.

    . Issue:

    You were encountering the below error:

    Microsoft.SemanticKernel.HttpOperationException: Incorrect API key provided: https://************************com/. You can find your API key at https://platform.openai.com/account/api-keys
    

    . . Resolution:

    You managed to resolve the issue by replacing it with AddAzureOpenAIChatCompletion.

    0 comments No comments

0 additional answers

Sort by: Most helpful