BotSharp/src/Plugins/BotSharp.Plugin.PythonInterpreter/PythonInterpreterPlugin.cs

59 lines
2 KiB
C#
Raw Normal View History

2024-08-23 15:16:37 +00:00
using Microsoft.AspNetCore.Builder;
2025-09-29 20:07:54 +00:00
using Microsoft.Extensions.Hosting;
2025-09-29 20:34:52 +00:00
using Microsoft.Extensions.Logging;
2024-08-23 15:16:37 +00:00
using Python.Runtime;
using System.IO;
2024-08-12 19:22:47 +00:00
namespace BotSharp.Plugin.PythonInterpreter;
2025-09-29 06:35:08 +00:00
public class PythonInterpreterPlugin : IBotSharpAppPlugin
2024-08-12 19:22:47 +00:00
{
public string Id => "23174e08-e866-4173-824a-cf1d97afa8d0";
public string Name => "Python Interpreter";
public string Description => "Python Interpreter enables AI to write and execute Python code within a secure, sandboxed environment.";
public string? IconUrl => "https://static.vecteezy.com/system/resources/previews/012/697/295/non_2x/3d-python-programming-language-logo-free-png.png";
2025-09-29 20:07:54 +00:00
private nint _pyState;
2024-08-12 19:22:47 +00:00
public void RegisterDI(IServiceCollection services, IConfiguration config)
{
2025-09-29 20:07:54 +00:00
var settings = new PythonInterpreterSettings();
config.Bind("PythonInterpreter", settings);
services.AddSingleton(x => settings);
2025-09-29 06:20:25 +00:00
2025-09-29 20:07:54 +00:00
services.AddScoped<IAgentUtilityHook, PyProgrammerUtilityHook>();
2024-08-12 19:22:47 +00:00
}
2024-08-23 15:16:37 +00:00
public void Configure(IApplicationBuilder app)
{
2025-09-29 20:34:52 +00:00
var sp = app.ApplicationServices;
var settings = sp.GetRequiredService<PythonInterpreterSettings>();
var logger = sp.GetRequiredService<ILogger<PyProgrammerFn>>();
var pyLoc = settings.InstallLocation;
2024-08-23 15:16:37 +00:00
2025-09-29 20:34:52 +00:00
try
2024-08-23 15:16:37 +00:00
{
2025-09-29 20:34:52 +00:00
if (File.Exists(pyLoc))
{
Runtime.PythonDLL = pyLoc;
PythonEngine.Initialize();
_pyState = PythonEngine.BeginAllowThreads();
var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() => {
PythonEngine.EndAllowThreads(_pyState);
PythonEngine.Shutdown();
});
}
else
{
logger.LogError($"Python dll not found at {pyLoc}");
}
2024-08-23 15:16:37 +00:00
}
2025-09-29 20:34:52 +00:00
catch (Exception ex)
2024-08-23 15:16:37 +00:00
{
2025-09-29 20:34:52 +00:00
logger.LogError(ex, $"Error when loading python dll {pyLoc}");
2024-08-23 15:16:37 +00:00
}
}
2024-08-12 19:22:47 +00:00
}