In the following code, it always works fine the first time. As you can see I'm trying to keep the list of previous questions and answers to keep context with the _items
List.
So the second time it fails with error 400 bad request, but to test I tried adding the two commented lines to begin my first question with an input of "How old is he?" so it has context and it also fails with error 400 so it cannot be any of the rest of the code! I cannot figure out why it won't let me add more context when all of the examples I've seen online say you can add multiple messages so as to keep context.
private List<RequestMessage> _items = new();
// Method to send a message to the ChatGPT API and return the response
async public Task<string> SendMessage(string message)
{
Request request = new Request();
List<RequestMessage> requestMessages = new();
requestMessages.Add(
new RequestMessage()
{
Role = "system",
Content = $"You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date: {DateTime.Now.ToString("yyyy-MM-dd")}",
});
requestMessages.Add(
new RequestMessage()
{
Role = "user",
Content = "How are you?",
});
requestMessages.Add(
new RequestMessage()
{
Role = "assistant",
Content = "I am doing well",
});
/*
requestMessages.Add(
new RequestMessage()
{
Role = "user",
Content = "Who is Brendan Fraser?",
});
requestMessages.Add(
new RequestMessage()
{
Role = "assistant",
Content = "Brendan Fraser is a Canadian American actor",
});
*/
requestMessages.AddRange(_items);
requestMessages.Add(
new RequestMessage()
{
Role = "user",
Content = message,
});
request.Messages = requestMessages.ToArray();
string requestData = JsonSerializer.Serialize(request);
StringContent content = new StringContent(requestData, Encoding.UTF8, "application/json");
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(_apiUrl, content);
if (httpResponseMessage.IsSuccessStatusCode)
{
string responseString = await httpResponseMessage.Content.ReadAsStringAsync();
Response response = JsonSerializer.Deserialize<Response>(responseString);
string responseText = response.Choices[0].Message.Content;
_items.Add(new RequestMessage() { Role = "user", Content = message });
_items.Add(new RequestMessage() { Role = "assistant", Content = responseText });
return responseText;
}
else
{
return $"Error: {httpResponseMessage.StatusCode} - {httpResponseMessage.ReasonPhrase}";
}
}
}