| | | 1 | | using Microsoft.Extensions.AI; |
| | | 2 | | |
| | | 3 | | namespace NexusLabs.Needlr.AgentFramework.Workflows.Middleware; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// <see cref="DelegatingChatClient"/> middleware that intercepts |
| | | 7 | | /// <see cref="GetResponseAsync"/> calls and writes request/response pairs to an |
| | | 8 | | /// <see cref="ITranscriptWriter"/>. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// <para> |
| | | 12 | | /// Set <see cref="CurrentStageName"/> before each pipeline stage to tag |
| | | 13 | | /// transcript entries with the originating stage. If not set, entries default |
| | | 14 | | /// to <c>"unknown"</c>. |
| | | 15 | | /// </para> |
| | | 16 | | /// <para> |
| | | 17 | | /// This middleware does not buffer or transform messages — it records them |
| | | 18 | | /// as-is and delegates to the inner client unchanged. |
| | | 19 | | /// </para> |
| | | 20 | | /// </remarks> |
| | | 21 | | [DoNotAutoRegister] |
| | | 22 | | public sealed class TranscriptLoggingChatClient : DelegatingChatClient |
| | | 23 | | { |
| | | 24 | | private readonly ITranscriptWriter _writer; |
| | 4 | 25 | | private string _currentStageName = "unknown"; |
| | | 26 | | |
| | | 27 | | /// <param name="innerClient">The inner chat client to delegate to.</param> |
| | | 28 | | /// <param name="writer">The transcript writer to record entries into.</param> |
| | | 29 | | public TranscriptLoggingChatClient( |
| | | 30 | | IChatClient innerClient, |
| | | 31 | | ITranscriptWriter writer) |
| | 4 | 32 | | : base(innerClient) |
| | | 33 | | { |
| | 4 | 34 | | ArgumentNullException.ThrowIfNull(writer); |
| | 4 | 35 | | _writer = writer; |
| | 4 | 36 | | } |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// Gets or sets the current stage name used to tag transcript entries. |
| | | 40 | | /// Call this before each stage execution. |
| | | 41 | | /// </summary> |
| | | 42 | | public string CurrentStageName |
| | | 43 | | { |
| | 1 | 44 | | get => _currentStageName; |
| | 1 | 45 | | set => _currentStageName = value; |
| | | 46 | | } |
| | | 47 | | |
| | | 48 | | /// <inheritdoc /> |
| | | 49 | | public override async Task<ChatResponse> GetResponseAsync( |
| | | 50 | | IEnumerable<ChatMessage> messages, |
| | | 51 | | ChatOptions? options = null, |
| | | 52 | | CancellationToken cancellationToken = default) |
| | | 53 | | { |
| | 3 | 54 | | var messagesList = messages as IList<ChatMessage> ?? messages.ToList(); |
| | 3 | 55 | | _writer.WriteRequest(_currentStageName, messagesList, options); |
| | | 56 | | |
| | 3 | 57 | | var response = await base |
| | 3 | 58 | | .GetResponseAsync(messagesList, options, cancellationToken) |
| | 3 | 59 | | .ConfigureAwait(false); |
| | | 60 | | |
| | 3 | 61 | | _writer.WriteResponse(_currentStageName, response); |
| | 3 | 62 | | return response; |
| | 3 | 63 | | } |
| | | 64 | | } |