Skip to content

Commit

Permalink
Merge pull request #10 from UiT-ITA/Import-old-chats
Browse files Browse the repository at this point in the history
Import old chats
  • Loading branch information
tveito authored Nov 27, 2024
2 parents cb6b756 + 055d349 commit 5bc7c6e
Show file tree
Hide file tree
Showing 7 changed files with 150 additions and 95 deletions.
29 changes: 25 additions & 4 deletions ChatUiT2/Components/Layout/NavMenu.razor
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<div style="display:flex; flex-direction:column;height:100%; overflow-x:hidden; width:100%;">
@using ChatUiT2.Services
<div style="display:flex; flex-direction:column;height:100%; overflow-x:hidden; width:100%;">
<div>

<div style="display: flex; align-items: center; justify-content:space-between;" class="pt-0">
Expand Down Expand Up @@ -71,6 +72,13 @@
</MudStack>
</MudButton>

<MudButton FullWidth Class="pa-2" Style="display:flex; justify-content:flex-start" OnClick="ImportOldChats" Color="Color.Tertiary">
<MudStack Row>
<MudIcon Icon="@Icons.Material.Filled.BrowserUpdated" Size="Size.Medium" Class="mt-0" Style="height:28px; width: 28px;" />
<MudText Typo="Typo.h5" Class="pt-1">Import old chats</MudText>
</MudStack>
</MudButton>

@* Delete all user data *@
<MudButton FullWidth Class="pa-2" Style="display:flex; justify-content:flex-start" OnClick="DeleteAll" Color="Color.Tertiary">
<MudStack Row>
Expand All @@ -89,16 +97,16 @@
</MudStack>
</MudButton>
}
@if (!Nav.Uri.EndsWith("/test") && UserService.IsTester)
*@
@* @if (!Nav.Uri.EndsWith("/test"))
{
<MudButton FullWidth Class="pa-2" Style="display:flex; justify-content:flex-start" OnClick="@(() => Nav.NavigateTo("/test"))" Color="Color.Tertiary">
<MudStack Row>
<MudIcon Icon="@Icons.Material.Filled.Science" Size="Size.Medium" Class="mt-0" Style="height:28px; width: 28px;" />
<MudText Typo="Typo.h5" Class="pt-1">Test area</MudText>
</MudStack>
</MudButton>
} *@
} *@



Expand All @@ -120,6 +128,7 @@
[Inject] private IDialogService DialogService { get; set; } = null!;
[Inject] private IJSRuntime JS { get; set; } = null!;
[Inject] private IUpdateService UpdateService { get; set; } = null!;
[Inject] private LocalStorageService LocalStorageService { get; set; } = null!;

[Parameter] public EventCallback OnClose { get; set; }

Expand Down Expand Up @@ -172,6 +181,18 @@
await JS.InvokeVoidAsync("downloadFileFromBase64", fileName, base64);
}

private async Task ImportOldChats()
{
var chats = await LocalStorageService.GetLocalConversations();

Console.WriteLine(chats[0].Messages[0].Content);

foreach (var chat in chats)
{
UserService.AddChat(chat);
}
}

private async Task DeleteAll()
{
// Display confirmation dialog
Expand Down
101 changes: 10 additions & 91 deletions ChatUiT2/Components/Pages/Test.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,107 +9,26 @@
<MudText Typo="Typo.h6">Testing purposes ONLY!</MudText>

<MudButton StartIcon="@Icons.Material.Filled.Science" FullWidth OnClick="Testing">Testing</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.Science" FullWidth OnClick="TestAI">TestAI</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.Science" FullWidth OnClick="TestStorage">Test storage</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.Science" FullWidth OnClick="ToggleFileUpload">@("Turn file upload " + (userService.EnableFileUpload ? "off" : "on"))</MudButton>



<span>@debug_text</span>

@code {
[Inject] private TestService testService { get; set; } = null!;
//[Inject] private IStorageService storageService { get; set; } = null!;
[Inject] private IUserService userService { get; set; } = null!;
[Inject] private ILogger<Test> logger { get; set; } = null!;
// [Inject] private AuthenticationStateProvider Auth { get; set; } = null!;
[Inject] private LocalStorageService LocalStorageService { get; set; } = null!;
[Inject] private IUserService UserService { get; set; } = null!;

string? debug_text = "Debug text";
private string debug_text = "";

public async Task Testing()
public async void Testing()
{
await TestAI();
var chats = await LocalStorageService.GetLocalConversations();

StateHasChanged();
}

public async Task TestAI()
{
await Task.Delay(1);
// Model model = testService._configService.GetModel("GPT-4o");
// Console.WriteLine(model.Name);
// ModelEndpoint endpoint = testService._configService.GetEndpoint(model.Deployment);
// var client = new AzureOpenAIClient(new Uri(endpoint.Url), new Azure.AzureKeyCredential(endpoint.Key)).GetChatClient(model.DeploymentName);
// var options = new ChatCompletionOptions()
// {
// MaxTokens = Math.Min(model.MaxTokens, 4096),
// Temperature = 0.2f
// };
// int availableTokens = model.MaxContext - (int)options.MaxTokens;
// List<OpenAI.Chat.ChatMessage> messages = new();
// messages.Add(new SystemChatMessage("You are a helpful ai assistant, respond using markdown."));
// var contentPartText = OpenAI.Chat.ChatMessageContentPart.CreateTextMessageContentPart("What is in this image?");
// var contentPartImage = OpenAI.Chat.ChatMessageContentPart.CreateImageMessageContentPart(new Uri("https://upload.wikimedia.org/wikipedia/commons/3/3e/Emperor_Penguins_(15885611526).jpg"));
// var UserChatMessage = new UserChatMessage([contentPartText, contentPartImage]);
// messages.Add(UserChatMessage);


// var response = client.CompleteChatStreamingAsync(messages, options);
// string content = "";
// await foreach (var chatUpdate in response)
// {
// foreach (var update in chatUpdate.ContentUpdate)
// content += update.Text;
Console.WriteLine(chats[0].Messages[0].Content);

// }
// debug_text = content;
// StateHasChanged();
}

public async Task TestStorage()
{
await Task.Delay(1);
// // Define test data
// string username = "testuser";
// string filename = "test.txt";
// byte[] fileContent = System.Text.Encoding.UTF8.GetBytes("Hello world!\n");
// // Upload the file
// await storageService.UploadFile(username, filename, fileContent);
// Console.WriteLine("File uploaded successfully.");
// // Download the file
// byte[]? downloadedFileContent = await storageService.GetFileBytes(username, filename);
// if (downloadedFileContent != null)
// {
// string downloadedText = System.Text.Encoding.UTF8.GetString(downloadedFileContent);
// Console.WriteLine("Downloaded file content: " + downloadedText);
// }
// else
// {
// Console.WriteLine("Failed to download file.");
// }
}

public void ToggleFileUpload()
{
userService.EnableFileUpload = !userService.EnableFileUpload;
foreach(var chat in chats)
{
UserService.AddChat(chat);
}
}

public void LogSomething()
{
// testService.LogSomething();
}

}
9 changes: 9 additions & 0 deletions ChatUiT2/Components/Shared/ChatStartView.razor
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
</a>
</MudStack>
<MudDivider />
<a href="https://uit.topdesk.net/tas/public/ssp/content/detail/service?unid=5a3379b4e20e4a72bd4903f58e214ca1" target="_blank" style="text-decoration: none;">
<MudAlert Severity="Severity.Info">
New verison! Read more here :)
</MudAlert>
</a>
<MudText Typo="Typo.body1">
Get old chats from ChatUiT by clicking Import old chats.
</MudText>
<MudDivider />
<MudStack Row>
<MudText Typo="Typo.h4" Class="pt-3">Model:</MudText>
<MudSpacer />
Expand Down
1 change: 1 addition & 0 deletions ChatUiT2/Interfaces/IUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public interface IUserService
ChatWidth ChatWidth { get; set; }

void NewChat();
void AddChat(WorkItemChat chat);
void SetWorkItem(IWorkItem workItem);
bool GetSaveHistory();
Task SetSaveHistory(IWorkItem workItem, bool value);
Expand Down
1 change: 1 addition & 0 deletions ChatUiT2/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
builder.Services.AddScoped<IAuthUserService, AuthUserService>();
builder.Services.AddScoped<IUpdateService, UpdateService>();
builder.Services.AddScoped<SpeechService>();
builder.Services.AddScoped<LocalStorageService>();

// Transient services

Expand Down
98 changes: 98 additions & 0 deletions ChatUiT2/Services/LocalStorageService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using ChatUiT2.Models;
using Microsoft.JSInterop;
using System.Text.Json;


namespace ChatUiT2.Services;

public class LocalStorageService
{
private readonly IJSRuntime JSRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
JSRuntime = jsRuntime;
}

public async Task<string> GetItemAsync(string key)
{
return await JSRuntime.InvokeAsync<string>("localStorage.getItem", key);
}

public async Task<List<Conversation>> GetConversationHistoryAsync()
{
string json = await GetItemAsync("conversationHistory");
if (string.IsNullOrEmpty(json))
{
return null;
}
return JsonSerializer.Deserialize<List<Conversation>>(json);
}

public async Task<List<WorkItemChat>> GetLocalConversations()
{
List<WorkItemChat> conversationHistory = new List<WorkItemChat>();
Console.WriteLine("Getting history");
var history = await GetConversationHistoryAsync();
if (history == null)
{
Console.WriteLine("No history found");
return conversationHistory;
}
Console.WriteLine("Got history");
foreach (var conversation in history)
{
Console.WriteLine($"Conversation: {conversation.name}");

if (conversation.messages.Count == 0)
{
continue;
}

var settings = new ChatSettings { MaxTokens = 4096, Model = "gpt-4o-mini", Prompt = conversation.prompt, Temperature = (float)conversation.temperature };
var messages = new List<ChatMessage>();

messages = conversation.messages.Select(m => new ChatMessage
{
Role = m.role == "user" ? ChatMessageRole.User : ChatMessageRole.Assistant,
Content = m.content,
Status = ChatMessageStatus.Done
}).ToList();

var newConversation = new WorkItemChat
{
Name = conversation.name,
Settings = settings,
Messages = messages,
Persistant = false
};

conversationHistory.Add(newConversation);
}


return conversationHistory;
}
}

public class Conversation
{
public string id { get; set; } // Matches "id"

Check warning on line 79 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 79 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public string name { get; set; } // Matches "name"

Check warning on line 80 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 80 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public List<Message> messages { get; set; } // Matches "messages"

Check warning on line 81 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'messages' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 81 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'messages' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public OldModel model { get; set; } // Matches "model"

Check warning on line 82 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'model' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 82 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'model' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public string prompt { get; set; } // Matches "prompt"

Check warning on line 83 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'prompt' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 83 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'prompt' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public double temperature { get; set; } // Matches "temperature"
public string folderId { get; set; } // Matches "folderId"

Check warning on line 85 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'folderId' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 85 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'folderId' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
}
public class Message
{
public string role { get; set; } // Matches "role"

Check warning on line 89 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'role' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 89 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'role' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public string content { get; set; } // Matches "content"

Check warning on line 90 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'content' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 90 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'content' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
}
public class OldModel
{
public string id { get; set; } // Matches "id"

Check warning on line 94 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 94 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'id' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public string name { get; set; } // Matches "name"

Check warning on line 95 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 95 in ChatUiT2/Services/LocalStorageService.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
public int maxLength { get; set; } // Matches "maxLength"
public int tokenLimit { get; set; } // Matches "tokenLimit"
}
6 changes: 6 additions & 0 deletions ChatUiT2/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,12 @@ public void NewChat()
SetWorkItem(newChat);
}

public void AddChat(WorkItemChat chat)
{
User.Chats.Add(chat);
_updateService.Update(UpdateType.Global);
}

public void SetWorkItem(IWorkItem workItem)
{
if (Waiting)
Expand Down

0 comments on commit 5bc7c6e

Please sign in to comment.