BotSharp/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.LoadAgent.cs

70 lines
1.8 KiB
C#
Raw Normal View History

2023-08-14 17:00:01 +00:00
using BotSharp.Abstraction.Agents.Models;
2023-09-20 10:31:50 +00:00
using BotSharp.Abstraction.Routing;
using BotSharp.Abstraction.Routing.Settings;
2023-08-30 23:29:01 +00:00
using BotSharp.Abstraction.Templating;
2023-08-14 17:00:01 +00:00
namespace BotSharp.Core.Agents.Services;
public partial class AgentService
{
2023-09-08 17:03:49 +00:00
#if !DEBUG
[MemoryCache(10 * 60)]
#endif
2023-08-14 17:00:01 +00:00
public async Task<Agent> LoadAgent(string id)
{
var hooks = _services.GetServices<IAgentHook>();
// Before agent is loaded.
foreach (var hook in hooks)
{
hook.OnAgentLoading(ref id);
}
2023-09-25 22:46:00 +00:00
var agent = await GetAgent(id);
var templateDict = new Dictionary<string, object>();
PopulateState(templateDict);
2023-08-14 17:00:01 +00:00
// After agent is loaded
foreach (var hook in hooks)
{
hook.SetAget(agent);
if (!string.IsNullOrEmpty(agent.Instruction))
{
hook.OnInstructionLoaded(agent.Instruction, templateDict);
2023-08-14 17:00:01 +00:00
}
2023-09-06 04:41:49 +00:00
if (!agent.Functions.IsNullOrEmpty())
2023-08-14 17:00:01 +00:00
{
var functions = agent.Functions;
hook.OnFunctionsLoaded(ref functions);
}
if (!string.IsNullOrEmpty(agent.Samples))
{
var samples = agent.Samples;
hook.OnSamplesLoaded(ref samples);
}
2023-08-17 04:04:23 +00:00
hook.OnAgentLoaded(agent);
2023-08-14 17:00:01 +00:00
}
// render liquid template
2023-08-30 23:29:01 +00:00
var render = _services.GetRequiredService<ITemplateRender>();
agent.Instruction = render.Render(agent.Instruction, templateDict);
2023-08-17 04:04:23 +00:00
_logger.LogInformation($"Loaded agent {agent}.");
2023-08-14 17:00:01 +00:00
return agent;
}
private void PopulateState(Dictionary<string, object> dict)
{
2023-09-06 03:19:36 +00:00
var conv = _services.GetRequiredService<IConversationService>();
foreach (var t in conv.States.GetStates())
{
dict[t.Key] = t.Value;
}
}
2023-08-14 17:00:01 +00:00
}