// Copyright (c) Microsoft. All rights reserved. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.AI; using Microsoft.Shared.Diagnostics; namespace Microsoft.Agents.AI; /// /// Provides extension methods for configuring and customizing instances. /// public static class FunctionInvocationDelegatingAgentBuilderExtensions { /// /// Adds function invocation callbacks to the pipeline that intercepts and processes calls. /// /// The to which the function invocation callback is added. /// /// A delegate that processes function invocations. The delegate receives the instance, /// the function invocation context, and a continuation delegate representing the next callback in the pipeline. /// It returns a task representing the result of the function invocation. /// /// The instance with the function invocation callback added, enabling method chaining. /// or is . /// /// /// The callback must call the provided continuation delegate to proceed with the function invocation, /// unless it intends to completely replace the function's behavior. /// /// /// The inner agent or the pipeline wrapping it must include a . If one does not exist, /// the added to the pipline by this method will throw an exception when it is invoked. /// /// public static AIAgentBuilder Use(this AIAgentBuilder builder, Func>, CancellationToken, ValueTask> callback) { _ = Throw.IfNull(builder); _ = Throw.IfNull(callback); return builder.Use((innerAgent, _) => { // Function calling requires a ChatClientAgent inner agent. if (innerAgent.GetService() is null) { throw new InvalidOperationException($"The function invocation middleware can only be used with decorations of a {nameof(AIAgent)} that support usage of FunctionInvokingChatClient decorated chat clients."); } return new FunctionInvocationDelegatingAgent(innerAgent, callback); }); } }