Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions src/Infrastructure/BotSharp.Abstraction/Agents/AgentHookBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
protected readonly IServiceProvider _services;
protected readonly AgentSettings _settings;

public AgentHookBase(IServiceProvider services, AgentSettings settings)

Check warning on line 16 in src/Infrastructure/BotSharp.Abstraction/Agents/AgentHookBase.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Non-nullable field '_agent' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable.
{
_services = services;
_settings = settings;
Expand All @@ -24,44 +24,45 @@
_agent = agent;
}

public virtual bool OnAgentLoading(ref string id)
public virtual Task<string?> OnAgentLoading(string id)
{
return true;
return Task.FromResult<string?>(id);
}

public virtual bool OnInstructionLoaded(string template, IDictionary<string, object> dict)
public virtual Task<bool> OnInstructionLoaded(string template, IDictionary<string, object> dict)
{
dict["current_date"] = $"{DateTime.Now:MMM dd, yyyy}";
dict["current_time"] = $"{DateTime.Now:hh:mm tt}";
dict["current_weekday"] = $"{DateTime.Now:dddd}";
dict["current_utc_datetime"] = $"{DateTime.UtcNow}";

return true;
return Task.FromResult(true);
}

public virtual bool OnFunctionsLoaded(List<FunctionDef> functions)
public virtual Task<bool> OnFunctionsLoaded(List<FunctionDef> functions)
{
_agent.Functions = functions;
return true;
return Task.FromResult(true);
}

public virtual bool OnSamplesLoaded(List<string> samples)
public virtual Task<bool> OnSamplesLoaded(List<string> samples)
{
_agent.Samples = samples;
return true;
return Task.FromResult(true);
}

public virtual void OnAgentLoaded(Agent agent)
public virtual Task OnAgentLoaded(Agent agent)
{
return Task.CompletedTask;
}

public virtual void OnAgentUtilityLoaded(Agent agent)
public virtual Task OnAgentUtilityLoaded(Agent agent)
{

return Task.CompletedTask;
}

public virtual void OnAgentMcpToolLoaded(Agent agent)
public virtual Task OnAgentMcpToolLoaded(Agent agent)
{

return Task.CompletedTask;
}
}
18 changes: 9 additions & 9 deletions src/Infrastructure/BotSharp.Abstraction/Agents/IAgentHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@ public interface IAgentHook : IHookBase

/// <summary>
/// Triggered when agent is loading.
/// Return different agent for redirection purpose.
/// Return different agent id for redirection purpose.
/// </summary>
/// <param name="id">Agent Id</param>
/// <returns></returns>
bool OnAgentLoading(ref string id);
/// <returns>New agent id if redirection is needed, null otherwise</returns>
Task<string?> OnAgentLoading(string id);

bool OnInstructionLoaded(string template, IDictionary<string, object> dict);
Task<bool> OnInstructionLoaded(string template, IDictionary<string, object> dict);

bool OnFunctionsLoaded(List<FunctionDef> functions);
Task<bool> OnFunctionsLoaded(List<FunctionDef> functions);

bool OnSamplesLoaded(List<string> samples);
Task<bool> OnSamplesLoaded(List<string> samples);

void OnAgentUtilityLoaded(Agent agent);
Task OnAgentUtilityLoaded(Agent agent);

void OnAgentMcpToolLoaded(Agent agent);
Task OnAgentMcpToolLoaded(Agent agent);

/// <summary>
/// Triggered when agent is loaded completely.
/// </summary>
/// <param name="agent"></param>
/// <returns></returns>
void OnAgentLoaded(Agent agent);
Task OnAgentLoaded(Agent agent);
}
16 changes: 8 additions & 8 deletions src/Infrastructure/BotSharp.Core.A2A/Hooks/A2AAgentHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,29 @@ public A2AAgentHook(IServiceProvider services, IA2AService a2aService, A2ASettin
_a2aSettings = a2aSettings;
}

public override bool OnAgentLoading(ref string id)
public override async Task<string?> OnAgentLoading(string id)
{
var agentId = id;
var remoteConfig = _a2aSettings.Agents?.FirstOrDefault(x => x.Id == agentId);
var remoteConfig = _a2aSettings.Agents?.FirstOrDefault(x => x.Id == id);
if (remoteConfig != null)
{
return true;
return id; // No redirection needed, continue with current id
}
return base.OnAgentLoading(ref id);
return await base.OnAgentLoading(id);
}

public override void OnAgentLoaded(Agent agent)
public override async Task OnAgentLoaded(Agent agent)
{
// Check if this is an A2A remote agent
if (agent.Type != AgentType.A2ARemote)
{
await base.OnAgentLoaded(agent);
return;
}

var remoteConfig = _a2aSettings.Agents?.FirstOrDefault(x => x.Id == agent.Id);
if (remoteConfig != null)
{
var agentCard = _a2aService.GetCapabilitiesAsync(remoteConfig.Endpoint).GetAwaiter().GetResult();
var agentCard = await _a2aService.GetCapabilitiesAsync(remoteConfig.Endpoint);
if (agentCard != null)
{
agent.Name = agentCard.Name;
Expand Down Expand Up @@ -83,6 +83,6 @@ public override void OnAgentLoaded(Agent agent)
});
}
}
base.OnAgentLoaded(agent);
await base.OnAgentLoaded(agent);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ public BasicAgentHook(IServiceProvider services, AgentSettings settings)
{
}

public override void OnAgentUtilityLoaded(Agent agent)
public override Task OnAgentUtilityLoaded(Agent agent)
{
var conv = _services.GetRequiredService<IConversationService>();
var isConvMode = conv.IsConversationMode();
if (!isConvMode) return;
if (!isConvMode) return Task.CompletedTask;

agent.Utilities ??= [];
agent.SecondaryFunctions ??= [];
Expand All @@ -26,6 +26,8 @@ public override void OnAgentUtilityLoaded(Agent agent)
agent.SecondaryFunctions = agent.SecondaryFunctions.Concat(functions).DistinctBy(x => x.Name, StringComparer.OrdinalIgnoreCase).ToList();
var contents = templates.Select(x => x.Content);
agent.SecondaryInstructions = agent.SecondaryInstructions.Concat(contents).Distinct(StringComparer.OrdinalIgnoreCase).ToList();

return Task.CompletedTask;
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using BotSharp.Abstraction.Hooks;
using BotSharp.Abstraction.Routing.Models;
using System.Collections.Concurrent;

Expand All @@ -15,7 +16,16 @@ public async Task<Agent> LoadAgent(string id, bool loadUtility = true)
return null;
}

HookEmitter.Emit<IAgentHook>(_services, hook => hook.OnAgentLoading(ref id), id);
var hooks = _services.GetHooks<IAgentHook>(id);
foreach (var hook in hooks)
{
var newId = await hook.OnAgentLoading(id);
if (!string.IsNullOrEmpty(newId) && newId != id)
{
id = newId;
break; // Only the first hook that redirects takes effect
}
}

var agent = await GetAgent(id);
if (agent == null)
Expand All @@ -35,35 +45,35 @@ public async Task<Agent> LoadAgent(string id, bool loadUtility = true)
PopulateState(agent);

// After agent is loaded
HookEmitter.Emit<IAgentHook>(_services, hook => {
await HookEmitter.Emit<IAgentHook>(_services, async hook => {
hook.SetAgent(agent);

if (!string.IsNullOrEmpty(agent.Instruction))
{
hook.OnInstructionLoaded(agent.Instruction, agent.TemplateDict);
await hook.OnInstructionLoaded(agent.Instruction, agent.TemplateDict);
}

if (agent.Functions != null)
{
hook.OnFunctionsLoaded(agent.Functions);
await hook.OnFunctionsLoaded(agent.Functions);
}

if (agent.Samples != null)
{
hook.OnSamplesLoaded(agent.Samples);
await hook.OnSamplesLoaded(agent.Samples);
}

if (loadUtility && !agent.Utilities.IsNullOrEmpty())
{
hook.OnAgentUtilityLoaded(agent);
await hook.OnAgentUtilityLoaded(agent);
}

if (!agent.McpTools.IsNullOrEmpty())
{
hook.OnAgentMcpToolLoaded(agent);
await hook.OnAgentMcpToolLoaded(agent);
}

hook.OnAgentLoaded(agent);
await hook.OnAgentLoaded(agent);

}, id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public McpToolAgentHook(IServiceProvider services, AgentSettings settings)
{
}

public override void OnAgentMcpToolLoaded(Agent agent)
public override async Task OnAgentMcpToolLoaded(Agent agent)
{
if (agent.Type == AgentType.Routing)
{
Expand All @@ -27,7 +27,7 @@ public override void OnAgentMcpToolLoaded(Agent agent)

agent.SecondaryFunctions ??= [];

var functions = GetMcpContent(agent).ConfigureAwait(false).GetAwaiter().GetResult();
var functions = await GetMcpContent(agent);
agent.SecondaryFunctions = agent.SecondaryFunctions.Concat(functions).DistinctBy(x => x.Name, StringComparer.OrdinalIgnoreCase).ToList();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public RoutingAgentHook(IServiceProvider services, AgentSettings settings, Routi
_routingSetting = routingSetting;
}

public override bool OnInstructionLoaded(string template, IDictionary<string, object> dict)
public override async Task<bool> OnInstructionLoaded(string template, IDictionary<string, object> dict)
{
if (_agent.Type != AgentType.Routing)
{
return base.OnInstructionLoaded(template, dict);
return await base.OnInstructionLoaded(template, dict);
}
dict["router"] = _agent;

Expand Down Expand Up @@ -59,10 +59,10 @@ public override bool OnInstructionLoaded(string template, IDictionary<string, ob

dict["routing_agents"] = agents;

return base.OnInstructionLoaded(template, dict);
return await base.OnInstructionLoaded(template, dict);
}

public override bool OnFunctionsLoaded(List<FunctionDef> functions)
public override async Task<bool> OnFunctionsLoaded(List<FunctionDef> functions)
{
if (_agent.Type == AgentType.Task)
{
Expand All @@ -73,7 +73,7 @@ public override bool OnFunctionsLoaded(List<FunctionDef> functions)
if (rule != null)
{
var agentService = _services.GetRequiredService<IAgentService>();
var redirectAgent = agentService.GetAgent(rule.RedirectTo).ConfigureAwait(false).GetAwaiter().GetResult();
var redirectAgent = await agentService.GetAgent(rule.RedirectTo);

var json = JsonSerializer.Serialize(new
{
Expand Down Expand Up @@ -111,6 +111,6 @@ public override bool OnFunctionsLoaded(List<FunctionDef> functions)
}
}

return base.OnFunctionsLoaded(functions);
return await base.OnFunctionsLoaded(functions);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
using BotSharp.Abstraction.Agents;
using BotSharp.Abstraction.Agents.Settings;
using BotSharp.Abstraction.Knowledges;
using BotSharp.Abstraction.MLTasks;
using BotSharp.Plugin.Planner.Enums;

namespace BotSharp.Plugin.Planner.SqlGeneration.Hooks;

public class SqlPlannerAgentHook : AgentHookBase
Expand All @@ -9,18 +15,18 @@ public SqlPlannerAgentHook(IServiceProvider services, AgentSettings settings)
{
}

public override bool OnInstructionLoaded(string template, IDictionary<string, object> dict)
public override async Task<bool> OnInstructionLoaded(string template, IDictionary<string, object> dict)
{
var knowledgeHooks = _services.GetServices<IKnowledgeHook>();

// Get global knowledges
var knowledges = new List<string>();
foreach (var hook in knowledgeHooks)
{
var k = hook.GetGlobalKnowledges(new RoleDialogModel(AgentRole.User, template)
var k = await hook.GetGlobalKnowledges(new RoleDialogModel(AgentRole.User, template)
{
CurrentAgentId = PlannerAgentId.SqlPlanner
}).ConfigureAwait(false).GetAwaiter().GetResult();
});
knowledges.AddRange(k);
}
dict["global_knowledges"] = knowledges;
Expand Down
4 changes: 2 additions & 2 deletions tests/BotSharp.Plugin.PizzaBot/Hooks/CommonAgentHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ public CommonAgentHook(IServiceProvider services, AgentSettings settings)
{
}

public override bool OnInstructionLoaded(string template, IDictionary<string, object> dict)
public override async Task<bool> OnInstructionLoaded(string template, IDictionary<string, object> dict)
{
dict["current_date"] = DateTime.Now.ToString("MM/dd/yyyy");
dict["current_time"] = DateTime.Now.ToString("hh:mm tt");
dict["current_weekday"] = DateTime.Now.DayOfWeek;
return base.OnInstructionLoaded(template, dict);
return await base.OnInstructionLoaded(template, dict);
}
}
4 changes: 2 additions & 2 deletions tests/BotSharp.Plugin.PizzaBot/Hooks/PizzaBotAgentHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public PizzaBotAgentHook(IServiceProvider services, AgentSettings settings)
{
}

public override bool OnInstructionLoaded(string template, IDictionary<string, object> dict)
public override async Task<bool> OnInstructionLoaded(string template, IDictionary<string, object> dict)
{
return base.OnInstructionLoaded(template, dict);
return await base.OnInstructionLoaded(template, dict);
}
}
Loading