2024-08-12 19:22:47 +00:00
|
|
|
using BotSharp.Abstraction.Conversations.Models;
|
|
|
|
|
using BotSharp.Abstraction.Functions;
|
|
|
|
|
using BotSharp.Abstraction.Interpreters.Models;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using Python.Runtime;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Plugin.PythonInterpreter.Functions;
|
|
|
|
|
|
2025-09-27 00:21:08 +00:00
|
|
|
public class PyInterpretationFn : IFunctionCallback
|
2024-08-12 19:22:47 +00:00
|
|
|
{
|
2025-09-27 00:21:08 +00:00
|
|
|
public string Name => "util-code-python_interpreter";
|
|
|
|
|
public string Indication => "Executing python code";
|
2024-08-12 19:22:47 +00:00
|
|
|
|
|
|
|
|
private readonly IServiceProvider _services;
|
2025-09-27 00:21:08 +00:00
|
|
|
private readonly ILogger<PyInterpretationFn> _logger;
|
|
|
|
|
|
|
|
|
|
public PyInterpretationFn(
|
|
|
|
|
IServiceProvider services,
|
|
|
|
|
ILogger<PyInterpretationFn> logger)
|
|
|
|
|
{
|
|
|
|
|
_services = services;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
}
|
2024-08-12 19:22:47 +00:00
|
|
|
|
|
|
|
|
public async Task<bool> Execute(RoleDialogModel message)
|
|
|
|
|
{
|
|
|
|
|
var args = JsonSerializer.Deserialize<InterpretationRequest>(message.FunctionArgs);
|
|
|
|
|
|
|
|
|
|
using (Py.GIL())
|
|
|
|
|
{
|
|
|
|
|
// Import necessary Python modules
|
|
|
|
|
dynamic sys = Py.Import("sys");
|
|
|
|
|
dynamic io = Py.Import("io");
|
|
|
|
|
|
|
|
|
|
// Redirect standard output to capture it
|
|
|
|
|
dynamic stringIO = io.StringIO();
|
|
|
|
|
sys.stdout = stringIO;
|
|
|
|
|
|
|
|
|
|
// Execute a simple Python script
|
|
|
|
|
using var locals = new PyDict();
|
|
|
|
|
PythonEngine.Exec(args.Script, null, locals);
|
|
|
|
|
|
|
|
|
|
// Console.WriteLine($"Result from Python: {result}");
|
|
|
|
|
message.Content = stringIO.getvalue();
|
|
|
|
|
|
|
|
|
|
// Restore the original stdout
|
|
|
|
|
sys.stdout = sys.__stdout__;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|