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

Liwei Yin 0 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 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. Liwei Yin 0 Reputation points Microsoft Employee
    2024-07-01T02:41:20.8033333+00:00

    Resolved by replacing it with AddAzureOpenAIChatCompletion

    0 comments No comments