// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Shared.DiagnosticIds;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Compaction;
///
/// Provides extension methods for .
///
[Experimental(DiagnosticIds.Experiments.AgentsAIExperiments)]
public static class ChatStrategyExtensions
{
///
/// Returns an that applies this to reduce a list of messages.
///
/// The compaction strategy to wrap as an .
///
/// An that, on each call to , builds a
/// from the supplied messages and applies the strategy's compaction logic,
/// returning the resulting included messages.
///
///
/// This allows any to be used wherever an is expected,
/// bridging the compaction pipeline into systems bound to the Microsoft.Extensions.AI contract.
///
public static IChatReducer AsChatReducer(this CompactionStrategy strategy)
{
Throw.IfNull(strategy);
return new CompactionStrategyChatReducer(strategy);
}
///
/// An adapter that delegates to a .
///
private sealed class CompactionStrategyChatReducer : IChatReducer
{
private readonly CompactionStrategy _strategy;
public CompactionStrategyChatReducer(CompactionStrategy strategy)
{
this._strategy = strategy;
}
///
public async Task> ReduceAsync(IEnumerable messages, CancellationToken cancellationToken = default)
{
CompactionMessageIndex index = CompactionMessageIndex.Create([.. messages]);
await this._strategy.CompactAsync(index, cancellationToken: cancellationToken).ConfigureAwait(false);
return index.GetIncludedMessages();
}
}
}