|
| 1 | +using System.ComponentModel; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | +using Devlooped.Extensions.AI; |
| 4 | +using Spectre.Console; |
| 5 | +using Spectre.Console.Json; |
| 6 | + |
| 7 | +namespace Microsoft.Extensions.AI; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Adds console logging capabilities to the chat client. |
| 11 | +/// </summary> |
| 12 | +[EditorBrowsable(EditorBrowsableState.Never)] |
| 13 | +public static class JsonConsoleLoggingExtensions |
| 14 | +{ |
| 15 | + /// <summary> |
| 16 | + /// Renders chat messages and responses to the console using Spectre.Console rich JSON formatting. |
| 17 | + /// </summary> |
| 18 | + /// <param name="builder">The builder in use.</param> |
| 19 | + /// <param name="askConfirmation">If true, prompts the user for confirmation before enabling console logging.</param> |
| 20 | + public static ChatClientBuilder UseJsonConsoleLogging(this ChatClientBuilder builder, bool askConfirmation = false) |
| 21 | + { |
| 22 | + if (askConfirmation && !AnsiConsole.Confirm("Do you want to enable console logging for chat messages?")) |
| 23 | + return builder; |
| 24 | + |
| 25 | + return builder.Use(inner => new ConsoleLoggingChatClient(inner)); |
| 26 | + } |
| 27 | + |
| 28 | + class ConsoleLoggingChatClient(IChatClient innerClient) : DelegatingChatClient(innerClient) |
| 29 | + { |
| 30 | + public override async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default) |
| 31 | + { |
| 32 | + AnsiConsole.Write(new Panel(new JsonText(new |
| 33 | + { |
| 34 | + messages = messages.Where(x => x.Role != ChatRole.System).ToArray(), |
| 35 | + options |
| 36 | + }.ToJsonString()))); |
| 37 | + |
| 38 | + var response = await InnerClient.GetResponseAsync(messages, options, cancellationToken); |
| 39 | + |
| 40 | + AnsiConsole.Write(new Panel(new JsonText(response.ToJsonString()))); |
| 41 | + return response; |
| 42 | + } |
| 43 | + |
| 44 | + public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 45 | + { |
| 46 | + AnsiConsole.Write(new Panel(new JsonText(new |
| 47 | + { |
| 48 | + messages = messages.Where(x => x.Role != ChatRole.System).ToArray(), |
| 49 | + options |
| 50 | + }.ToJsonString()))); |
| 51 | + |
| 52 | + List<ChatResponseUpdate> updates = []; |
| 53 | + |
| 54 | + await foreach (var update in base.GetStreamingResponseAsync(messages, options, cancellationToken)) |
| 55 | + { |
| 56 | + updates.Add(update); |
| 57 | + yield return update; |
| 58 | + } |
| 59 | + |
| 60 | + AnsiConsole.Write(new Panel(new JsonText(updates.ToJsonString()))); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments