BotSharp/src/Infrastructure/BotSharp.Core/Instructs/Services/InstructService.Execute.cs

199 lines
6.4 KiB
C#
Raw Normal View History

2025-09-30 20:03:06 +00:00
using BotSharp.Abstraction.CodeInterpreter;
2024-10-17 23:17:38 +00:00
using BotSharp.Abstraction.Instructs;
using BotSharp.Abstraction.Instructs.Models;
using BotSharp.Abstraction.MLTasks;
2025-09-30 20:03:06 +00:00
using BotSharp.Abstraction.Models;
2024-10-17 23:17:38 +00:00
namespace BotSharp.Core.Instructs;
public partial class InstructService
{
2025-10-01 20:52:43 +00:00
private const string DEFAULT_CODE_INTERPRETER = "python-interpreter";
2025-09-30 20:03:06 +00:00
public async Task<InstructResult> Execute(
string agentId,
RoleDialogModel message,
string? instruction = null,
2025-09-30 20:26:32 +00:00
string? templateName = null,
2025-09-30 20:03:06 +00:00
IEnumerable<InstructFileModel>? files = null,
CodeInstructOptions? codeOptions = null)
2024-10-17 23:17:38 +00:00
{
var agentService = _services.GetRequiredService<IAgentService>();
Agent agent = await agentService.LoadAgent(agentId);
2025-09-30 20:03:06 +00:00
var response = new InstructResult
{
MessageId = message.MessageId,
2025-10-01 20:52:43 +00:00
Template = templateName
2025-09-30 20:03:06 +00:00
};
2025-08-26 04:42:21 +00:00
if (agent == null)
{
2025-09-30 20:03:06 +00:00
response.Text = $"Agent (id: {agentId}) does not exist!";
return response;
2025-08-26 04:42:21 +00:00
}
2024-10-17 23:17:38 +00:00
if (agent.Disabled)
{
var content = $"This agent ({agent.Name}) is disabled, please install the corresponding plugin ({agent.Plugin.Name}) to activate this agent.";
2025-09-30 20:03:06 +00:00
response.Text = content;
return response;
}
// Run code template
2025-10-01 20:52:43 +00:00
var (text, isCodeComplete) = await GetCodeResponse(agentId, templateName, codeOptions);
if (isCodeComplete)
2025-09-30 20:03:06 +00:00
{
2025-10-01 20:52:43 +00:00
response.Text = text;
2025-09-30 20:03:06 +00:00
return response;
2024-10-17 23:17:38 +00:00
}
2025-10-01 20:52:43 +00:00
2024-10-17 23:17:38 +00:00
// Trigger before completion hooks
2025-05-16 01:19:55 +00:00
var hooks = _services.GetHooks<IInstructHook>(agentId);
2024-10-17 23:17:38 +00:00
foreach (var hook in hooks)
{
await hook.BeforeCompletion(agent, message);
// Interrupted by hook
if (message.StopCompletion)
{
return new InstructResult
{
MessageId = message.MessageId,
Text = message.Content
};
}
}
2025-10-01 20:52:43 +00:00
2025-03-05 23:22:46 +00:00
var provider = string.Empty;
var model = string.Empty;
2024-10-17 23:17:38 +00:00
// Render prompt
2025-09-30 20:26:32 +00:00
var prompt = string.IsNullOrEmpty(templateName) ?
2025-08-13 18:54:14 +00:00
agentService.RenderInstruction(agent) :
2025-09-30 20:26:32 +00:00
agentService.RenderTemplate(agent, templateName);
2024-10-17 23:17:38 +00:00
var completer = CompletionProvider.GetCompletion(_services,
agentConfig: agent.LlmConfig);
if (completer is ITextCompletion textCompleter)
{
2025-03-05 23:22:46 +00:00
instruction = null;
provider = textCompleter.Provider;
model = textCompleter.Model;
2024-10-17 23:17:38 +00:00
var result = await textCompleter.GetCompletion(prompt, agentId, message.MessageId);
response.Text = result;
}
else if (completer is IChatCompletion chatCompleter)
{
2025-03-05 23:22:46 +00:00
provider = chatCompleter.Provider;
model = chatCompleter.Model;
2024-10-17 23:17:38 +00:00
if (instruction == "#TEMPLATE#")
{
instruction = prompt;
prompt = message.Content;
}
var result = await chatCompleter.GetChatCompletions(new Agent
{
Id = agentId,
Name = agent.Name,
Instruction = instruction
}, new List<RoleDialogModel>
{
new RoleDialogModel(AgentRole.User, prompt)
{
CurrentAgentId = agentId,
2025-03-31 20:16:46 +00:00
MessageId = message.MessageId,
2025-08-26 04:42:21 +00:00
Files = files?.Select(x => new BotSharpFile { FileUrl = x.FileUrl, FileData = x.FileData, ContentType = x.ContentType }).ToList() ?? []
2024-10-17 23:17:38 +00:00
}
});
response.Text = result.Content;
}
foreach (var hook in hooks)
{
await hook.AfterCompletion(agent, response);
2025-03-05 23:22:46 +00:00
await hook.OnResponseGenerated(new InstructResponseModel
{
AgentId = agentId,
Provider = provider,
Model = model,
2025-09-30 20:26:32 +00:00
TemplateName = templateName,
2025-03-05 23:22:46 +00:00
UserMessage = prompt,
SystemInstruction = instruction,
CompletionText = response.Text
});
2024-10-17 23:17:38 +00:00
}
return response;
}
2025-10-01 20:52:43 +00:00
private async Task<(string?, bool)> GetCodeResponse(string agentId, string templateName, CodeInstructOptions? codeOptions)
{
var state = _services.GetRequiredService<IConversationStateService>();
var db = _services.GetRequiredService<IBotSharpRepository>();
var isComplete = false;
var response = string.Empty;
var codeProvider = codeOptions?.CodeInterpretProvider.IfNullOrEmptyAs(DEFAULT_CODE_INTERPRETER);
var codeInterpreter = _services.GetServices<ICodeInterpretService>()
.FirstOrDefault(x => x.Provider.IsEqualTo(codeProvider));
if (codeInterpreter == null)
{
_logger.LogWarning($"No code interpreter found. (Agent: {agentId}, Code interpreter: {codeProvider})");
return (response, isComplete);
}
// Get code script name
var scriptName = string.Empty;
if (!string.IsNullOrEmpty(codeOptions?.CodeScriptName))
{
scriptName = codeOptions.CodeScriptName;
}
else if (!string.IsNullOrEmpty(templateName))
{
scriptName = $"{templateName}.py";
}
if (string.IsNullOrEmpty(scriptName))
{
_logger.LogWarning($"Empty code script name. (Agent: {agentId}, {scriptName})");
return (response, isComplete);
}
// Get code script
var codeScript = db.GetAgentCodeScript(agentId, scriptName);
if (string.IsNullOrWhiteSpace(codeScript))
{
_logger.LogWarning($"Empty code script. (Agent: {agentId}, {scriptName})");
return (response, isComplete);
}
// Get code arguments
var arguments = codeOptions?.Arguments ?? [];
if (arguments.IsNullOrEmpty())
{
arguments = state.GetStates().Select(x => new KeyValue(x.Key, x.Value)).ToList();
}
// Run code script
var result = await codeInterpreter.RunCode(codeScript, options: new()
{
Arguments = arguments
});
response = result?.Result?.ToString();
isComplete = true;
return (response, isComplete);
}
2024-10-17 23:17:38 +00:00
}