| | | 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)); |
| | 0 | 81 | | return await run.CollectAgentResponsesAsync(cancellationToken); |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Creates a streaming execution of the workflow, sends the message, collects all agent |
| | | 86 | | /// responses, and stops early when any termination condition is met. |
| | | 87 | | /// </summary> |
| | | 88 | | /// <param name="workflow">The workflow to execute.</param> |
| | | 89 | | /// <param name="message">The chat message to send to the workflow.</param> |
| | | 90 | | /// <param name="terminationConditions"> |
| | | 91 | | /// Conditions evaluated after each completed agent turn. The first condition that returns |
| | | 92 | | /// <see langword="true"/> causes the loop to stop and remaining responses to be discarded. |
| | | 93 | | /// Pass an empty collection (or <see langword="null"/>) to disable Layer 2 termination. |
| | | 94 | | /// </param> |
| | | 95 | | /// <param name="cancellationToken">Optional cancellation token.</param> |
| | | 96 | | /// <returns> |
| | | 97 | | /// A dictionary mapping each agent's executor ID to its complete response text up to the |
| | | 98 | | /// point of termination. Agents that emitted no text produce no entry. |
| | | 99 | | /// </returns> |
| | | 100 | | public static async Task<IReadOnlyDictionary<string, string>> RunAsync( |
| | | 101 | | this Workflow workflow, |
| | | 102 | | ChatMessage message, |
| | | 103 | | IReadOnlyList<IWorkflowTerminationCondition>? terminationConditions, |
| | | 104 | | CancellationToken cancellationToken = default) |
| | | 105 | | { |
| | 0 | 106 | | ArgumentNullException.ThrowIfNull(workflow); |
| | 0 | 107 | | ArgumentNullException.ThrowIfNull(message); |
| | 0 | 108 | | await using var run = await InProcessExecution.RunStreamingAsync(workflow, message, cancellationToken: cancellat |
| | 0 | 109 | | await run.TrySendMessageAsync(new TurnToken(emitEvents: true)); |
| | | 110 | | |
| | 0 | 111 | | if (terminationConditions is null || terminationConditions.Count == 0) |
| | 0 | 112 | | return await run.CollectAgentResponsesAsync(cancellationToken); |
| | | 113 | | |
| | 0 | 114 | | return await CollectWithTerminationAsync( |
| | 0 | 115 | | run.WatchStreamAsync(cancellationToken), |
| | 0 | 116 | | terminationConditions, |
| | 0 | 117 | | cancellationToken); |
| | 0 | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Collects all agent response text from a streaming run, grouped by executor ID. |
| | | 122 | | /// </summary> |
| | | 123 | | /// <returns> |
| | | 124 | | /// A dictionary mapping each agent's executor ID to its complete response text. |
| | | 125 | | /// Agents that emitted no text produce no entry. |
| | | 126 | | /// </returns> |
| | | 127 | | public static Task<IReadOnlyDictionary<string, string>> CollectAgentResponsesAsync( |
| | | 128 | | this StreamingRun run, |
| | | 129 | | CancellationToken cancellationToken = default) |
| | | 130 | | { |
| | 0 | 131 | | ArgumentNullException.ThrowIfNull(run); |
| | 0 | 132 | | return CollectFromEventsAsync(run.WatchStreamAsync(cancellationToken)); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | internal static async Task<IReadOnlyDictionary<string, string>> CollectFromEventsAsync( |
| | | 136 | | IAsyncEnumerable<WorkflowEvent> events) |
| | | 137 | | { |
| | 5 | 138 | | var responses = new Dictionary<string, System.Text.StringBuilder>(); |
| | | 139 | | |
| | 30 | 140 | | await foreach (var evt in events) |
| | | 141 | | { |
| | 10 | 142 | | if (evt is AgentResponseUpdateEvent update |
| | 10 | 143 | | && update.ExecutorId is not null |
| | 10 | 144 | | && update.Data is not null) |
| | | 145 | | { |
| | 10 | 146 | | var text = update.Data.ToString(); |
| | 10 | 147 | | if (string.IsNullOrEmpty(text)) |
| | | 148 | | continue; |
| | | 149 | | |
| | 9 | 150 | | if (!responses.TryGetValue(update.ExecutorId, out var sb)) |
| | 6 | 151 | | responses[update.ExecutorId] = sb = new System.Text.StringBuilder(); |
| | | 152 | | |
| | 9 | 153 | | sb.Append(text); |
| | | 154 | | } |
| | | 155 | | } |
| | | 156 | | |
| | 5 | 157 | | return responses.ToDictionary( |
| | 6 | 158 | | kv => kv.Key, |
| | 11 | 159 | | kv => kv.Value.ToString()); |
| | 5 | 160 | | } |
| | | 161 | | |
| | | 162 | | internal static async Task<IReadOnlyDictionary<string, string>> CollectWithTerminationAsync( |
| | | 163 | | IAsyncEnumerable<WorkflowEvent> events, |
| | | 164 | | IReadOnlyList<IWorkflowTerminationCondition> conditions, |
| | | 165 | | CancellationToken cancellationToken) |
| | | 166 | | { |
| | 8 | 167 | | var responses = new Dictionary<string, System.Text.StringBuilder>(); |
| | 8 | 168 | | var history = new List<ChatMessage>(); |
| | 8 | 169 | | var turnCount = 0; |
| | | 170 | | |
| | 8 | 171 | | string? currentExecutorId = null; |
| | | 172 | | |
| | 48 | 173 | | await foreach (var evt in events.WithCancellation(cancellationToken)) |
| | | 174 | | { |
| | 18 | 175 | | if (evt is not AgentResponseUpdateEvent update |
| | 18 | 176 | | || update.ExecutorId is null |
| | 18 | 177 | | || update.Data is null) |
| | | 178 | | { |
| | | 179 | | continue; |
| | | 180 | | } |
| | | 181 | | |
| | 18 | 182 | | var text = update.Data.ToString(); |
| | 18 | 183 | | if (string.IsNullOrEmpty(text)) |
| | | 184 | | continue; |
| | | 185 | | |
| | | 186 | | // Detect executor change — previous agent's turn is complete |
| | 18 | 187 | | if (currentExecutorId is not null |
| | 18 | 188 | | && currentExecutorId != update.ExecutorId |
| | 18 | 189 | | && responses.TryGetValue(currentExecutorId, out var completedSb)) |
| | | 190 | | { |
| | 9 | 191 | | var responseText = completedSb.ToString(); |
| | 9 | 192 | | turnCount++; |
| | 9 | 193 | | history.Add(new ChatMessage(ChatRole.Assistant, responseText)); |
| | | 194 | | |
| | 9 | 195 | | var ctx = new TerminationContext |
| | 9 | 196 | | { |
| | 9 | 197 | | AgentId = currentExecutorId, |
| | 9 | 198 | | ResponseText = responseText, |
| | 9 | 199 | | TurnCount = turnCount, |
| | 9 | 200 | | ConversationHistory = history, |
| | 9 | 201 | | }; |
| | | 202 | | |
| | 9 | 203 | | if (ShouldTerminate(ctx, conditions)) |
| | 4 | 204 | | return FinalizeResponses(responses); |
| | | 205 | | } |
| | | 206 | | |
| | 14 | 207 | | currentExecutorId = update.ExecutorId; |
| | | 208 | | |
| | 14 | 209 | | if (!responses.TryGetValue(update.ExecutorId, out var sb)) |
| | 12 | 210 | | responses[update.ExecutorId] = sb = new System.Text.StringBuilder(); |
| | | 211 | | |
| | 14 | 212 | | sb.Append(text); |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | // Check the last agent's turn |
| | 4 | 216 | | if (currentExecutorId is not null |
| | 4 | 217 | | && responses.TryGetValue(currentExecutorId, out var lastSb)) |
| | | 218 | | { |
| | 3 | 219 | | var responseText = lastSb.ToString(); |
| | 3 | 220 | | turnCount++; |
| | 3 | 221 | | history.Add(new ChatMessage(ChatRole.Assistant, responseText)); |
| | | 222 | | |
| | 3 | 223 | | var ctx = new TerminationContext |
| | 3 | 224 | | { |
| | 3 | 225 | | AgentId = currentExecutorId, |
| | 3 | 226 | | ResponseText = responseText, |
| | 3 | 227 | | TurnCount = turnCount, |
| | 3 | 228 | | ConversationHistory = history, |
| | 3 | 229 | | }; |
| | | 230 | | |
| | 3 | 231 | | ShouldTerminate(ctx, conditions); // evaluate but don't stop — stream already ended |
| | | 232 | | } |
| | | 233 | | |
| | 4 | 234 | | return FinalizeResponses(responses); |
| | 8 | 235 | | } |
| | | 236 | | |
| | | 237 | | private static bool ShouldTerminate( |
| | | 238 | | TerminationContext ctx, |
| | | 239 | | IReadOnlyList<IWorkflowTerminationCondition> conditions) |
| | | 240 | | { |
| | 40 | 241 | | foreach (var condition in conditions) |
| | | 242 | | { |
| | 10 | 243 | | if (condition.ShouldTerminate(ctx)) |
| | 4 | 244 | | return true; |
| | | 245 | | } |
| | 8 | 246 | | return false; |
| | 4 | 247 | | } |
| | | 248 | | |
| | | 249 | | private static IReadOnlyDictionary<string, string> FinalizeResponses( |
| | | 250 | | Dictionary<string, System.Text.StringBuilder> responses) |
| | 32 | 251 | | => responses.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()); |
| | | 252 | | } |
| | | 253 | | |