BotSharp/src/Infrastructure/BotSharp.Core/Planning/HFPlanner.cs

98 lines
2.8 KiB
C#
Raw Normal View History

2023-10-28 20:59:26 +00:00
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Functions.Models;
using BotSharp.Abstraction.Planning;
2023-10-29 01:54:10 +00:00
using BotSharp.Abstraction.Repositories;
using BotSharp.Abstraction.Routing.Models;
2023-10-30 16:48:18 +00:00
using BotSharp.Abstraction.Routing.Settings;
2023-10-28 20:59:26 +00:00
using BotSharp.Abstraction.Templating;
namespace BotSharp.Core.Planning;
2023-10-30 16:48:18 +00:00
/// <summary>
/// Human feedback based planner
/// </summary>
public class HFPlanner : IPlaner
2023-10-28 20:59:26 +00:00
{
private readonly IServiceProvider _services;
private readonly ILogger _logger;
2023-10-30 16:48:18 +00:00
public HFPlanner(IServiceProvider services, ILogger<HFPlanner> logger)
2023-10-28 20:59:26 +00:00
{
_services = services;
_logger = logger;
}
2023-10-30 16:48:18 +00:00
public async Task<FunctionCallFromLlm> GetNextInstruction(Agent router, string messageId)
2023-10-28 20:59:26 +00:00
{
var next = GetNextStepPrompt(router);
RoleDialogModel response = default;
var inst = new FunctionCallFromLlm();
2023-10-30 16:48:18 +00:00
var completion = CompletionProvider.GetChatCompletion(_services);
2023-10-28 20:59:26 +00:00
int retryCount = 0;
while (retryCount < 3)
{
try
{
response = completion.GetChatCompletions(router, new List<RoleDialogModel>
{
2023-10-29 01:54:10 +00:00
new RoleDialogModel(AgentRole.User, next)
2023-10-30 16:48:18 +00:00
{
MessageId = messageId
}
2023-10-28 20:59:26 +00:00
});
inst = response.Content.JsonContent<FunctionCallFromLlm>();
break;
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}: {response.Content}");
inst.Function = "response_to_user";
inst.Response = ex.Message;
inst.AgentName = "Router";
}
finally
{
retryCount++;
}
}
return inst;
}
2023-10-29 01:54:10 +00:00
public async Task<bool> AgentExecuting(FunctionCallFromLlm inst, RoleDialogModel message)
{
2023-10-30 16:48:18 +00:00
if (!string.IsNullOrEmpty(inst.AgentName))
{
var db = _services.GetRequiredService<IBotSharpRepository>();
var agent = db.GetAgents(inst.AgentName).FirstOrDefault();
2023-10-29 01:54:10 +00:00
2023-10-30 16:48:18 +00:00
var context = _services.GetRequiredService<RoutingContext>();
context.Push(agent.Id);
}
2023-10-29 01:54:10 +00:00
return true;
}
2023-10-28 20:59:26 +00:00
public async Task<bool> AgentExecuted(FunctionCallFromLlm inst, RoleDialogModel message)
{
2023-10-29 01:54:10 +00:00
var context = _services.GetRequiredService<RoutingContext>();
context.Pop();
2023-10-28 20:59:26 +00:00
return true;
}
private string GetNextStepPrompt(Agent router)
{
var template = router.Templates.First(x => x.Name == "next_step_prompt").Content;
var render = _services.GetRequiredService<ITemplateRender>();
return render.Render(template, new Dictionary<string, object>
{
});
}
}