| | | 1 | | using Microsoft.Agents.AI; |
| | | 2 | | |
| | | 3 | | namespace NexusLabs.Needlr.AgentFramework; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Convenience extensions for <see cref="AgentResponse"/>. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class AgentResponseExtensions |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Extracts the concatenated text content from all messages in the response. |
| | | 12 | | /// Returns <see langword="null"/> if the response has no messages or all messages |
| | | 13 | | /// have empty text. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// <para> |
| | | 17 | | /// MAF's <see cref="AgentResponse.Messages"/> can contain multiple |
| | | 18 | | /// <see cref="Microsoft.Extensions.AI.ChatMessage"/> entries (e.g., tool-call results |
| | | 19 | | /// interleaved with assistant text). This method concatenates only the non-empty |
| | | 20 | | /// <c>Text</c> properties, separated by newlines, into a single string. |
| | | 21 | | /// </para> |
| | | 22 | | /// <para> |
| | | 23 | | /// Typical usage for standalone agent runs: |
| | | 24 | | /// <code> |
| | | 25 | | /// var response = await agent.RunAsync(prompt, cancellationToken: ct); |
| | | 26 | | /// var text = response.GetText(); // "The answer is 42." |
| | | 27 | | /// </code> |
| | | 28 | | /// </para> |
| | | 29 | | /// </remarks> |
| | | 30 | | public static string? GetText(this AgentResponse response) |
| | | 31 | | { |
| | 7 | 32 | | ArgumentNullException.ThrowIfNull(response); |
| | | 33 | | |
| | 6 | 34 | | if (response.Messages is null or { Count: 0 }) |
| | 2 | 35 | | return null; |
| | | 36 | | |
| | 4 | 37 | | string? result = null; |
| | 24 | 38 | | foreach (var message in response.Messages) |
| | | 39 | | { |
| | 8 | 40 | | if (string.IsNullOrWhiteSpace(message.Text)) |
| | | 41 | | continue; |
| | | 42 | | |
| | 5 | 43 | | result = result is null |
| | 5 | 44 | | ? message.Text |
| | 5 | 45 | | : string.Concat(result, "\n", message.Text); |
| | | 46 | | } |
| | | 47 | | |
| | 4 | 48 | | return result; |
| | | 49 | | } |
| | | 50 | | } |