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

96 lines
2.5 KiB
C#
Raw Normal View History

2023-08-14 17:00:01 +00:00
using BotSharp.Abstraction.Agents.Models;
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-10-25 15:48:25 +00:00
[MemoryCache(10 * 60, perInstanceCache: true)]
2023-08-14 17:00:01 +00:00
public async Task<Agent> LoadAgent(string id)
{
2023-12-05 00:12:57 +00:00
if (string.IsNullOrEmpty(id) || id == Guid.Empty.ToString())
{
return null;
}
2023-08-14 17:00:01 +00:00
var hooks = _services.GetServices<IAgentHook>();
// Before agent is loaded.
foreach (var hook in hooks)
{
2023-10-24 21:38:34 +00:00
if (!string.IsNullOrEmpty(hook.SelfId) && hook.SelfId != id)
{
continue;
}
2023-08-14 17:00:01 +00:00
hook.OnAgentLoading(ref id);
}
2023-09-25 22:46:00 +00:00
var agent = await GetAgent(id);
if (agent == null)
{
throw new Exception($"Can't load agent by id: {id}");
}
2023-10-28 20:59:26 +00:00
agent.TemplateDict = new Dictionary<string, object>();
// Populate state into dictionary
PopulateState(agent.TemplateDict);
2023-08-14 17:00:01 +00:00
// After agent is loaded
foreach (var hook in hooks)
{
2023-10-24 21:38:34 +00:00
if (!string.IsNullOrEmpty(hook.SelfId) && hook.SelfId != id)
{
continue;
}
2023-08-14 17:00:01 +00:00
hook.SetAget(agent);
if (!string.IsNullOrEmpty(agent.Instruction))
{
2023-10-28 20:59:26 +00:00
hook.OnInstructionLoaded(agent.Instruction, agent.TemplateDict);
2023-08-14 17:00:01 +00:00
}
2023-09-28 03:31:58 +00:00
if (agent.Functions != null)
2023-08-14 17:00:01 +00:00
{
hook.OnFunctionsLoaded(agent.Functions);
2023-08-14 17:00:01 +00:00
}
2023-10-19 17:24:00 +00:00
if (agent.Samples != null)
2023-08-14 17:00:01 +00:00
{
2023-10-19 17:24:00 +00:00
hook.OnSamplesLoaded(agent.Samples);
2023-08-14 17:00:01 +00:00
}
2023-08-17 04:04:23 +00:00
hook.OnAgentLoaded(agent);
2023-08-14 17:00:01 +00:00
}
2023-08-17 04:04:23 +00:00
_logger.LogInformation($"Loaded agent {agent}.");
2023-08-14 17:00:01 +00:00
return agent;
}
2023-10-28 20:59:26 +00:00
public string RenderedTemplate(Agent agent, string templateName)
{
// render liquid template
var render = _services.GetRequiredService<ITemplateRender>();
var template = agent.Templates.First(x => x.Name == templateName).Content;
return render.Render(template, agent.TemplateDict);
}
public string RenderedInstruction(Agent agent)
{
var render = _services.GetRequiredService<ITemplateRender>();
return render.Render(agent.Instruction, agent.TemplateDict);
}
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
}