| | | 1 | | using Microsoft.Agents.AI.Workflows; |
| | | 2 | | using Microsoft.Extensions.AI; |
| | | 3 | | using NexusLabs.Needlr.AgentFramework; |
| | | 4 | | |
| | | 5 | | namespace NexusLabs.Needlr.AgentFramework.Workflows; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Extension methods on <see cref="StreamingRun"/> and <see cref="Workflow"/> for collecting agent responses. |
| | | 9 | | /// </summary> |
| | | 10 | | public static class StreamingRunWorkflowExtensions |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Creates a streaming execution of the workflow, sends the message, and collects all agent responses. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <param name="workflow">The workflow to execute.</param> |
| | | 16 | | /// <param name="message">The user message to send to the workflow.</param> |
| | | 17 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 18 | | /// <returns> |
| | | 19 | | /// A dictionary mapping each agent's executor ID to its complete response text. |
| | | 20 | | /// Agents that emitted no text produce no entry. |
| | | 21 | | /// </returns> |
| | | 22 | | public static async Task<IReadOnlyDictionary<string, string>> RunAsync( |
| | | 23 | | this Workflow workflow, |
| | | 24 | | string message, |
| | | 25 | | CancellationToken cancellationToken = default) |
| | | 26 | | { |
| | 3 | 27 | | ArgumentNullException.ThrowIfNull(workflow); |
| | 2 | 28 | | ArgumentException.ThrowIfNullOrEmpty(message); |
| | 0 | 29 | | return await workflow.RunAsync(new ChatMessage(ChatRole.User, message), cancellationToken); |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Creates a streaming execution of the workflow, sends the message, collects all agent |
| | | 34 | | /// responses, and stops early when any termination condition is met. |
| | | 35 | | /// </summary> |
| | | 36 | | /// <param name="workflow">The workflow to execute.</param> |
| | | 37 | | /// <param name="message">The user message to send to the workflow.</param> |
| | | 38 | | /// <param name="terminationConditions"> |
| | | 39 | | /// Conditions evaluated after each completed agent turn. The first condition that returns |
| | | 40 | | /// <see langword="true"/> causes the loop to stop and remaining responses to be discarded. |
| | | 41 | | /// Pass an empty collection (or <see langword="null"/>) to disable Layer 2 termination. |
| | | 42 | | /// </param> |
| | | 43 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 44 | | /// <returns> |
| | | 45 | | /// A dictionary mapping each agent's executor ID to its complete response text up to the |
| | | 46 | | /// point of termination. Agents that emitted no text produce no entry. |
| | | 47 | | /// </returns> |
| | | 48 | | public static async Task<IReadOnlyDictionary<string, string>> RunAsync( |
| | | 49 | | this Workflow workflow, |
| | | 50 | | string message, |
| | | 51 | | IReadOnlyList<IWorkflowTerminationCondition>? terminationConditions, |
| | | 52 | | CancellationToken cancellationToken = default) |
| | | 53 | | { |
| | 0 | 54 | | ArgumentNullException.ThrowIfNull(workflow); |
| | 0 | 55 | | ArgumentException.ThrowIfNullOrEmpty(message); |
| | 0 | 56 | | return await workflow.RunAsync( |
| | 0 | 57 | | new ChatMessage(ChatRole.User, message), |
| | 0 | 58 | | terminationConditions, |
| | 0 | 59 | | cancellationToken); |
| | 0 | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Creates a streaming execution of the workflow, sends the message, and collects all agent responses. |
| | | 64 | | /// </summary> |
| | | 65 | | /// <param name="workflow">The workflow to execute.</param> |
| | | 66 | | /// <param name="message">The chat message to send to the workflow.</param> |
| | | 67 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 68 | | /// <returns> |
| | | 69 | | /// A dictionary mapping each agent's executor ID to its complete response text. |
| | | 70 | | /// Agents that emitted no text produce no entry. |
| | | 71 | | /// </returns> |
| | | 72 | | public static async Task<IReadOnlyDictionary<string, string>> RunAsync( |
| | | 73 | | this Workflow workflow, |
| | | 74 | | ChatMessage message, |
| | | 75 | | CancellationToken cancellationToken = default) |
| | | 76 | | { |
| | 2 | 77 | | ArgumentNullException.ThrowIfNull(workflow); |
| | 1 | 78 | | ArgumentNullException.ThrowIfNull(message); |
| | 0 | 79 | | await using var run = await InProcessExecution.RunStreamingAsync(workflow, message, cancellationToken: cancellat |
| | 0 | 80 | | await run.TrySendMessageAsync(new TurnToken(emitEvents: true)); |
| | | 81 | | |
| | | 82 | | // Register CancelRunAsync on the cancellation token so the workflow |
| | | 83 | | // actually stops (e.g., when a token budget is exceeded). |
| | 0 | 84 | | await using var registration = cancellationToken.CanBeCanceled |
| | 0 | 85 | | ? cancellationToken.Register(() => _ = run.CancelRunAsync()) |
| | 0 | 86 | | : default(CancellationTokenRegistration?); |
| | | 87 | | |
| | 0 | 88 | | var result = await run.CollectAgentResponsesAsync(cancellationToken); |
| | | 89 | | |
| | | 90 | | // If the cancellation token fired during execution (e.g., budget exceeded), |
| | | 91 | | // throw now. MAF may have swallowed the cancellation internally. |
| | 0 | 92 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 93 | | |
| | 0 | 94 | | return result; |
| | 0 | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// Creates a streaming execution of the workflow, sends the message, collects all agent |
| | | 99 | | /// responses, and stops early when any termination condition is met. |
| | | 100 | | /// </summary> |
| | | 101 | | /// <param name="workflow">The workflow to execute.</param> |
| | | 102 | | /// <param name="message">The chat message to send to the workflow.</param> |
| | | 103 | | /// <param name="terminationConditions"> |
| | | 104 | | /// Conditions evaluated after each completed agent turn. The first condition that returns |
| | | 105 | | /// <see langword="true"/> causes the loop to stop and remaining responses to be discarded. |
| | | 106 | | /// Pass an empty collection (or <see langword="null"/>) to disable Layer 2 termination. |
| | | 107 | | /// </param> |
| | | 108 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 109 | | /// <returns> |
| | | 110 | | /// A dictionary mapping each agent's executor ID to its complete response text up to the |
| | | 111 | | /// point of termination. Agents that emitted no text produce no entry. |
| | | 112 | | /// </returns> |
| | | 113 | | public static async Task<IReadOnlyDictionary<string, string>> RunAsync( |
| | | 114 | | this Workflow workflow, |
| | | 115 | | ChatMessage message, |
| | | 116 | | IReadOnlyList<IWorkflowTerminationCondition>? terminationConditions, |
| | | 117 | | CancellationToken cancellationToken = default) |
| | | 118 | | { |
| | 0 | 119 | | ArgumentNullException.ThrowIfNull(workflow); |
| | 0 | 120 | | ArgumentNullException.ThrowIfNull(message); |
| | 0 | 121 | | await using var run = await InProcessExecution.RunStreamingAsync(workflow, message, cancellationToken: cancellat |
| | 0 | 122 | | await run.TrySendMessageAsync(new TurnToken(emitEvents: true)); |
| | | 123 | | |
| | 0 | 124 | | await using var registration = cancellationToken.CanBeCanceled |
| | 0 | 125 | | ? cancellationToken.Register(() => _ = run.CancelRunAsync()) |
| | 0 | 126 | | : default(CancellationTokenRegistration?); |
| | | 127 | | |
| | 0 | 128 | | if (terminationConditions is null || terminationConditions.Count == 0) |
| | | 129 | | { |
| | 0 | 130 | | var result = await run.CollectAgentResponsesAsync(cancellationToken); |
| | 0 | 131 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 132 | | return result; |
| | | 133 | | } |
| | | 134 | | |
| | 0 | 135 | | var terminationResult = await CollectWithTerminationAsync( |
| | 0 | 136 | | run.WatchStreamAsync(cancellationToken), |
| | 0 | 137 | | terminationConditions, |
| | 0 | 138 | | cancellationToken); |
| | 0 | 139 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 140 | | return terminationResult; |
| | 0 | 141 | | } |
| | | 142 | | |
| | | 143 | | /// <summary> |
| | | 144 | | /// Collects all agent response text from a streaming run, grouped by executor ID. |
| | | 145 | | /// </summary> |
| | | 146 | | /// <returns> |
| | | 147 | | /// A dictionary mapping each agent's executor ID to its complete response text. |
| | | 148 | | /// Agents that emitted no text produce no entry. |
| | | 149 | | /// </returns> |
| | | 150 | | public static Task<IReadOnlyDictionary<string, string>> CollectAgentResponsesAsync( |
| | | 151 | | this StreamingRun run, |
| | | 152 | | CancellationToken cancellationToken = default) |
| | | 153 | | { |
| | 0 | 154 | | ArgumentNullException.ThrowIfNull(run); |
| | 0 | 155 | | return CollectFromEventsAsync(run.WatchStreamAsync(cancellationToken)); |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | internal static async Task<IReadOnlyDictionary<string, string>> CollectFromEventsAsync( |
| | | 159 | | IAsyncEnumerable<WorkflowEvent> events) |
| | | 160 | | { |
| | 5 | 161 | | var responses = new Dictionary<string, System.Text.StringBuilder>(); |
| | | 162 | | |
| | 30 | 163 | | await foreach (var evt in events) |
| | | 164 | | { |
| | 10 | 165 | | if (evt is AgentResponseUpdateEvent update |
| | 10 | 166 | | && update.ExecutorId is not null |
| | 10 | 167 | | && update.Data is not null) |
| | | 168 | | { |
| | 10 | 169 | | var text = update.Data.ToString(); |
| | 10 | 170 | | if (string.IsNullOrEmpty(text)) |
| | | 171 | | continue; |
| | | 172 | | |
| | 9 | 173 | | if (!responses.TryGetValue(update.ExecutorId, out var sb)) |
| | 6 | 174 | | responses[update.ExecutorId] = sb = new System.Text.StringBuilder(); |
| | | 175 | | |
| | 9 | 176 | | sb.Append(text); |
| | | 177 | | } |
| | | 178 | | } |
| | | 179 | | |
| | 5 | 180 | | return responses.ToDictionary( |
| | 6 | 181 | | kv => kv.Key, |
| | 11 | 182 | | kv => kv.Value.ToString()); |
| | 5 | 183 | | } |
| | | 184 | | |
| | | 185 | | internal static async Task<IReadOnlyDictionary<string, string>> CollectWithTerminationAsync( |
| | | 186 | | IAsyncEnumerable<WorkflowEvent> events, |
| | | 187 | | IReadOnlyList<IWorkflowTerminationCondition> conditions, |
| | | 188 | | CancellationToken cancellationToken) |
| | | 189 | | { |
| | 8 | 190 | | var responses = new Dictionary<string, System.Text.StringBuilder>(); |
| | 8 | 191 | | var history = new List<ChatMessage>(); |
| | 8 | 192 | | var turnCount = 0; |
| | | 193 | | |
| | 8 | 194 | | string? currentExecutorId = null; |
| | | 195 | | |
| | 48 | 196 | | await foreach (var evt in events.WithCancellation(cancellationToken)) |
| | | 197 | | { |
| | 18 | 198 | | if (evt is not AgentResponseUpdateEvent update |
| | 18 | 199 | | || update.ExecutorId is null |
| | 18 | 200 | | || update.Data is null) |
| | | 201 | | { |
| | | 202 | | continue; |
| | | 203 | | } |
| | | 204 | | |
| | 18 | 205 | | var text = update.Data.ToString(); |
| | 18 | 206 | | if (string.IsNullOrEmpty(text)) |
| | | 207 | | continue; |
| | | 208 | | |
| | | 209 | | // Detect executor change — previous agent's turn is complete |
| | 18 | 210 | | if (currentExecutorId is not null |
| | 18 | 211 | | && currentExecutorId != update.ExecutorId |
| | 18 | 212 | | && responses.TryGetValue(currentExecutorId, out var completedSb)) |
| | | 213 | | { |
| | 9 | 214 | | var responseText = completedSb.ToString(); |
| | 9 | 215 | | turnCount++; |
| | 9 | 216 | | var completedMessage = new ChatMessage(ChatRole.Assistant, responseText); |
| | 9 | 217 | | history.Add(completedMessage); |
| | | 218 | | |
| | 9 | 219 | | var ctx = new TerminationContext |
| | 9 | 220 | | { |
| | 9 | 221 | | AgentId = currentExecutorId, |
| | 9 | 222 | | LastMessage = completedMessage, |
| | 9 | 223 | | TurnCount = turnCount, |
| | 9 | 224 | | ConversationHistory = history, |
| | 9 | 225 | | }; |
| | | 226 | | |
| | 9 | 227 | | if (ShouldTerminate(ctx, conditions)) |
| | 4 | 228 | | return FinalizeResponses(responses); |
| | | 229 | | } |
| | | 230 | | |
| | 14 | 231 | | currentExecutorId = update.ExecutorId; |
| | | 232 | | |
| | 14 | 233 | | if (!responses.TryGetValue(update.ExecutorId, out var sb)) |
| | 12 | 234 | | responses[update.ExecutorId] = sb = new System.Text.StringBuilder(); |
| | | 235 | | |
| | 14 | 236 | | sb.Append(text); |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | // Check the last agent's turn |
| | 4 | 240 | | if (currentExecutorId is not null |
| | 4 | 241 | | && responses.TryGetValue(currentExecutorId, out var lastSb)) |
| | | 242 | | { |
| | 3 | 243 | | var responseText = lastSb.ToString(); |
| | 3 | 244 | | turnCount++; |
| | 3 | 245 | | var lastMessage = new ChatMessage(ChatRole.Assistant, responseText); |
| | 3 | 246 | | history.Add(lastMessage); |
| | | 247 | | |
| | 3 | 248 | | var ctx = new TerminationContext |
| | 3 | 249 | | { |
| | 3 | 250 | | AgentId = currentExecutorId, |
| | 3 | 251 | | LastMessage = lastMessage, |
| | 3 | 252 | | TurnCount = turnCount, |
| | 3 | 253 | | ConversationHistory = history, |
| | 3 | 254 | | }; |
| | | 255 | | |
| | 3 | 256 | | ShouldTerminate(ctx, conditions); // evaluate but don't stop — stream already ended |
| | | 257 | | } |
| | | 258 | | |
| | 4 | 259 | | return FinalizeResponses(responses); |
| | 8 | 260 | | } |
| | | 261 | | |
| | | 262 | | private static bool ShouldTerminate( |
| | | 263 | | TerminationContext ctx, |
| | | 264 | | IReadOnlyList<IWorkflowTerminationCondition> conditions) |
| | | 265 | | { |
| | 40 | 266 | | foreach (var condition in conditions) |
| | | 267 | | { |
| | 10 | 268 | | if (condition.ShouldTerminate(ctx)) |
| | 4 | 269 | | return true; |
| | | 270 | | } |
| | 8 | 271 | | return false; |
| | 4 | 272 | | } |
| | | 273 | | |
| | | 274 | | private static IReadOnlyDictionary<string, string> FinalizeResponses( |
| | | 275 | | Dictionary<string, System.Text.StringBuilder> responses) |
| | 32 | 276 | | => responses.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()); |
| | | 277 | | } |
| | | 278 | | |