|
| 1 | +using System.Runtime.CompilerServices; |
| 2 | +using Microsoft.Extensions.AI; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | + |
| 5 | +namespace Knowledge.Shared.Agents; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// A delegating chat client that filters out tool call content from responses. |
| 9 | +/// This is useful when the upstream model uses tools internally but the downstream |
| 10 | +/// consumer doesn't have access to those tools. |
| 11 | +/// </summary> |
| 12 | +public class ToolCallFilteringChatClient : DelegatingChatClient |
| 13 | +{ |
| 14 | + private readonly ILogger<ToolCallFilteringChatClient>? _logger; |
| 15 | + |
| 16 | + public ToolCallFilteringChatClient(IChatClient innerClient, ILogger<ToolCallFilteringChatClient>? logger = null) |
| 17 | + : base(innerClient) |
| 18 | + { |
| 19 | + _logger = logger; |
| 20 | + } |
| 21 | + |
| 22 | + public override async Task<ChatResponse> GetResponseAsync( |
| 23 | + IEnumerable<ChatMessage> messages, |
| 24 | + ChatOptions? options = null, |
| 25 | + CancellationToken cancellationToken = default) |
| 26 | + { |
| 27 | + var response = await base.GetResponseAsync(messages, options, cancellationToken); |
| 28 | + |
| 29 | + // Filter and transform the response messages |
| 30 | + var filteredMessages = new List<ChatMessage>(); |
| 31 | + foreach (var message in response.Messages) |
| 32 | + { |
| 33 | + var filtered = FilterMessage(message); |
| 34 | + if (filtered != null) |
| 35 | + { |
| 36 | + filteredMessages.Add(filtered); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return new ChatResponse(filteredMessages) |
| 41 | + { |
| 42 | + CreatedAt = response.CreatedAt, |
| 43 | + FinishReason = response.FinishReason, |
| 44 | + ModelId = response.ModelId, |
| 45 | + RawRepresentation = response.RawRepresentation, |
| 46 | + ResponseId = response.ResponseId, |
| 47 | + Usage = response.Usage |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync( |
| 52 | + IEnumerable<ChatMessage> messages, |
| 53 | + ChatOptions? options = null, |
| 54 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 55 | + { |
| 56 | + await foreach (var update in base.GetStreamingResponseAsync(messages, options, cancellationToken)) |
| 57 | + { |
| 58 | + _logger?.LogDebug("ToolCallFilter: Received update with {ContentCount} contents, Role={Role}, FinishReason={FinishReason}", |
| 59 | + update.Contents.Count, update.Role, update.FinishReason); |
| 60 | + |
| 61 | + foreach (var content in update.Contents) |
| 62 | + { |
| 63 | + _logger?.LogDebug("ToolCallFilter: Content type={Type}", content.GetType().Name); |
| 64 | + } |
| 65 | + |
| 66 | + var filtered = FilterUpdate(update); |
| 67 | + if (filtered != null) |
| 68 | + { |
| 69 | + _logger?.LogDebug("ToolCallFilter: Yielding filtered update with {ContentCount} contents", filtered.Contents.Count); |
| 70 | + yield return filtered; |
| 71 | + } |
| 72 | + else |
| 73 | + { |
| 74 | + _logger?.LogDebug("ToolCallFilter: Skipping update (filtered to null)"); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + private static ChatMessage? FilterMessage(ChatMessage message) |
| 80 | + { |
| 81 | + // Skip tool call messages entirely |
| 82 | + if (message.Role == ChatRole.Assistant) |
| 83 | + { |
| 84 | + var hasToolCalls = message.Contents.Any(c => c is FunctionCallContent); |
| 85 | + var hasToolResults = message.Contents.Any(c => c is FunctionResultContent); |
| 86 | + |
| 87 | + if (hasToolCalls || hasToolResults) |
| 88 | + { |
| 89 | + // Filter out tool-related content, keep only non-tool content |
| 90 | + var filteredContent = message.Contents |
| 91 | + .Where(c => c is not FunctionCallContent and not FunctionResultContent) |
| 92 | + .ToList(); |
| 93 | + |
| 94 | + if (filteredContent.Count == 0) |
| 95 | + { |
| 96 | + return null; |
| 97 | + } |
| 98 | + |
| 99 | + return new ChatMessage(message.Role, filteredContent); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + // Skip tool role messages entirely |
| 104 | + if (message.Role == ChatRole.Tool) |
| 105 | + { |
| 106 | + return null; |
| 107 | + } |
| 108 | + |
| 109 | + return message; |
| 110 | + } |
| 111 | + |
| 112 | + private static ChatResponseUpdate? FilterUpdate(ChatResponseUpdate update) |
| 113 | + { |
| 114 | + // Check if this update contains tool calls or results |
| 115 | + var hasToolCalls = update.Contents.Any(c => c is FunctionCallContent); |
| 116 | + var hasToolResults = update.Contents.Any(c => c is FunctionResultContent); |
| 117 | + |
| 118 | + if (hasToolCalls || hasToolResults) |
| 119 | + { |
| 120 | + // Filter out tool-related content, keep only non-tool content |
| 121 | + var filteredContents = update.Contents |
| 122 | + .Where(c => c is not FunctionCallContent and not FunctionResultContent) |
| 123 | + .ToList(); |
| 124 | + |
| 125 | + // If there's no non-tool content, skip this update entirely |
| 126 | + if (filteredContents.Count == 0) |
| 127 | + { |
| 128 | + return null; |
| 129 | + } |
| 130 | + |
| 131 | + return new ChatResponseUpdate |
| 132 | + { |
| 133 | + Contents = filteredContents, |
| 134 | + CreatedAt = update.CreatedAt, |
| 135 | + FinishReason = update.FinishReason, |
| 136 | + ModelId = update.ModelId, |
| 137 | + RawRepresentation = update.RawRepresentation, |
| 138 | + ResponseId = update.ResponseId, |
| 139 | + Role = update.Role |
| 140 | + }; |
| 141 | + } |
| 142 | + |
| 143 | + // Check if this is from a tool role - skip it |
| 144 | + if (update.Role == ChatRole.Tool) |
| 145 | + { |
| 146 | + return null; |
| 147 | + } |
| 148 | + |
| 149 | + return update; |
| 150 | + } |
| 151 | +} |
0 commit comments