2024-11-26 00:06:26 +00:00
|
|
|
/*****************************************************************************
|
|
|
|
|
Copyright 2024 Written by Haiping Chen. All Rights Reserved.
|
|
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
|
limitations under the License.
|
|
|
|
|
******************************************************************************/
|
|
|
|
|
|
2024-12-10 18:30:41 +00:00
|
|
|
namespace BotSharp.Plugin.Planner.Sequential;
|
2024-01-23 23:14:57 +00:00
|
|
|
|
2024-11-26 00:06:26 +00:00
|
|
|
/// <summary>
|
2024-12-10 18:30:41 +00:00
|
|
|
/// A Sequential Planner for a large language model (LLM) is a framework or methodology to execute some list tasks in a predefined order by the user,
|
|
|
|
|
/// LLM can follow to produce an organized and coherent output.
|
|
|
|
|
/// Sequential Planners are useful for tasks that involve multiple stages of reasoning, information retrieval, or interdependent subtasks.
|
2024-11-26 00:06:26 +00:00
|
|
|
/// </summary>
|
2024-12-10 18:30:41 +00:00
|
|
|
public class SequentialPlanner : ITaskPlanner
|
2024-01-23 23:14:57 +00:00
|
|
|
{
|
|
|
|
|
private readonly IServiceProvider _services;
|
|
|
|
|
private readonly ILogger _logger;
|
2024-12-10 18:30:41 +00:00
|
|
|
public string Name => "Sequential-Planner";
|
2024-02-01 18:32:16 +00:00
|
|
|
public bool HideDialogContext => true;
|
2024-02-02 04:16:57 +00:00
|
|
|
public int MaxLoopCount => 100;
|
|
|
|
|
private FunctionCallFromLlm _lastInst;
|
2024-02-01 18:32:16 +00:00
|
|
|
|
2024-12-10 18:30:41 +00:00
|
|
|
public SequentialPlanner(IServiceProvider services, ILogger<SequentialPlanner> logger)
|
2024-01-23 23:14:57 +00:00
|
|
|
{
|
|
|
|
|
_services = services;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-02 04:16:57 +00:00
|
|
|
public async Task<FunctionCallFromLlm> GetNextInstruction(Agent router, string messageId, List<RoleDialogModel> dialogs)
|
2024-01-23 23:14:57 +00:00
|
|
|
{
|
2024-02-02 04:16:57 +00:00
|
|
|
var decomposation = await GetDecomposedStepAsync(router, messageId, dialogs);
|
|
|
|
|
if (decomposation.TotalRemainingSteps > 0 && _lastInst != null)
|
|
|
|
|
{
|
|
|
|
|
_lastInst.Response = decomposation.Description;
|
2024-03-22 19:06:20 +00:00
|
|
|
_lastInst.NextActionReason = $"Having {decomposation.TotalRemainingSteps} steps left.";
|
2024-02-02 04:16:57 +00:00
|
|
|
return _lastInst;
|
|
|
|
|
}
|
2024-02-06 05:58:38 +00:00
|
|
|
else if (decomposation.TotalRemainingSteps == 0 || decomposation.ShouldStop)
|
2024-02-05 04:22:43 +00:00
|
|
|
{
|
2024-02-08 21:39:56 +00:00
|
|
|
if (!string.IsNullOrEmpty(decomposation.StopReason))
|
2024-02-05 04:22:43 +00:00
|
|
|
{
|
2024-02-08 21:39:56 +00:00
|
|
|
// Tell router all steps are done
|
|
|
|
|
dialogs.Add(new RoleDialogModel(AgentRole.Assistant, decomposation.StopReason)
|
|
|
|
|
{
|
|
|
|
|
CurrentAgentId = router.Id,
|
|
|
|
|
MessageId = messageId
|
|
|
|
|
});
|
|
|
|
|
router.TemplateDict["conversation"] = router.TemplateDict["conversation"].ToString().TrimEnd() +
|
|
|
|
|
$"\r\n{router.Name}: {decomposation.StopReason}";
|
|
|
|
|
}
|
2024-02-05 04:22:43 +00:00
|
|
|
}
|
2024-02-02 04:16:57 +00:00
|
|
|
|
2024-01-23 23:14:57 +00:00
|
|
|
var next = GetNextStepPrompt(router);
|
|
|
|
|
|
|
|
|
|
var inst = new FunctionCallFromLlm();
|
|
|
|
|
|
|
|
|
|
// text completion
|
|
|
|
|
/*var agentService = _services.GetRequiredService<IAgentService>();
|
|
|
|
|
var instruction = agentService.RenderedInstruction(router);
|
|
|
|
|
var content = $"{instruction}\r\n###\r\n{next}";
|
|
|
|
|
content = content + "\r\nResponse: ";
|
|
|
|
|
var completion = CompletionProvider.GetTextCompletion(_services);*/
|
|
|
|
|
|
|
|
|
|
// chat completion
|
|
|
|
|
var completion = CompletionProvider.GetChatCompletion(_services,
|
|
|
|
|
provider: router?.LlmConfig?.Provider,
|
|
|
|
|
model: router?.LlmConfig?.Model);
|
|
|
|
|
|
|
|
|
|
int retryCount = 0;
|
|
|
|
|
while (retryCount < 3)
|
|
|
|
|
{
|
|
|
|
|
string text = string.Empty;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
// text completion
|
|
|
|
|
// text = await completion.GetCompletion(content, router.Id, messageId);
|
2024-02-02 04:16:57 +00:00
|
|
|
dialogs = new List<RoleDialogModel>
|
2024-01-23 23:14:57 +00:00
|
|
|
{
|
|
|
|
|
new RoleDialogModel(AgentRole.User, next)
|
|
|
|
|
{
|
2024-12-10 18:30:41 +00:00
|
|
|
FunctionName = nameof(SequentialPlanner),
|
2024-01-23 23:14:57 +00:00
|
|
|
MessageId = messageId
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
var response = await completion.GetChatCompletions(router, dialogs);
|
|
|
|
|
|
|
|
|
|
inst = response.Content.JsonContent<FunctionCallFromLlm>();
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError($"{ex.Message}: {text}");
|
|
|
|
|
inst.Function = "response_to_user";
|
|
|
|
|
inst.Response = ex.Message;
|
|
|
|
|
inst.AgentName = "Router";
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
retryCount++;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-02 04:16:57 +00:00
|
|
|
if (decomposation.TotalRemainingSteps > 0)
|
|
|
|
|
{
|
|
|
|
|
inst.Response = decomposation.Description;
|
2024-03-22 19:06:20 +00:00
|
|
|
inst.NextActionReason = $"{decomposation.TotalRemainingSteps} steps left.";
|
2024-02-19 22:55:41 +00:00
|
|
|
inst.HandleDialogsByPlanner = true;
|
2024-02-02 04:16:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_lastInst = inst;
|
2024-01-23 23:14:57 +00:00
|
|
|
return inst;
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-19 22:55:41 +00:00
|
|
|
public List<RoleDialogModel> BeforeHandleContext(FunctionCallFromLlm inst, RoleDialogModel message, List<RoleDialogModel> dialogs)
|
|
|
|
|
{
|
|
|
|
|
var taskAgentDialogs = new List<RoleDialogModel>
|
|
|
|
|
{
|
|
|
|
|
new RoleDialogModel(AgentRole.User, inst.Response)
|
|
|
|
|
{
|
|
|
|
|
MessageId = message.MessageId,
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return taskAgentDialogs;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool AfterHandleContext(List<RoleDialogModel> dialogs, List<RoleDialogModel> taskAgentDialogs)
|
|
|
|
|
{
|
|
|
|
|
dialogs.AddRange(taskAgentDialogs.Skip(1));
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> AgentExecuting(Agent router, FunctionCallFromLlm inst, RoleDialogModel message, List<RoleDialogModel> dialogs)
|
2024-01-23 23:14:57 +00:00
|
|
|
{
|
|
|
|
|
// Set user content as Planner's question
|
|
|
|
|
message.FunctionName = inst.Function;
|
|
|
|
|
message.FunctionArgs = inst.Arguments == null ? "{}" : JsonSerializer.Serialize(inst.Arguments);
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-19 22:55:41 +00:00
|
|
|
public async Task<bool> AgentExecuted(Agent router, FunctionCallFromLlm inst, RoleDialogModel message, List<RoleDialogModel> dialogs)
|
2024-01-23 23:14:57 +00:00
|
|
|
{
|
2024-02-28 16:21:14 +00:00
|
|
|
var context = _services.GetRequiredService<IRoutingContext>();
|
2024-01-23 23:14:57 +00:00
|
|
|
|
|
|
|
|
if (message.StopCompletion)
|
|
|
|
|
{
|
2024-12-10 18:30:41 +00:00
|
|
|
context.Empty(reason: $"Agent queue is cleared by {nameof(SequentialPlanner)}");
|
2024-01-23 23:14:57 +00:00
|
|
|
return false;
|
|
|
|
|
}
|
2024-01-29 18:08:49 +00:00
|
|
|
|
2024-01-23 23:14:57 +00:00
|
|
|
// Handover to Router;
|
|
|
|
|
context.Pop();
|
|
|
|
|
|
|
|
|
|
var routing = _services.GetRequiredService<IRoutingService>();
|
2024-10-29 19:59:46 +00:00
|
|
|
routing.Context.ResetRecursiveCounter();
|
2024-01-23 23:14:57 +00:00
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private string GetNextStepPrompt(Agent router)
|
|
|
|
|
{
|
2024-11-26 00:06:26 +00:00
|
|
|
var template = router.Templates.First(x => x.Name == "reasoner.sequential").Content;
|
2024-01-23 23:14:57 +00:00
|
|
|
|
|
|
|
|
var render = _services.GetRequiredService<ITemplateRender>();
|
|
|
|
|
return render.Render(template, new Dictionary<string, object>
|
|
|
|
|
{
|
|
|
|
|
});
|
|
|
|
|
}
|
2024-02-01 18:32:16 +00:00
|
|
|
|
|
|
|
|
public async Task<DecomposedStep> GetDecomposedStepAsync(Agent router, string messageId, List<RoleDialogModel> dialogs)
|
|
|
|
|
{
|
|
|
|
|
var systemPrompt = GetDecomposeTaskPrompt(router);
|
|
|
|
|
|
|
|
|
|
var inst = new DecomposedStep();
|
|
|
|
|
|
2024-02-02 22:36:05 +00:00
|
|
|
var llmProviderService = _services.GetRequiredService<ILlmProviderService>();
|
2024-11-26 00:06:26 +00:00
|
|
|
var model = llmProviderService.GetProviderModel("openai", "gpt-4o");
|
2024-02-02 22:36:05 +00:00
|
|
|
|
2024-02-01 18:32:16 +00:00
|
|
|
// chat completion
|
|
|
|
|
var completion = CompletionProvider.GetChatCompletion(_services,
|
2024-11-26 00:06:26 +00:00
|
|
|
provider: "openai",
|
2024-02-02 22:36:05 +00:00
|
|
|
model: model.Name);
|
2024-02-01 18:32:16 +00:00
|
|
|
|
|
|
|
|
int retryCount = 0;
|
|
|
|
|
while (retryCount < 2)
|
|
|
|
|
{
|
|
|
|
|
string text = string.Empty;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var response = await completion.GetChatCompletions(new Agent
|
|
|
|
|
{
|
|
|
|
|
Id = router.Id,
|
2024-12-10 18:30:41 +00:00
|
|
|
Name = nameof(SequentialPlanner),
|
2024-02-01 18:32:16 +00:00
|
|
|
Instruction = systemPrompt
|
|
|
|
|
}, dialogs);
|
|
|
|
|
|
|
|
|
|
text = response.Content;
|
|
|
|
|
inst = response.Content.JsonContent<DecomposedStep>();
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError($"{ex.Message}: {text}");
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
retryCount++;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return inst;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private string GetDecomposeTaskPrompt(Agent router)
|
|
|
|
|
{
|
2024-11-26 00:06:26 +00:00
|
|
|
var template = router.Templates.First(x => x.Name == "reasoner.sequential.get_remaining_task").Content;
|
2024-02-01 18:32:16 +00:00
|
|
|
|
|
|
|
|
var render = _services.GetRequiredService<ITemplateRender>();
|
|
|
|
|
return render.Render(template, new Dictionary<string, object>
|
|
|
|
|
{
|
|
|
|
|
});
|
|
|
|
|
}
|
2024-01-23 23:14:57 +00:00
|
|
|
}
|