Skip to content

Commit

Permalink
Implemented LoadConversation method (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcominerva authored Apr 17, 2023
2 parents 5539626 + f7322f4 commit 2193d2c
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 5 deletions.
2 changes: 1 addition & 1 deletion samples/ChatGptConsole/ChatGptConsole.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

Expand Down
39 changes: 37 additions & 2 deletions src/ChatGptNet/ChatGptClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,35 @@ public Task DeleteConversationAsync(Guid conversationId, bool preserveSetup = fa
return Task.CompletedTask;
}

public Task<Guid> LoadConversationAsync(Guid conversationId, IEnumerable<ChatGptMessage> messages, bool replaceHistory = true)
{
ArgumentNullException.ThrowIfNull(messages);

// Ensures that conversationId isn't empty.
if (conversationId == Guid.Empty)
{
conversationId = Guid.NewGuid();
}

if (replaceHistory)
{
// If messages must replace history, just use the current list, discarding all the previously cached content.
// If messages.Count() > ChatGptOptions.MessageLimit, the UpdateCache take care of taking only the last messages.
UpdateCache(conversationId, messages);
}
else
{
// Retrieves the current history and adds new messages.
var conversationHistory = cache.Get<List<ChatGptMessage>>(conversationId) ?? new List<ChatGptMessage>();
conversationHistory.AddRange(messages);

// If messages total length > ChatGptOptions.MessageLimit, the UpdateCache take care of taking only the last messages.
UpdateCache(conversationId, conversationHistory);
}

return Task.FromResult(conversationId);
}

private IList<ChatGptMessage> CreateMessageList(Guid conversationId, string message)
{
// Checks whether a list of messages for the given conversationId already exists.
Expand Down Expand Up @@ -230,18 +259,24 @@ private ChatGptRequest CreateRequest(IList<ChatGptMessage> messages, bool stream
private void UpdateHistory(Guid conversationId, IList<ChatGptMessage> messages, ChatGptMessage message)
{
messages.Add(message);
UpdateCache(conversationId, messages);
}

private void UpdateCache(Guid conversationId, IEnumerable<ChatGptMessage> messages)
{
// If the maximum number of messages has been reached, deletes the oldest ones.
// Note: system message does not count for message limit.
var conversation = messages.Where(m => m.Role != ChatGptRoles.System);

if (conversation.Count() > options.MessageLimit)
{
conversation = conversation.TakeLast(options.MessageLimit);

// If the first message was of role system, adds it back in.
if (messages[0].Role == ChatGptRoles.System)
var firstMessage = messages.First();
if (firstMessage.Role == ChatGptRoles.System)
{
conversation = conversation.Prepend(messages[0]);
conversation = conversation.Prepend(firstMessage);
}

messages = conversation.ToList();
Expand Down
29 changes: 28 additions & 1 deletion src/ChatGptNet/IChatGptClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public interface IChatGptClient
/// Setups a new conversation with a system message, that is used to influence assistant behavior.
/// </summary>
/// <param name="message">The system message.</param>
/// <returns>The new Conversation Id.</returns>
/// <returns>The unique identifier of the new conversation.</returns>
/// <remarks>This method creates a new conversation with a system message and a random Conversation Id. Then, call <see cref="AskAsync(Guid, string, ChatGptParameters, string, CancellationToken)"/> with this Id to start the actual conversation.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null"/>.</exception>
/// <seealso cref="AskAsync(Guid, string, ChatGptParameters, string, CancellationToken)"/>
Expand Down Expand Up @@ -106,6 +106,33 @@ IAsyncEnumerable<ChatGptResponse> AskStreamAsync(string message, ChatGptParamete
/// <seealso cref="ChatGptMessage"/>
Task<IEnumerable<ChatGptMessage>> GetConversationAsync(Guid conversationId);

/// <summary>
/// Loads messages into a new conversation.
/// </summary>
/// <param name="messages">Messages to load into a new conversation.</param>
/// <returns>The unique identifier of the new conversation.</returns>
/// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception>
/// <remarks>
/// <para>This method creates a new conversation with a random Conversation Id. Then, call <see cref="AskAsync(Guid, string, ChatGptParameters, string, CancellationToken)"/> with this Id to start the actual conversation.</para>
/// <para>The total number of messages never exceeds the message limit defined in <see cref="ChatGptOptions.MessageLimit"/>. If <paramref name="messages"/> contains more, only the latest ones are loaded.</para>
/// </remarks>
/// <seealso cref="ChatGptOptions.MessageLimit"/>
/// <seealso cref="AskStreamAsync(Guid, string, ChatGptParameters?, string?, CancellationToken)"/>
Task<Guid> LoadConversationAsync(IEnumerable<ChatGptMessage> messages)
=> LoadConversationAsync(Guid.NewGuid(), messages);

/// <summary>
/// Loads messages into conversation history.
/// </summary>
/// <param name="conversationId">The unique identifier of the conversation.</param>
/// <param name="messages">The messages to load into conversation history.</param>
/// <param name="replaceHistory"><see langword="true"/> to replace all the existing messages; <see langword="false"/> to mantain them.</param>
/// <returns>The unique identifier of the conversation.</returns>
/// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception>
/// <remarks>The total number of messages never exceeds the message limit defined in <see cref="ChatGptOptions.MessageLimit"/>. If <paramref name="messages"/> contains more, only the latest ones are loaded.</remarks>
/// <seealso cref="ChatGptOptions.MessageLimit"/>
Task<Guid> LoadConversationAsync(Guid conversationId, IEnumerable<ChatGptMessage> messages, bool replaceHistory = true);

/// <summary>
/// Deletes a chat conversation, clearing all the history.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/ChatGptNet/version.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
"version": "1.3",
"version": "1.4",
"publicReleaseRefSpec": [
"^refs/heads/master$" // we release out of master
],
Expand Down

0 comments on commit 2193d2c

Please sign in to comment.