|
| 1 | +using AiDotNet.Agentic.Models; |
| 2 | +using AiDotNet.Agentic.Tools; |
| 3 | + |
| 4 | +// Disambiguate from the legacy AiDotNet.PromptEngineering.Templates.ChatMessage (global using). |
| 5 | +using ChatMessage = AiDotNet.Agentic.Models.ChatMessage; |
| 6 | + |
| 7 | +namespace AiDotNet.Agentic.Agents; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// A single-model agent that drives an <see cref="IChatClient{T}"/> in a native tool-calling loop: |
| 11 | +/// it calls the model, runs any tools the model requests, feeds the results back, and repeats until the |
| 12 | +/// model returns a final answer (or the iteration cap is hit). |
| 13 | +/// </summary> |
| 14 | +/// <typeparam name="T">The numeric type shared with the underlying <see cref="IChatClient{T}"/>.</typeparam> |
| 15 | +/// <remarks> |
| 16 | +/// <para> |
| 17 | +/// This replaces the legacy prompt-parsed ReAct loop with provider-native function calling: tool requests |
| 18 | +/// arrive as structured <see cref="ToolCallContent"/> rather than scraped from prose, and tool results go |
| 19 | +/// back as <see cref="ChatRole.Tool"/> messages. It is the leaf <see cref="IAgent{T}"/> that the multi-agent |
| 20 | +/// coordinators (supervisor/swarm) compose. |
| 21 | +/// </para> |
| 22 | +/// <para><b>For Beginners:</b> Give it a model and (optionally) a toolbox. Ask it something. Internally it |
| 23 | +/// loops: "model, here's the task and your tools" → if the model asks to use a tool, the executor runs it |
| 24 | +/// and tells the model the result → repeat → until the model just answers. You get that final answer back, |
| 25 | +/// plus the full transcript of what happened. |
| 26 | +/// </para> |
| 27 | +/// </remarks> |
| 28 | +public sealed class AgentExecutor<T> : IAgent<T> |
| 29 | +{ |
| 30 | + private readonly IChatClient<T> _client; |
| 31 | + private readonly ToolCollection _tools; |
| 32 | + private readonly AgentExecutorOptions _options; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Initializes a new <see cref="AgentExecutor{T}"/>. |
| 36 | + /// </summary> |
| 37 | + /// <param name="client">The chat model the agent drives.</param> |
| 38 | + /// <param name="tools">The tools the agent may use. <c>null</c> means the agent has no tools.</param> |
| 39 | + /// <param name="options">Agent settings. <c>null</c> uses defaults.</param> |
| 40 | + /// <exception cref="ArgumentNullException">Thrown when <paramref name="client"/> is <c>null</c>.</exception> |
| 41 | + public AgentExecutor(IChatClient<T> client, ToolCollection? tools = null, AgentExecutorOptions? options = null) |
| 42 | + { |
| 43 | + Guard.NotNull(client); |
| 44 | + _client = client; |
| 45 | + _tools = tools ?? new ToolCollection(); |
| 46 | + _options = options ?? new AgentExecutorOptions(); |
| 47 | + } |
| 48 | + |
| 49 | + /// <inheritdoc/> |
| 50 | + public string Name => |
| 51 | + _options.Name is { } name && name.Trim().Length > 0 ? name : "agent"; |
| 52 | + |
| 53 | + /// <inheritdoc/> |
| 54 | + public string Description => _options.Description ?? string.Empty; |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// Runs the agent against a single user message. |
| 58 | + /// </summary> |
| 59 | + /// <param name="userMessage">The user's request.</param> |
| 60 | + /// <param name="cancellationToken">Token used to cancel the run.</param> |
| 61 | + /// <returns>A task producing the agent's <see cref="AgentRunResult"/>.</returns> |
| 62 | + /// <exception cref="ArgumentNullException">Thrown when <paramref name="userMessage"/> is <c>null</c>.</exception> |
| 63 | + public Task<AgentRunResult> RunAsync(string userMessage, CancellationToken cancellationToken = default) |
| 64 | + { |
| 65 | + Guard.NotNull(userMessage); |
| 66 | + return RunAsync(new[] { ChatMessage.User(userMessage) }, cancellationToken); |
| 67 | + } |
| 68 | + |
| 69 | + /// <inheritdoc/> |
| 70 | + /// <exception cref="ArgumentNullException">Thrown when <paramref name="messages"/> is <c>null</c>.</exception> |
| 71 | + /// <exception cref="ArgumentException">Thrown when <paramref name="messages"/> is empty.</exception> |
| 72 | + public async Task<AgentRunResult> RunAsync( |
| 73 | + IReadOnlyList<ChatMessage> messages, |
| 74 | + CancellationToken cancellationToken = default) |
| 75 | + { |
| 76 | + Guard.NotNull(messages); |
| 77 | + if (messages.Count == 0) |
| 78 | + { |
| 79 | + throw new ArgumentException("The conversation must contain at least one message.", nameof(messages)); |
| 80 | + } |
| 81 | + |
| 82 | + var transcript = new List<ChatMessage>(messages.Count + 4); |
| 83 | + var systemPrompt = _options.SystemPrompt; |
| 84 | + if (systemPrompt is { } prompt && prompt.Trim().Length > 0) |
| 85 | + { |
| 86 | + transcript.Add(ChatMessage.System(prompt)); |
| 87 | + } |
| 88 | + |
| 89 | + transcript.AddRange(messages); |
| 90 | + |
| 91 | + var hasTools = _tools.Count > 0; |
| 92 | + var requestOptions = new ChatOptions |
| 93 | + { |
| 94 | + Temperature = _options.Temperature, |
| 95 | + MaxOutputTokens = _options.MaxOutputTokens, |
| 96 | + Tools = hasTools ? _tools.GetDefinitions() : null, |
| 97 | + ToolChoice = hasTools ? (_options.ToolChoice ?? ToolChoiceMode.Auto) : null, |
| 98 | + }; |
| 99 | + |
| 100 | + var maxIterations = _options.MaxIterations is { } configured && configured > 0 |
| 101 | + ? configured |
| 102 | + : AgentExecutorOptions.DefaultMaxIterations; |
| 103 | + |
| 104 | + var inputTokens = 0; |
| 105 | + var outputTokens = 0; |
| 106 | + var sawUsage = false; |
| 107 | + |
| 108 | + for (var iteration = 1; iteration <= maxIterations; iteration++) |
| 109 | + { |
| 110 | + cancellationToken.ThrowIfCancellationRequested(); |
| 111 | + |
| 112 | + var response = await _client.GetResponseAsync(transcript, requestOptions, cancellationToken) |
| 113 | + .ConfigureAwait(false); |
| 114 | + transcript.Add(response.Message); |
| 115 | + |
| 116 | + if (response.Usage is { } usage) |
| 117 | + { |
| 118 | + sawUsage = true; |
| 119 | + inputTokens += usage.InputTokens; |
| 120 | + outputTokens += usage.OutputTokens; |
| 121 | + } |
| 122 | + |
| 123 | + var toolCalls = response.Message.ToolCalls; |
| 124 | + var wantsTools = response.FinishReason == ChatFinishReason.ToolCalls || toolCalls.Count > 0; |
| 125 | + |
| 126 | + if (hasTools && wantsTools && toolCalls.Count > 0) |
| 127 | + { |
| 128 | + foreach (var call in toolCalls) |
| 129 | + { |
| 130 | + cancellationToken.ThrowIfCancellationRequested(); |
| 131 | + var toolMessage = await _tools.InvokeToToolMessageAsync(call, cancellationToken) |
| 132 | + .ConfigureAwait(false); |
| 133 | + transcript.Add(toolMessage); |
| 134 | + } |
| 135 | + |
| 136 | + continue; |
| 137 | + } |
| 138 | + |
| 139 | + return AgentRunResult.Finished( |
| 140 | + response.Message.Text, |
| 141 | + transcript, |
| 142 | + iteration, |
| 143 | + sawUsage ? new ChatUsage(inputTokens, outputTokens) : null); |
| 144 | + } |
| 145 | + |
| 146 | + var lastText = transcript.Count > 0 ? transcript[transcript.Count - 1].Text : string.Empty; |
| 147 | + return AgentRunResult.Stopped( |
| 148 | + lastText, |
| 149 | + transcript, |
| 150 | + maxIterations, |
| 151 | + sawUsage ? new ChatUsage(inputTokens, outputTokens) : null); |
| 152 | + } |
| 153 | +} |
0 commit comments