Skip to content

Commit

Permalink
feat: store current chat in localstorage #12 (#96)
Browse files Browse the repository at this point in the history
* feat: store current chat in localstorage #12

* cleanup

* cleanup

---------

Co-authored-by: Alexander <[email protected]>
  • Loading branch information
LXBdev and Alexander authored Jul 30, 2024
1 parent f40af3f commit 4358a05
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 8 deletions.
5 changes: 4 additions & 1 deletion OpenAIChatGPTBlazor/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
</div>
<div class="top-row p-4 header justify-content-between @_additionalTopRowClass">
<h4>
Welcome to my Chat using OpenAI
Welcome
</h4>
<div>
<button class="btn btn-sm btn-light" @onclick="() => ResetChat()" title="New Chat">
<i class="fas fa-file-circle-plus"></i> New Chat
</button>
<EditForm style="display:inline" Model="@this">
<InputCheckbox id="isAutoscrollEnabled" @bind-Value="_isAutoscrollEnabled" @bind-Value:after="OnSettingsChanged" class="form-check-input" />
<label for="isAutoscrollEnabled" class="form-check-label">Autoscroll</label>
Expand Down
78 changes: 71 additions & 7 deletions OpenAIChatGPTBlazor/Pages/Index.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,17 @@
using Azure.AI.OpenAI;
using System.Globalization;
using Microsoft.Extensions.Options;
using System.Text.Json;

namespace OpenAIChatGPTBlazor.Pages
{
public partial class Index : IAsyncDisposable
{
private const string SELECTED_MODEL = "SelectedModel";
private const string IS_AUTOSCROLL_ENABLED = "IsAutoscrollEnabled";
private const string CHAT_HISTORY = "ChatHistoryV1";

private readonly ChatCompletionsOptions _chat = new ChatCompletionsOptions
{
Messages =
{
new ChatRequestSystemMessage($"You are the assistant of a software engineer mainly working with .NET and Azure. Today is {DateTimeOffset.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.")
}
};
private readonly ChatCompletionsOptions _chat = new ChatCompletionsOptions();
private CancellationTokenSource? _searchCancellationTokenSource;
private string _warningMessage = string.Empty;
private string _next = string.Empty;
Expand Down Expand Up @@ -51,6 +47,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
"./Pages/Index.razor.js");
_SelectedOptionKey = await LocalStorage.GetItemAsync<string>(SELECTED_MODEL) ?? _SelectedOptionKey;
_isAutoscrollEnabled = await LocalStorage.GetItemAsync<bool?>(IS_AUTOSCROLL_ENABLED) ?? _isAutoscrollEnabled;
await InitiateChat();

_loading = false;
this.StateHasChanged();
Expand Down Expand Up @@ -110,6 +107,8 @@ private async Task RunSearch()
}

_chat.Messages.Add(new ChatRequestAssistantMessage(_stream));
await StoreChatHistory();

_loading = false;
_stream = string.Empty;
_warningMessage = string.Empty;
Expand Down Expand Up @@ -211,5 +210,70 @@ async ValueTask IAsyncDisposable.DisposeAsync()
}
}
}

private async Task ResetChat()
{
_chat.Messages.Clear();
_chat.Messages.Add(new ChatRequestSystemMessage($"You are the assistant of a software engineer mainly working with .NET and Azure. Today is {DateTimeOffset.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}."));

await StoreChatHistory();
}

private async Task StoreChatHistory()
{
var mapped = new List<MyChatMessage>();
foreach (var item in _chat.Messages)
{
var a = item switch
{
ChatRequestSystemMessage message => new MyChatMessage(message.Role.ToString(), message.Content),
ChatRequestUserMessage message => new MyChatMessage(message.Role.ToString(), message.Content),
ChatRequestAssistantMessage message => new MyChatMessage(message.Role.ToString(), message.Content),
_ => new MyChatMessage("", "")
};
mapped.Add(a);
}
var json = JsonSerializer.Serialize(mapped);
await LocalStorage.SetItemAsStringAsync(CHAT_HISTORY, json);
}

private async Task InitiateChat()
{
var chatHistory = await LocalStorage.GetItemAsync<string>(CHAT_HISTORY) ?? "[]";
var chat = JsonToChat(chatHistory);
if (chat.Count > 0)
{
_chat.Messages.Clear();
foreach (var item in chat)
{
_chat.Messages.Add(item);
}
}
else
{
await ResetChat();
}
}

private IList<ChatRequestMessage> JsonToChat(string json)
{
List<ChatRequestMessage> result = [];
var messages = JsonSerializer.Deserialize<IList<MyChatMessage>>(json) ?? [];
foreach (var item in messages)
{
ChatRequestMessage a = item switch
{
{ role: "system" } message => new ChatRequestSystemMessage(message.message),
{ role: "assistant" } message => new ChatRequestAssistantMessage(message.message),
_ => new ChatRequestUserMessage(item.message)
} ;

result.Add(a);
}

return result;
}
}

record MyChatMessage(string role, string message);
}

0 comments on commit 4358a05

Please sign in to comment.