feat: Add commands and functionality to save and load chat sessions.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Extensions.AI;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AnchorCli;
|
||||
|
||||
@@ -69,4 +70,38 @@ internal sealed class ChatSession
|
||||
yield return update;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SaveAsync(string filePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Skip the system message when saving (it will be recreated on load)
|
||||
var messagesToSave = History.Skip(1).ToList();
|
||||
|
||||
var options = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(messagesToSave, AppJsonContext.Default.ListChatMessage);
|
||||
await File.WriteAllTextAsync(filePath, json, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task LoadAsync(string filePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var json = await File.ReadAllTextAsync(filePath, cancellationToken);
|
||||
|
||||
var options = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
};
|
||||
|
||||
var messages = JsonSerializer.Deserialize<List<ChatMessage>>(json, AppJsonContext.Default.ListChatMessage)
|
||||
?? new List<ChatMessage>();
|
||||
|
||||
// Keep the system message and append loaded messages
|
||||
var systemMessage = History[0];
|
||||
History.Clear();
|
||||
History.Add(systemMessage);
|
||||
History.AddRange(messages);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user