Response status code does not indicate success: 404 (Not Found)

Hi,
I am using below code with correct API Key, but i am getting error, Can you please tell why? and how to fix?
public async Task GetChatResponseAsync(string prompt)
{
var request = new
{
model = “gpt-4”,
messages = new
{
new { role = “system”, content = “You are a helpful assistant.” },
new { role = “user”, content = prompt }
},
max_tokens = 100
};

 var requestMessage = new HttpRequestMessage(HttpMethod.Post, OpenAiUrl);
 requestMessage.Headers.Add("Authorization", $"Bearer {_apiKey}");
 requestMessage.Content = JsonContent.Create(request);

 var response = await _httpClient.SendAsync(requestMessage);
 response.EnsureSuccessStatusCode();

 using var responseStream = await response.Content.ReadAsStreamAsync();
 using var jsonDoc = await JsonDocument.ParseAsync(responseStream);

 return jsonDoc.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();

}

Below is Error:

ystem.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at ComboChatGPT.Services.OpenAiService.GetChatResponseAsync(String prompt) in D:\Ashok\ComboChatGPT\ComboChatGPT\ComboChatGPT\Services\ChatGPTService.cs:line 48
   at ComboChatGPT.Controllers.ChatController.Chat(ChatRequest request) in D:\Ashok\ComboChatGPT\ComboChatGPT\ComboChatGPT\Controllers\ChatController.cs:line 20
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
1 Like

What is the OpenAiUrl? 404 means you are posting to an URL that does not exist.

1 Like