BotSharp/src/Infrastructure/BotSharp.Core/Routing/Planning/NaivePlanner.cs

174 lines
5.9 KiB
C#
Raw Normal View History

2024-03-29 16:46:48 +00:00
using BotSharp.Abstraction.Infrastructures.Enums;
2023-10-29 01:54:10 +00:00
using BotSharp.Abstraction.Routing.Models;
using BotSharp.Abstraction.Routing.Planning;
2023-10-28 20:59:26 +00:00
using BotSharp.Abstraction.Templating;
namespace BotSharp.Core.Routing.Planning;
2023-10-28 20:59:26 +00:00
public class NaivePlanner : IPlaner
{
private readonly IServiceProvider _services;
private readonly ILogger _logger;
public NaivePlanner(IServiceProvider services, ILogger<NaivePlanner> logger)
{
_services = services;
_logger = logger;
}
2024-02-02 04:16:57 +00:00
public async Task<FunctionCallFromLlm> GetNextInstruction(Agent router, string messageId, List<RoleDialogModel> dialogs)
2023-10-28 20:59:26 +00:00
{
var next = GetNextStepPrompt(router);
var inst = new FunctionCallFromLlm();
2023-11-01 01:48:12 +00:00
// text completion
/*var agentService = _services.GetRequiredService<IAgentService>();
2023-10-28 20:59:26 +00:00
var instruction = agentService.RenderedInstruction(router);
2023-10-29 01:54:10 +00:00
var content = $"{instruction}\r\n###\r\n{next}";
2023-10-28 20:59:26 +00:00
content = content + "\r\nResponse: ";
2023-11-01 01:48:12 +00:00
var completion = CompletionProvider.GetTextCompletion(_services);*/
2023-10-28 20:59:26 +00:00
2023-11-01 01:48:12 +00:00
// chat completion
var completion = CompletionProvider.GetChatCompletion(_services,
2023-12-13 18:12:25 +00:00
provider: router?.LlmConfig?.Provider,
model: router?.LlmConfig?.Model);
2023-10-28 20:59:26 +00:00
int retryCount = 0;
while (retryCount < 3)
{
2023-10-30 16:48:18 +00:00
string text = string.Empty;
2023-10-28 20:59:26 +00:00
try
{
2023-11-01 01:48:12 +00:00
// text completion
// text = await completion.GetCompletion(content, router.Id, messageId);
2024-02-02 04:16:57 +00:00
dialogs = new List<RoleDialogModel>
2023-10-30 16:48:18 +00:00
{
2023-11-01 01:48:12 +00:00
new RoleDialogModel(AgentRole.User, next)
{
2024-01-24 23:47:57 +00:00
FunctionName = nameof(NaivePlanner),
2023-11-01 01:48:12 +00:00
MessageId = messageId
}
2023-10-30 16:48:18 +00:00
};
2024-01-14 04:48:26 +00:00
var response = await completion.GetChatCompletions(router, dialogs);
2023-11-01 01:48:12 +00:00
2023-10-28 20:59:26 +00:00
inst = response.Content.JsonContent<FunctionCallFromLlm>();
break;
}
catch (Exception ex)
{
2023-10-30 16:48:18 +00:00
_logger.LogError($"{ex.Message}: {text}");
2023-10-28 20:59:26 +00:00
inst.Function = "response_to_user";
inst.Response = ex.Message;
inst.AgentName = "Router";
}
finally
{
retryCount++;
}
}
2023-10-29 01:54:10 +00:00
// Fix LLM malformed response
FixMalformedResponse(inst);
2023-10-28 20:59:26 +00:00
return inst;
}
2024-02-19 22:55:41 +00:00
public async Task<bool> AgentExecuting(Agent router, FunctionCallFromLlm inst, RoleDialogModel message, List<RoleDialogModel> dialogs)
2023-10-29 01:54:10 +00:00
{
2023-10-30 16:48:18 +00:00
// Set user content as Planner's question
message.FunctionName = inst.Function;
message.FunctionArgs = inst.Arguments == null ? "{}" : JsonSerializer.Serialize(inst.Arguments);
2023-10-29 01:54:10 +00:00
return true;
}
2024-02-19 22:55:41 +00:00
public async Task<bool> AgentExecuted(Agent router, FunctionCallFromLlm inst, RoleDialogModel message, List<RoleDialogModel> dialogs)
2023-10-28 20:59:26 +00:00
{
2024-02-28 16:21:14 +00:00
var context = _services.GetRequiredService<IRoutingContext>();
2024-01-06 22:24:22 +00:00
if (inst.UnmatchedAgent)
{
var unmatchedAgentId = context.GetCurrentAgentId();
2024-01-06 22:24:22 +00:00
// Exclude the wrong routed agent
var agents = router.TemplateDict["routing_agents"] as RoutableAgent[];
2024-01-06 22:24:22 +00:00
router.TemplateDict["routing_agents"] = agents.Where(x => x.AgentId != unmatchedAgentId).ToArray();
// Handover to Router;
context.Pop();
}
else
{
2024-02-28 20:40:59 +00:00
context.Empty(reason: $"Agent queue is cleared by {nameof(NaivePlanner)}");
// context.Push(inst.OriginalAgent, "Push user goal agent");
2024-01-06 22:24:22 +00:00
}
2023-10-28 20:59:26 +00:00
return true;
}
private string GetNextStepPrompt(Agent router)
{
2024-01-23 23:14:57 +00:00
var template = router.Templates.First(x => x.Name == "planner_prompt.naive").Content;
2023-10-28 20:59:26 +00:00
2024-03-15 00:52:58 +00:00
var states = _services.GetRequiredService<IConversationStateService>();
2023-10-28 20:59:26 +00:00
var render = _services.GetRequiredService<ITemplateRender>();
return render.Render(template, new Dictionary<string, object>
{
2024-03-29 16:46:48 +00:00
{ StateConst.EXPECTED_ACTION_AGENT, states.GetState(StateConst.EXPECTED_ACTION_AGENT) },
{ StateConst.EXPECTED_GOAL_AGENT, states.GetState(StateConst.EXPECTED_GOAL_AGENT) }
2023-10-28 20:59:26 +00:00
});
}
2023-10-29 01:54:10 +00:00
/// <summary>
/// Sometimes LLM hallucinates and fails to set function names correctly.
/// </summary>
/// <param name="args"></param>
private void FixMalformedResponse(FunctionCallFromLlm args)
{
var agentService = _services.GetRequiredService<IAgentService>();
var agents = agentService.GetAgents(new AgentFilter
{
2024-01-26 04:32:48 +00:00
Type = AgentType.Task
2024-01-23 05:04:06 +00:00
}).Result.Items.ToList();
2023-10-29 01:54:10 +00:00
var malformed = false;
// Sometimes it populate malformed Function in Agent name
if (!string.IsNullOrEmpty(args.Function) &&
args.Function == args.AgentName)
{
args.Function = "route_to_agent";
malformed = true;
}
// Another case of malformed response
if (string.IsNullOrEmpty(args.AgentName) &&
agents.Select(x => x.Name).Contains(args.Function))
{
args.AgentName = args.Function;
args.Function = "route_to_agent";
malformed = true;
}
// It should be Route to agent, but it is used as Response to user.
if (!string.IsNullOrEmpty(args.AgentName) &&
agents.Select(x => x.Name).Contains(args.AgentName) &&
args.Function != "route_to_agent")
{
args.Function = "route_to_agent";
malformed = true;
}
// Function name shouldn't contain dot symbol
if (!string.IsNullOrEmpty(args.Function) &&
args.Function.Contains('.'))
{
args.Function = args.Function.Split('.').Last();
malformed = true;
}
if (malformed)
{
_logger.LogWarning($"Captured LLM malformed response");
}
}
2023-10-28 20:59:26 +00:00
}