|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using Microsoft.Agents.AI; |
| 4 | +using Microsoft.Extensions.AI; |
| 5 | +using Microsoft.Extensions.VectorData; |
| 6 | + |
| 7 | +namespace SampleApp; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// A <see cref="ChatHistoryProvider"/> that keeps a bounded window of recent messages in session state |
| 11 | +/// (via <see cref="InMemoryChatHistoryProvider"/>) and overflows older messages to a vector store |
| 12 | +/// (via <see cref="ChatHistoryMemoryProvider"/>). When providing chat history, it searches the vector |
| 13 | +/// store for relevant older messages and prepends them as a memory context message. |
| 14 | +/// </summary> |
| 15 | +/// <remarks> |
| 16 | +/// Only non-system messages are counted towards the session state limit and overflow mechanism. System messages are always retained in session state and are not included in the vector store. |
| 17 | +/// Function calls and function results are also dropped when truncation happens, both from in-memory state, and they are also not persisted to the vector store. |
| 18 | +/// </remarks> |
| 19 | +internal sealed class BoundedChatHistoryProvider : ChatHistoryProvider, IDisposable |
| 20 | +{ |
| 21 | + private readonly InMemoryChatHistoryProvider _chatHistoryProvider; |
| 22 | + private readonly ChatHistoryMemoryProvider _memoryProvider; |
| 23 | + private readonly TruncatingChatReducer _reducer; |
| 24 | + private readonly string _contextPrompt; |
| 25 | + private IReadOnlyList<string>? _stateKeys; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Initializes a new instance of the <see cref="BoundedChatHistoryProvider"/> class. |
| 29 | + /// </summary> |
| 30 | + /// <param name="maxSessionMessages">The maximum number of non-system messages to keep in session state before overflowing to the vector store.</param> |
| 31 | + /// <param name="vectorStore">The vector store to use for storing and retrieving overflow chat history.</param> |
| 32 | + /// <param name="collectionName">The name of the collection for storing overflow chat history in the vector store.</param> |
| 33 | + /// <param name="vectorDimensions">The number of dimensions to use for the chat history vector store embeddings.</param> |
| 34 | + /// <param name="stateInitializer">A delegate that initializes the memory provider state, providing the storage and search scopes.</param> |
| 35 | + /// <param name="contextPrompt">Optional prompt to prefix memory search results. Defaults to a standard memory context prompt.</param> |
| 36 | + public BoundedChatHistoryProvider( |
| 37 | + int maxSessionMessages, |
| 38 | + VectorStore vectorStore, |
| 39 | + string collectionName, |
| 40 | + int vectorDimensions, |
| 41 | + Func<AgentSession?, ChatHistoryMemoryProvider.State> stateInitializer, |
| 42 | + string? contextPrompt = null) |
| 43 | + { |
| 44 | + if (maxSessionMessages < 0) |
| 45 | + { |
| 46 | + throw new ArgumentOutOfRangeException(nameof(maxSessionMessages), "maxSessionMessages must be non-negative."); |
| 47 | + } |
| 48 | + |
| 49 | + this._reducer = new TruncatingChatReducer(maxSessionMessages); |
| 50 | + this._chatHistoryProvider = new InMemoryChatHistoryProvider(new InMemoryChatHistoryProviderOptions |
| 51 | + { |
| 52 | + ChatReducer = this._reducer, |
| 53 | + ReducerTriggerEvent = InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.AfterMessageAdded, |
| 54 | + StorageInputRequestMessageFilter = msgs => msgs, |
| 55 | + }); |
| 56 | + this._memoryProvider = new ChatHistoryMemoryProvider( |
| 57 | + vectorStore, |
| 58 | + collectionName, |
| 59 | + vectorDimensions, |
| 60 | + stateInitializer, |
| 61 | + options: new ChatHistoryMemoryProviderOptions |
| 62 | + { |
| 63 | + SearchInputMessageFilter = msgs => msgs, |
| 64 | + StorageInputRequestMessageFilter = msgs => msgs, |
| 65 | + }); |
| 66 | + this._contextPrompt = contextPrompt |
| 67 | + ?? "The following are memories from earlier in this conversation. Use them to inform your responses:"; |
| 68 | + } |
| 69 | + |
| 70 | + /// <inheritdoc /> |
| 71 | + public override IReadOnlyList<string> StateKeys => this._stateKeys ??= this._chatHistoryProvider.StateKeys.Concat(this._memoryProvider.StateKeys).ToArray(); |
| 72 | + |
| 73 | + /// <inheritdoc /> |
| 74 | + protected override async ValueTask<IEnumerable<ChatMessage>> ProvideChatHistoryAsync( |
| 75 | + InvokingContext context, |
| 76 | + CancellationToken cancellationToken = default) |
| 77 | + { |
| 78 | + // Delegate to the inner provider's full lifecycle (retrieve, filter, stamp, merge with request messages). |
| 79 | + var chatHistoryProviderInputContext = new InvokingContext(context.Agent, context.Session, []); |
| 80 | + var allMessages = await this._chatHistoryProvider.InvokingAsync(chatHistoryProviderInputContext, cancellationToken).ConfigureAwait(false); |
| 81 | + |
| 82 | + // Search the vector store for relevant older messages. |
| 83 | + var aiContext = new AIContext { Messages = context.RequestMessages.ToList() }; |
| 84 | + var invokingContext = new AIContextProvider.InvokingContext( |
| 85 | + context.Agent, context.Session, aiContext); |
| 86 | + |
| 87 | + var result = await this._memoryProvider.InvokingAsync(invokingContext, cancellationToken).ConfigureAwait(false); |
| 88 | + |
| 89 | + // Extract only the messages added by the memory provider (stamped with AIContextProvider source type). |
| 90 | + var memoryMessages = result.Messages? |
| 91 | + .Where(m => m.GetAgentRequestMessageSourceType() == AgentRequestMessageSourceType.AIContextProvider) |
| 92 | + .ToList(); |
| 93 | + |
| 94 | + if (memoryMessages is { Count: > 0 }) |
| 95 | + { |
| 96 | + var memoryText = string.Join("\n", memoryMessages.Select(m => m.Text).Where(t => !string.IsNullOrWhiteSpace(t))); |
| 97 | + |
| 98 | + if (!string.IsNullOrWhiteSpace(memoryText)) |
| 99 | + { |
| 100 | + var contextMessage = new ChatMessage(ChatRole.User, $"{this._contextPrompt}\n{memoryText}"); |
| 101 | + return new[] { contextMessage }.Concat(allMessages); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + return allMessages; |
| 106 | + } |
| 107 | + |
| 108 | + /// <inheritdoc /> |
| 109 | + protected override async ValueTask StoreChatHistoryAsync( |
| 110 | + InvokedContext context, |
| 111 | + CancellationToken cancellationToken = default) |
| 112 | + { |
| 113 | + // Delegate storage to the in-memory provider. Its TruncatingChatReducer (AfterMessageAdded trigger) |
| 114 | + // will automatically truncate to the configured maximum and expose any removed messages. |
| 115 | + var innerContext = new InvokedContext( |
| 116 | + context.Agent, context.Session, context.RequestMessages, context.ResponseMessages!); |
| 117 | + await this._chatHistoryProvider.InvokedAsync(innerContext, cancellationToken).ConfigureAwait(false); |
| 118 | + |
| 119 | + // Archive any messages that the reducer removed to the vector store. |
| 120 | + if (this._reducer.RemovedMessages is { Count: > 0 }) |
| 121 | + { |
| 122 | + var overflowContext = new AIContextProvider.InvokedContext( |
| 123 | + context.Agent, context.Session, this._reducer.RemovedMessages, []); |
| 124 | + await this._memoryProvider.InvokedAsync(overflowContext, cancellationToken).ConfigureAwait(false); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + /// <inheritdoc/> |
| 129 | + public void Dispose() |
| 130 | + { |
| 131 | + this._memoryProvider.Dispose(); |
| 132 | + } |
| 133 | +} |
0 commit comments