| using System; |
| using System.Threading.Tasks; |
| using Microsoft.Extensions.AI; |
| namespace OnDeviceAgent.AgentCore |
| { |
|
|
| public abstract class AgentToolBase : IAgentTool |
| { |
| public abstract string Name { get; } |
| public abstract string Description { get; } |
| public abstract AITool ToAIFunction(AgentToolContext context); |
|
|
| protected async Task<string> RunGuarded(AgentToolContext ctx, string argsJson, Func<Task<string>> body, string notConfiguredMessage = null) |
| { |
| if (!ctx.Tracker.TryBegin(Name, "Tool " + Name + " called.", argsJson, out var blocked)) |
| return blocked; |
|
|
| if (!await ctx.Approval.IsApprovedOrRequest(this, ctx).ConfigureAwait(false)) |
| return ctx.Tracker.Finish(Name, argsJson, |
| "Approval required for tool " + Name + ". Choose an approval option in the modal to run this command."); |
|
|
| if (body == null) |
| return ctx.Tracker.Finish(Name, argsJson, notConfiguredMessage ?? (Name + " is not configured.")); |
|
|
| try |
| { |
| return ctx.Tracker.Finish(Name, argsJson, await body().ConfigureAwait(false)); |
| } |
| catch (OperationCanceledException) |
| { |
| throw; |
| } |
| catch (Exception ex) |
| { |
| return ctx.Tracker.Finish(Name, argsJson, Name + " failed: " + ex.Message); |
| } |
| } |
| } |
| } |
|
|