Implement chats in a MAUI app with ChatGPT valid for a session #373
-
In my I saw your examples but none of them explains how to create more messages in the same chat with the same using var api = new OpenAIClient();
var messages = new List<Message>
{
new Message(Role.System, "You are a helpful assistant designed to output JSON."),
new Message(Role.User, "Who won the world series in 2020?"),
};
var chatRequest = new ChatRequest(messages, Model.GPT4o,
responseFormat: ChatResponseFormat.Json);
var response = await api.ChatEndpoint.GetCompletionAsync(chatRequest);
foreach (var choice in response.Choices)
{
Console.WriteLine($"[{choice.Index}] {choice.Message.Role}: {choice} " +
$"| Finish Reason: {choice.FinishReason}");
}
response.GetUsage(); In this example, there is no interaction with a user. Also, in the app, the user can leave the chat page and then open it later but the conversation should continue. Do you have any example for that? Thank you in advance, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Hi @erossini There is a Conversation class you can use for exactly this purpose. I use it like so: using var api = new OpenAIClient();
var conversation = new Conversation(
[
new(Role.System, "You are a helpful assistant designed to output JSON."),
new(Role.User, "Who won the world series in 2020?")
]);
var chatRequest = new ChatRequest(conversation.Messages, Model.GPT4o,
responseFormat: ChatResponseFormat.Json);
var response = await api.ChatEndpoint.GetCompletionAsync(chatRequest);
conversation.AppendMessage(response.FirstChoice.Message); You should be able to serialize this object to json if you wish to store a user session and return to it later :) also, appending the message also works for tool calls and other function/roles. you will need your own system of remembering and saving sessions though. |
Beta Was this translation helpful? Give feedback.
-
I'm trying to create the var request = new CreateAssistantRequest(Model.GPT4o);
assistant = await client.AssistantsEndpoint.CreateAssistantAsync(
new CreateAssistantRequest(
name: "English Teacher",
instructions: "You are a personal English Teacher.",
model: Model.GPT4o));
var messages = new List<Message> { "Good morning! How is the weather?" };
var threadRequest = new CreateThreadRequest(messages);
chats = await assistant.CreateThreadAndRunAsync(threadRequest); Now, I can add messages only in |
Beta Was this translation helpful? Give feedback.
Hi @erossini
There is a Conversation class you can use for exactly this purpose.
I use it like so:
You should be able to serialize this object …