Skip to content

Conversation

iceljc
Copy link
Collaborator

@iceljc iceljc commented Oct 1, 2025

PR Type

Enhancement


Description

  • Refine Python interpreter with code generation capabilities

  • Add realtime model options and settings

  • Implement code interpretation service infrastructure

  • Add agent code script management system


Diagram Walkthrough

flowchart LR
  A["Python Interpreter"] --> B["Code Generation"]
  A --> C["Code Interpretation Service"]
  B --> D["LLM-based Code Gen"]
  C --> E["Script Execution"]
  F["Realtime Hub"] --> G["Model Options"]
  H["Agent Service"] --> I["Code Script Management"]
  I --> J["Database Operations"]
Loading

File Walkthrough

Relevant files
Cleanup
7 files
IAgentService.cs
Remove unused UpdateAgentFromFile method                                 
+0/-1     
AgentService.UpdateAgent.cs
Remove UpdateAgentFromFile method implementation                 
+1/-106 
BotSharpCoreExtensions.cs
Remove interpreter settings configuration                               
+0/-5     
AgentController.cs
Remove UpdateAgentFromFile endpoint                                           
+0/-6     
InterpretationFn.cs
Remove old interpretation function                                             
+0/-46   
InterpreterPlugin.cs
Remove old interpreter plugin                                                       
+0/-40   
python_interpreter.fn.liquid
Remove old Python interpreter template                                     
+0/-1     
Enhancement
56 files
AgentCodeScript.cs
Add AgentCodeScript model for code management                       
+18/-0   
ICodeInterpretService.cs
Add code interpretation service interface                               
+11/-0   
CodeInterpretOptions.cs
Add code interpretation options model                                       
+6/-0     
CodeInterpretResult.cs
Add code interpretation result model                                         
+8/-0     
RoleDialogModel.cs
Add RoleContent property for unified content access           
+19/-0   
IInstructService.cs
Add code options parameter to Execute method                         
+8/-5     
CodeInstructOptions.cs
Add code instruction options model                                             
+8/-0     
IRealTimeCompletion.cs
Add SetOptions method for realtime configuration                 
+1/-0     
KeyValue.cs
Add constructor overloads to KeyValue model                           
+11/-0   
IRealtimeHub.cs
Add options parameter to ConnectToModel method                     
+2/-1     
RealtimeOptions.cs
Add RealtimeOptions model for audio formats                           
+12/-0   
IBotSharpRepository.cs
Add agent code script repository methods                                 
+14/-4   
RealtimeHub.cs
Implement options parameter in ConnectToModel                       
+6/-1     
AgentService.CreateAgent.cs
Add GetCodeScriptsFromFile method for agent creation         
+19/-0   
AgentService.RefreshAgents.cs
Include code scripts in agent refresh process                       
+5/-2     
InstructService.Execute.cs
Add code template execution support                                           
+56/-17 
FileRepository.AgentCode.cs
Implement agent code script repository operations               
+159/-0 
FileRepository.AgentTask.cs
Update agent task methods with improved parameters             
+16/-9   
FileRepository.cs
Add AGENT_CODES_FOLDER constant                                                   
+1/-0     
AgentTaskService.cs
Update DeleteTask method call signature                                   
+1/-1     
InstructModeController.cs
Add code options support to instruction completion             
+3/-3     
InstructMessageModel.cs
Add CodeOptions property to instruction model                       
+3/-0     
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+11/-11 
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+3/-3     
ChatStreamMiddleware.cs
Add realtime options support to chat streaming                     
+3/-4     
ChatStreamRequest.cs
Add Options property to chat stream request                           
+4/-0     
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+3/-3     
GeminiChatCompletionProvider.cs
Use RoleContent property for message content                         
+5/-5     
PalmChatCompletionProvider.cs
Use RoleContent property for message content                         
+3/-3     
RealTimeCompletionProvider.cs
Add SetOptions method and use RoleContent                               
+17/-11 
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+2/-2     
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+1/-1     
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+4/-4     
MicrosoftExtensionsAIChatCompletionProvider.cs
Use RoleContent property for message content                         
+3/-3     
AgentCodeDocument.cs
Add MongoDB document for agent code scripts                           
+32/-0   
MongoDbContext.cs
Add AgentCodes collection to MongoDB context                         
+3/-0     
MongoRepository.Agent.cs
Include agent codes in delete operations                                 
+5/-1     
MongoRepository.AgentCode.cs
Implement MongoDB agent code repository operations             
+113/-0 
MongoRepository.AgentTask.cs
Update agent task repository methods                                         
+19/-23 
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+3/-3     
RealTimeCompletionProvider.cs
Add SetOptions method and realtime configuration                 
+11/-36 
UtilityName.cs
Rename utility from interpreter to programmer                       
+1/-1     
PyProgrammerFn.cs
Add new Python programmer function with LLM integration   
+188/-0 
PyPackageHelper.cs
Add Python package management helper                                         
+178/-0 
PyProgrammerUtilityHook.cs
Rename and update utility hook                                                     
+6/-6     
LlmContextIn.cs
Add LLM context input model                                                           
+12/-0   
LlmContextOut.cs
Add LLM context output model                                                         
+12/-0   
PackageInstallResult.cs
Add package installation result model                                       
+7/-0     
PythonInterpreterPlugin.cs
Add new Python interpreter plugin with enhanced features 
+59/-0   
PyInterpretService.cs
Add Python interpretation service implementation                 
+91/-0   
PythonInterpreterSettings.cs
Add comprehensive Python interpreter settings                       
+18/-0   
Using.cs
Update global using statements                                                     
+17/-0   
ChatCompletionProvider.cs
Use RoleContent property for message content                         
+2/-2     
util-chart-plot_instruction.liquid
Update chart plotting instruction template                             
+5/-2     
util-code-python_generate_instruction.liquid
Add comprehensive Python code generation instruction         
+49/-0   
util-code-python_programmer.fn.liquid
Add Python programmer function template                                   
+1/-0     
Bug fix
1 files
FileRepository.Agent.cs
Add null checks in GetAgentTemplate method                             
+6/-0     
Dependencies
1 files
Directory.Packages.props
Update pythonnet package version                                                 
+1/-1     
Configuration changes
1 files
BotSharp.Plugin.PythonInterpreter.csproj
Update project references and content files                           
+8/-6     
Additional files
8 files
InstructResult.cs +2/-1     
InterpretationRequest.cs +0/-10   
InterpreterSettings.cs +0/-11   
ExecuteTemplateFn.cs +0/-2     
python_interpreter.json +0/-19   
util-code-python_programmer.json +14/-0   
WebStarter.csproj +1/-0     
appsettings.json +27/-5   

Copy link

qodo-merge-pro bot commented Oct 1, 2025

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 Security concerns

Code execution sandboxing:
The Python interpreter executes arbitrary LLM-generated code (PyProgrammerFn and PyInterpretService) with full process permissions and access to sys modules. There are no resource limits, filesystem/network restrictions, or timeouts. This could allow remote code execution impacting the host. Consider sandboxing (separate process/container, restricted working directory, timeout, memory/CPU limits), validating/whitelisting imports, and disabling dangerous modules. Also, pip install via PyPackageHelper can fetch arbitrary packages at runtime without verification, which may introduce supply-chain risks.

⚡ Recommended focus areas for review

Possible Issue

Missing consideration for installing/importing required Python packages returned by the model; ret.ImportedPackages is parsed but never used. Generated code that relies on external packages may fail at runtime without pre-install checks or sandboxing.

var response = await GetChatCompletion(innerAgent, dialogs);
var ret = response.JsonContent<LlmContextOut>();

try
{
    using (Py.GIL())
    {
        // Import necessary Python modules
        dynamic sys = Py.Import("sys");
        dynamic io = Py.Import("io");

        // Redirect standard output/error to capture it
        dynamic stringIO = io.StringIO();
        sys.stdout = stringIO;
        sys.stderr = stringIO;

        // Set global items
        using var globals = new PyDict();
        if (ret.PythonCode?.Contains("__main__") == true)
        {
            globals.SetItem("__name__", new PyString("__main__"));
        }

        // Execute Python script
        PythonEngine.Exec(ret.PythonCode, globals);

        // Get result
        var result = stringIO.getvalue()?.ToString() as string;
        message.Content = result?.TrimEnd('\r', '\n') ?? string.Empty;
        message.RichContent = new RichContent<IRichMessage>
        {
            Recipient = new Recipient { Id = convService.ConversationId },
            Message = new ProgramCodeTemplateMessage
            {
                Text = ret.PythonCode ?? string.Empty,
                Language = "python"
            }
        };
        message.StopCompletion = true;

        // Restore the original stdout/stderr
        sys.stdout = sys.__stdout__;
        sys.stderr = sys.__stderr__;
    }
}
catch (Exception ex)
{
    var errorMsg = $"Error when executing python code.";
    message.Content = $"{errorMsg} {ex.Message}";
    _logger.LogError(ex, errorMsg);
}
Logic Error

In GetAgentCodeScripts, the condition if (scriptNames != null || !scriptNames.Contains(fileName)) will skip all files whenever scriptNames is not null. Likely intended to be && to filter only when a non-null list is provided.

var results = new List<AgentCodeScript>();
foreach (var file in Directory.GetFiles(dir))
{
    var fileName = Path.GetFileName(file);
    if (scriptNames != null || !scriptNames.Contains(fileName))
    {
        continue;
    }

    var script = new AgentCodeScript
    {
        AgentId = agentId,
        Name = fileName,
        Content = File.ReadAllText(file)
    };
    results.Add(script);
}
return results;
Resource Cleanup

Python runtime is initialized and thread state stored, but shutdown relies on ApplicationStopping only. If initialization partially fails or multiple initializations occur across scopes, ensure idempotency and guard against double shutdown; also validate InstallLocation path to a DLL vs directory on non-Windows.

public void Configure(IApplicationBuilder app)
{
    var sp = app.ApplicationServices;
    var settings = sp.GetRequiredService<PythonInterpreterSettings>();
    var logger = sp.GetRequiredService<ILogger<PyProgrammerFn>>();
    var pyLoc = settings.InstallLocation;

    try
    {
        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}");
        }
    }
    catch (Exception ex)
    {
        logger.LogError(ex, $"Error when loading python dll {pyLoc}");
    }
}

Copy link

qodo-merge-pro bot commented Oct 1, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Implement robust sandboxing for code execution

The current direct execution of LLM-generated Python code is a major security
risk. To fix this, implement a sandboxed environment using tools like Docker to
isolate the code execution and restrict its access to system resources.

Examples:

src/Plugins/BotSharp.Plugin.PythonInterpreter/Services/PyInterpretService.cs [23-90]
src/Plugins/BotSharp.Plugin.PythonInterpreter/Functions/PyProgrammerFn.cs [67-117]

Solution Walkthrough:

Before:

// In PyInterpretService.cs and PyProgrammerFn.cs
public class PyInterpretService
{
    public async Task<CodeInterpretResult> RunCode(string codeScript, ...)
    {
        try
        {
            using (Py.GIL())
            {
                // ... setup environment
                
                // Direct execution of arbitrary code in the same process
                PythonEngine.Exec(codeScript, globals);

                // ... capture and return result
            }
        }
        catch (Exception ex) { /* ... */ }
    }
}

After:

// A new sandboxed execution service
public class SandboxedPythonExecutor
{
    public async Task<ExecutionResult> Execute(string code)
    {
        // 1. Spin up an isolated environment (e.g., Docker container).
        // 2. Set strict resource limits (no network, read-only filesystem).
        // 3. Execute the code inside the isolated environment.
        // 4. Capture stdout/stderr.
        // 5. Tear down the environment.
        // 6. Return the result.
        var result = await RunInContainerAsync(code);
        return result;
    }
}

// In PyInterpretService.cs
public async Task<CodeInterpretResult> RunCode(string codeScript, ...)
{
    var sandboxedExecutor = _services.GetRequiredService<SandboxedPythonExecutor>();
    var result = await sandboxedExecutor.Execute(codeScript);
    // ... return result
}
Suggestion importance[1-10]: 10

__

Why: This suggestion addresses a critical security vulnerability by pointing out that executing LLM-generated code directly is unsafe and proposes a robust, standard solution.

High
Possible issue
Ensure agent-specific data deletion

Fix a critical bug in DeleteAgentCodeScripts by adding a filter for agentId to
prevent deleting code scripts from unintended agents.

src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentCode.cs [91-111]

     public bool DeleteAgentCodeScripts(string agentId, List<string>? scriptNames)
     {
         if (string.IsNullOrWhiteSpace(agentId))
         {
             return false;
         }
 
-        var filterDef = Builders<AgentCodeDocument>.Filter.Empty;
+        var builder = Builders<AgentCodeDocument>.Filter;
+        var filterDef = builder.Eq(x => x.AgentId, agentId);
+
         if (scriptNames != null)
         {
-            var builder = Builders<AgentCodeDocument>.Filter;
-            var filters = new List<FilterDefinition<AgentCodeDocument>>
-            {
-                builder.In(x => x.Name, scriptNames)
-            };
-            filterDef = builder.And(filters);
+            var scriptFilter = builder.In(x => x.Name, scriptNames);
+            filterDef = builder.And(filterDef, scriptFilter);
         }
 
         var deleted = _dc.AgentCodes.DeleteMany(filterDef);
         return deleted.DeletedCount > 0;
     }
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: This suggestion points out a critical data-loss bug where agentId is ignored during deletion, potentially deleting scripts from all agents. The fix is crucial for data integrity.

High
Fix incorrect filtering logic

Fix the incorrect filtering logic in GetAgentCodeScripts by changing the ||
operator to && to correctly filter files when scriptNames is provided.

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentCode.cs [24-28]

     var fileName = Path.GetFileName(file);
-    if (scriptNames != null || !scriptNames.Contains(fileName))
+    if (scriptNames != null && !scriptNames.Contains(fileName))
     {
         continue;
     }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug where the filtering logic is flawed, causing the method to either return an empty list or throw a NullReferenceException.

High
Ensure Python streams are always restored

Move the restoration logic for Python's sys.stdout and sys.stderr into a finally
block to ensure they are always restored, even if an exception occurs.

src/Plugins/BotSharp.Plugin.PythonInterpreter/Functions/PyProgrammerFn.cs [91-107]

     var result = stringIO.getvalue()?.ToString() as string;
     message.Content = result?.TrimEnd('\r', '\n') ?? string.Empty;
     message.RichContent = new RichContent<IRichMessage>
     {
         Recipient = new Recipient { Id = convService.ConversationId },
         Message = new ProgramCodeTemplateMessage
         {
             Text = ret.PythonCode ?? string.Empty,
             Language = "python"
         }
     };
     message.StopCompletion = true;
+  }
+  finally
+  {
+      using (Py.GIL())
+      {
+          // Restore the original stdout/stderr
+          dynamic sys = Py.Import("sys");
+          sys.stdout = sys.__stdout__;
+          sys.stderr = sys.__stderr__;
+      }
+  }
 
-    // Restore the original stdout/stderr
-    sys.stdout = sys.__stdout__;
-    sys.stderr = sys.__stderr__;
-

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential issue where Python's standard streams are not restored on error and provides a robust fix using a finally block, improving application stability.

Medium
Learned
best practice
Remove throwing default implementation

Remove the throwing default implementation and require implementers to provide a
concrete method, or provide a safe base class if needed.

src/Infrastructure/BotSharp.Abstraction/CodeInterpreter/ICodeInterpretService.cs [7-11]

 public interface ICodeInterpretService
 {
     string Provider { get; }
-
-    Task<CodeInterpretResult> RunCode(string codeScript, CodeInterpretOptions? options = null)
-        => throw new NotImplementedException();
+    Task<CodeInterpretResult> RunCode(string codeScript, CodeInterpretOptions? options = null);
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Validate asynchronous usage; avoid default interface implementations that throw NotImplementedException at runtime.

Low
  • More

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant