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

319 lines
9.9 KiB
C#
Raw Normal View History

2025-09-30 20:03:06 +00:00
using BotSharp.Abstraction.CodeInterpreter;
2025-10-14 18:52:01 +00:00
using BotSharp.Abstraction.Files.Proccessors;
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-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,
2025-10-14 18:52:01 +00:00
CodeInstructOptions? codeOptions = null,
FileInstructOptions? fileOptions = null)
2024-10-17 23:17:38 +00:00
{
var agentService = _services.GetRequiredService<IAgentService>();
2025-10-14 18:52:01 +00:00
var state = _services.GetRequiredService<IConversationStateService>();
2024-10-17 23:17:38 +00:00
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;
}
2025-10-02 00:58:28 +00:00
// Run code template
var codeResponse = await GetCodeResponse(agent, message, templateName, codeOptions);
if (codeResponse != null)
{
return codeResponse;
}
2025-10-01 20:52:43 +00:00
2024-10-17 23:17:38 +00:00
2025-10-02 00:58:28 +00:00
// 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
var provider = string.Empty;
var model = string.Empty;
2025-10-14 18:52:01 +00:00
var result = string.Empty;
// Render prompt
var prompt = string.IsNullOrEmpty(templateName) ?
agentService.RenderInstruction(agent) :
agentService.RenderTemplate(agent, templateName);
var completer = CompletionProvider.GetCompletion(_services,
agentConfig: agent.LlmConfig);
if (completer is ITextCompletion textCompleter)
2024-10-17 23:17:38 +00:00
{
instruction = null;
provider = textCompleter.Provider;
model = textCompleter.Model;
2025-10-14 18:52:01 +00:00
result = await GetTextCompletion(textCompleter, agent, prompt, message.MessageId);
response.Text = result;
2024-10-17 23:17:38 +00:00
}
else if (completer is IChatCompletion chatCompleter)
2024-10-17 23:17:38 +00:00
{
provider = chatCompleter.Provider;
model = chatCompleter.Model;
2025-10-14 18:52:01 +00:00
2025-03-05 23:22:46 +00:00
if (instruction == "#TEMPLATE#")
2024-10-17 23:17:38 +00:00
{
instruction = prompt;
prompt = message.Content;
2025-10-02 00:58:28 +00:00
}
2025-10-14 18:52:01 +00:00
IFileLlmProcessor? fileProcessor = null;
if (!files.IsNullOrEmpty() && !string.IsNullOrEmpty(fileOptions?.FileLlmProcessorProvider))
{
2025-10-14 18:52:01 +00:00
fileProcessor = _services.GetServices<IFileLlmProcessor>()
.FirstOrDefault(x => x.Provider.IsEqualTo(fileOptions?.FileLlmProcessorProvider));
}
if (fileProcessor != null)
2024-10-17 23:17:38 +00:00
{
2025-10-14 18:52:01 +00:00
var inference = await fileProcessor.GetFileLlmInferenceAsync(agent, prompt, files, new FileLlmProcessOptions
2024-10-17 23:17:38 +00:00
{
2025-10-14 18:52:01 +00:00
LlmProvider = provider,
LlModel = model,
Instruction = instruction,
TemplateName = templateName,
Data = state.GetStates().ToDictionary(x => x.Key, x => (object)x.Value)
});
result = inference?.Content ?? string.Empty;
}
else
{
result = await GetChatCompletion(chatCompleter, agent, instruction, prompt, message.MessageId, files);
}
response.Text = result;
2024-10-17 23:17:38 +00:00
}
2025-10-02 00:58:28 +00:00
// After completion hooks
2024-10-17 23:17:38 +00:00
foreach (var hook in hooks)
{
await hook.AfterCompletion(agent, response);
await hook.OnResponseGenerated(new InstructResponseModel
2025-03-05 23:22:46 +00:00
{
AgentId = agentId,
Provider = provider,
Model = model,
TemplateName = templateName,
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
2025-10-02 00:58:28 +00:00
/// <summary>
/// Get code response
2025-10-02 00:58:28 +00:00
/// </summary>
/// <param name="agent"></param>
/// <param name="message"></param>
2025-10-02 00:58:28 +00:00
/// <param name="templateName"></param>
/// <param name="codeOptions"></param>
/// <returns></returns>
2025-10-14 18:52:01 +00:00
private async Task<InstructResult?> GetCodeResponse(
Agent agent,
RoleDialogModel message,
string templateName,
CodeInstructOptions? codeOptions)
2025-10-01 20:52:43 +00:00
{
InstructResult? response = null;
if (agent == null)
{
return response;
}
2025-10-10 20:19:30 +00:00
var agentService = _services.GetRequiredService<IAgentService>();
2025-10-01 20:52:43 +00:00
var state = _services.GetRequiredService<IConversationStateService>();
var hooks = _services.GetHooks<IInstructHook>(agent.Id);
2025-10-01 20:52:43 +00:00
2025-10-08 20:12:00 +00:00
var codeProvider = codeOptions?.CodeInterpretProvider ?? "botsharp-py-interpreter";
2025-10-01 20:52:43 +00:00
var codeInterpreter = _services.GetServices<ICodeInterpretService>()
.FirstOrDefault(x => x.Provider.IsEqualTo(codeProvider));
if (codeInterpreter == null)
{
2025-10-02 00:58:28 +00:00
#if DEBUG
_logger.LogWarning($"No code interpreter found. (Agent: {agent.Id}, Code interpreter: {codeProvider})");
2025-10-02 00:58:28 +00:00
#endif
return response;
2025-10-01 20:52:43 +00:00
}
// 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))
{
2025-10-02 00:58:28 +00:00
#if DEBUG
_logger.LogWarning($"Empty code script name. (Agent: {agent.Id}, {scriptName})");
2025-10-02 00:58:28 +00:00
#endif
return response;
2025-10-01 20:52:43 +00:00
}
// Get code script
2025-10-10 20:19:30 +00:00
var codeScript = await agentService.GetAgentCodeScript(agent.Id, scriptName, scriptType: AgentCodeScriptType.Src);
2025-10-01 20:52:43 +00:00
if (string.IsNullOrWhiteSpace(codeScript))
{
2025-10-02 00:58:28 +00:00
#if DEBUG
_logger.LogWarning($"Empty code script. (Agent: {agent.Id}, {scriptName})");
2025-10-02 00:58:28 +00:00
#endif
return response;
2025-10-01 20:52:43 +00:00
}
// Get code arguments
var arguments = codeOptions?.Arguments ?? [];
if (arguments.IsNullOrEmpty())
{
arguments = state.GetStates().Select(x => new KeyValue(x.Key, x.Value)).ToList();
}
var context = new CodeInstructContext
{
2025-10-06 15:57:18 +00:00
CodeScript = codeScript,
Arguments = arguments
};
// Before code execution
foreach (var hook in hooks)
{
await hook.BeforeCodeExecution(agent, message, context);
// Interrupted by hook
if (message.StopCompletion)
{
return new InstructResult
{
MessageId = message.MessageId,
Text = message.Content
};
}
}
2025-10-01 20:52:43 +00:00
// Run code script
2025-10-06 15:57:18 +00:00
var result = await codeInterpreter.RunCode(context.CodeScript, options: new()
2025-10-01 20:52:43 +00:00
{
2025-10-08 20:12:00 +00:00
ScriptName = scriptName,
Arguments = context.Arguments
2025-10-01 20:52:43 +00:00
});
response = new InstructResult
{
MessageId = message.MessageId,
2025-10-06 15:50:20 +00:00
Template = scriptName,
Text = result?.Result?.ToString()
};
2025-10-14 15:13:12 +00:00
if (context?.Arguments != null)
{
context.Arguments.ForEach(x => state.SetState(x.Key, x.Value, source: StateSource.External));
}
// After code execution
foreach (var hook in hooks)
{
await hook.AfterCodeExecution(agent, response);
await hook.OnResponseGenerated(new InstructResponseModel
{
AgentId = agent.Id,
Provider = codeInterpreter.Provider,
Model = string.Empty,
TemplateName = scriptName,
2025-10-13 19:41:06 +00:00
UserMessage = message.Content,
2025-10-14 15:13:12 +00:00
SystemInstruction = context?.CodeScript,
CompletionText = response.Text
});
}
return response;
2025-10-01 20:52:43 +00:00
}
2025-10-14 18:52:01 +00:00
private async Task<string> GetTextCompletion(
ITextCompletion textCompleter,
Agent agent,
string text,
string messageId)
{
var result = await textCompleter.GetCompletion(text, agent.Id, messageId);
return result;
}
private async Task<string> GetChatCompletion(
IChatCompletion chatCompleter,
Agent agent,
string instruction,
string text,
string messageId,
IEnumerable<InstructFileModel>? files = null)
{
var result = await chatCompleter.GetChatCompletions(new Agent
{
Id = agent.Id,
Name = agent.Name,
Instruction = instruction
}, new List<RoleDialogModel>
{
new RoleDialogModel(AgentRole.User, text)
{
CurrentAgentId = agent.Id,
MessageId = messageId,
Files = files?.Select(x => new BotSharpFile { FileUrl = x.FileUrl, FileData = x.FileData, ContentType = x.ContentType }).ToList() ?? []
}
});
return result.Content;
}
2024-10-17 23:17:38 +00:00
}