An AI-Powered Python Code Generator Built with Rust
๐ Docker sandboxing, virtual-env isolation, multi-provider LLM support, real-time web dashboard, ruff linting, and bandit security scanning โ all built in!
A Rust-based interactive shell that leverages AI language models to generate, refine, and execute Python code on demand. This agentic tool helps you quickly prototype Python scripts with conversational AI assistance.
- AI-Powered Code Generation: Uses HuggingFace's Qwen2.5-Coder-32B-Instruct model for high-quality Python code (configurable)
- Multi-Provider Support: Route generation to HuggingFace (cloud), Ollama (local), or any OpenAI-compatible API
- Interactive REPL: Easy-to-use command-line interface with helpful commands
- Automatic Code Execution: Run generated Python scripts directly from the shell
- Smart Code Extraction: Handles markdown-formatted responses and extracts clean Python code
- Multi-Turn Refinement: Maintain conversation history to iteratively improve code
- Web Dashboard ๐: Real-time web interface with script history, code generation, session stats, Docker container monitoring, and WebSocket execution logs
- Interactive Mode ๐ฎ: Automatically detects and runs interactive programs (pygame games, user input, GUIs)
- Docker Sandbox ๐ณ: Optionally execute AI-generated code inside an isolated Docker container for security
- Virtual Environment Isolation ๐: Each script runs in a temporary venv to avoid polluting the system Python (host & Docker)
- Syntax Check & Auto-Refine: Validates code with
py_compilebefore execution; offers to auto-fix syntax errors via AI - Static Analysis (Linting) ๐: Runs
ruffon generated code to catch quality issues before execution; offers auto-refine on lint errors - Security Scanning ๐ก๏ธ: Runs
banditas a pre-flight security check to detect unsafe patterns (e.g.exec(),shell=True) before execution - API Retry with Backoff: Automatic retries with exponential backoff on network errors, rate limits, and server errors
- Execution Timeout: Configurable timeout kills runaway scripts (Captured mode only)
- Conversation History Limit: Automatically trims old messages to keep context manageable
- Streaming Responses โก: Real-time token-by-token code generation in REPL and dashboard via SSE
- Code Explanation ๐:
/explaincommand and dashboard button for step-by-step code breakdowns - Multi-File Projects ๐:
/projectcommand generates entire project structures with multiple files - Session Persistence ๐พ: Save and load conversation sessions across restarts
- CI/CD Pipeline โ : GitHub Actions with automated formatting, linting, and testing
- Script Management: List and re-run previously generated scripts anytime
- Dependency Detection: Automatically detects non-standard library imports
- Auto-Installation: Prompts to install required packages via pip (or auto-installs with config)
- Session Logging: All API calls and executions logged to timestamped files
- Success Metrics: Track and display success rates and session statistics
- Colored Output: Syntax-highlighted code display with colorized terminal output
- Web Dashboard: Browser-based UI for code generation and monitoring (
/dashboardcommand) - File Management: Save generated code to files with
/savecommand - History Tracking: View conversation history with
/history - Session Stats: Monitor performance with
/stats
- Rust (1.80+): Install Rust โ requires
LazyLocksupport - Python 3: For executing generated scripts
- HuggingFace Token (cloud mode): Required for the default HuggingFace provider (free tier available)
- Ollama (local mode, optional): For local/offline LLM inference โ Install Ollama
- Docker (optional): For sandboxed script execution โ Install Docker
- ruff (optional): For static analysis / linting of generated code โ
pip install ruff - bandit (optional): For pre-flight security scanning of generated code โ
pip install bandit
- Clone the repository:
git clone https://github.com/Alvaro5/python-maker-bot.git
cd python-maker-bot- Set up HuggingFace Token:
Create a
.envfile in the repository root:
echo "HF_TOKEN=your_huggingface_token_here" > .envGet your token from HuggingFace Settings
- Build and run:
cargo build --release
cargo run- (Optional) Build the Docker sandbox image:
docker build -t python-sandbox .Then enable it in pymakebot.toml:
use_docker = true| Command | Description |
|---|---|
/help |
Show all available commands |
/quit or /exit |
Exit the program |
/clear |
Clear conversation history |
/refine |
Refine the last generated code |
/save <filename> |
Save last code to a file |
/history |
Show conversation history |
/stats |
Display session statistics |
/list |
List all previously generated scripts |
/run <filename> |
Execute a previously generated script |
/provider |
Show current LLM provider info |
/lint |
Lint the last generated code with ruff |
/security |
Run security scan (bandit) on last code |
/dashboard |
Show dashboard URL (if enabled) |
/explain |
Explain the last generated code step-by-step |
/project <prompt> |
Generate a multi-file project structure |
/session save <name> |
Save current session to disk |
/session load <name> |
Load a saved session |
/session list |
List all saved sessions |
> Create a script that prints fibonacci numbers up to 100
----------- Generated Code -----------
# Fibonacci numbers up to 100
def fibonacci(limit):
a, b = 0, 1
while a < limit:
print(a, end=' ')
a, b = b, a + b
print()
fibonacci(100)
-----------------------------------
Execute this script? (y/n) : y
--- Execution Result ---
STDOUT:
0 1 1 2 3 5 8 13 21 34 55 89
> Create a simple calculator
[Code generated...]
> /refine
What would you like to change or add? Add division by zero handling
[Improved code generated...]
> Create a pygame game with a bouncing ball
โ ๏ธ Detected non-standard dependencies: pygame
Install these dependencies? (y/n) : y
โ Dependencies installed successfully
----------- Generated Code -----------
import pygame
# ... game code ...
-----------------------------------
Execute this script? (y/n) : y
๐ฎ Interactive mode detected (pygame/input/GUI)
Running with inherited stdio for user interaction...
[Pygame window opens with bouncing ball animation]
See INTERACTIVE_MODE.md for detailed documentation on running games, programs with user input, and GUI applications.
.
โโโ src/
โ โโโ main.rs # Entry point; loads .env and config
โ โโโ config.rs # AppConfig with TOML deserialization
โ โโโ lib.rs # Library entrypoint and re-exports
โ โโโ api.rs # Multi-provider LLM client (HuggingFace, Ollama, OpenAI-compatible)
โ โโโ interface.rs # Interactive REPL with syntax check, lint, and auto-refine
โ โโโ python_exec.rs # Python execution engine with timeout, lint, venv & Docker sandbox
โ โโโ utils.rs # Code extraction, import parsing, UTF-8 utils
โ โโโ logger.rs # Logging and metrics
โ โโโ dashboard/ # Web dashboard module
โ โโโ mod.rs # Module re-exports
โ โโโ server.rs # Axum HTTP server setup
โ โโโ routes.rs # REST API and page route handlers
โ โโโ state.rs # Shared dashboard state and event types
โ โโโ templates.rs # Askama template render helpers
โ โโโ websocket.rs # WebSocket handler for real-time logs
โโโ templates/ # Askama HTML templates (dashboard UI)
โ โโโ index.html # Main dashboard page
โ โโโ partials/ # HTMX partial templates (history, stats, code, containers)
โโโ generated/ # Generated Python scripts
โโโ logs/ # Session logs
โโโ Cargo.toml # Rust dependencies
โโโ Dockerfile # Docker sandbox image definition
โโโ pymakebot.toml # Optional configuration file
- Language: Rust 2021 Edition
- AI Model: Qwen/Qwen2.5-Coder-32B-Instruct via HuggingFace, Ollama, or any OpenAI-compatible endpoint โ configurable
- Key Dependencies:
reqwest: HTTP client for API callstokio: Async runtimeserde/serde_json: JSON serializationtoml/dirs: Configuration file supportwait-timeout: Execution timeoutcolored: Terminal color outputregex: Code extraction (cached withLazyLock)chrono: Timestampsrand: Retry jitteraxum: Web framework for the dashboard (with WebSocket support)askama: Compile-time HTML templateshtmx: Lightweight frontend interactivity (loaded via CDN)
HF_TOKEN: Your HuggingFace API token (required whenprovider = "huggingface", via.envfile)LLM_API_KEY: Optional API key for Ollama proxies or OpenAI-compatible providers (via.envfile)
Create an optional pymakebot.toml in the project directory or your home directory. All fields are optional โ missing fields use defaults:
# LLM Provider: "huggingface" (default), "ollama", or "openai-compatible"
provider = "huggingface"
# AI model settings
model = "Qwen/Qwen2.5-Coder-32B-Instruct"
api_url = "https://router.huggingface.co/v1/chat/completions"
max_tokens = 16384
temperature = 0.2
# Execution settings
execution_timeout_secs = 30 # Kill scripts after this many seconds (0 = no timeout)
auto_install_deps = false # Auto-install detected dependencies without prompting
use_docker = false # Run scripts inside Docker sandbox (requires: docker build -t python-sandbox .)
use_venv = true # Isolate each execution in a temporary Python virtual environment
use_linting = true # Run ruff lint check on generated code before execution\nuse_security_check = true # Run bandit security scan on generated code before execution
# API resilience
max_retries = 3 # Retry on network errors, 429, and 5xx responses
# History management
max_history_messages = 20 # Trim oldest messages when history exceeds this
# Web dashboard
enable_dashboard = false # Start the web dashboard alongside the REPL
dashboard_port = 3000 # Port for the dashboard HTTP server (localhost only)
# File locations
log_dir = "logs"
generated_dir = "generated"Load order: ./pymakebot.toml โ ~/pymakebot.toml โ built-in defaults
provider = "ollama"
model = "qwen2.5-coder:14b"No .env file or API key needed โ just have Ollama running locally. The API URL defaults to http://localhost:11434/v1/chat/completions.
provider = "openai-compatible"
api_url = "https://api.example.com/v1/chat/completions"
model = "gpt-4o-mini"Set LLM_API_KEY in .env if the endpoint requires authentication.
All sessions are logged to logs/session_TIMESTAMP.log with:
- API requests and responses
- Execution results
- Errors and warnings
- Total API requests
- Successful vs failed executions
- API errors
- Success rate percentage
View anytime with /stats
Best Practices:
- Enable Docker sandbox (
use_docker = true) to isolate generated code from your host - Review generated code before execution
- Don't commit your
.envfile - Monitor API usage to avoid unexpected costs
- Be cautious with file system operations in generated code
Safety Features:
- Docker sandbox: Runs scripts in an isolated container with no network access and read-only script mount
- Virtual environment isolation: Temp venv per execution prevents dependency pollution (host & Docker)
- Static analysis:
rufflint check catches code quality issues and unused imports before execution - Security scanning:
banditpre-flight scan detects unsafe patterns (exec(),shell=True, hardcoded passwords, etc.) and blocks HIGH-severity findings - Syntax check via
py_compilebefore execution catches errors early - Execution timeout prevents runaway scripts
- Dependency detection warns about non-standard imports before install
- Graceful fallback to host execution if Docker is unavailable
Limitations:
- HuggingFace free tier has rate limits; consider Pro for heavy usage (or switch to Ollama for unlimited local inference)
- Generated code quality depends on prompt clarity and model capability
Contributions are welcome! Areas for improvement:
- Implement virtual environment isolation per script
- Support for additional AI models (Ollama, OpenAI-compatible, etc.)
- Static analysis / linting with ruff
- Pre-flight security scanning with bandit
- Web dashboard with real-time monitoring
- Support for other programming languages
You can use this project as a library from other Rust projects. The crate exposes a run() entrypoint and re-exports AppConfig and CodeExecutor for convenience.
Example (simple main.rs using the library entrypoint):
use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
// Start the REPL from the library
python_maker_bot::run().await
}Example (programmatic usage of CodeExecutor):
use python_maker_bot::{AppConfig, CodeExecutor, ExecutionMode};
fn main() -> anyhow::Result<()> {
let cfg = AppConfig::load();
let executor = CodeExecutor::new(&cfg.generated_dir, cfg.use_docker, cfg.use_venv, &cfg.python_executable)?;
// Write and run a script (synchronous API available in the lib)
let result = executor.write_and_run_with_mode("print(\"hi\")", ExecutionMode::Captured)?;
println!("stdout: {}", result.stdout);
Ok(())
}MIT License - see LICENSE file for details
- HuggingFace for providing the inference API
- Qwen Team for the excellent code generation model
- Rust community for amazing libraries
- GitHub: Alvaro5
- Project: python-maker-bot
- โก Streaming LLM Responses: Real-time token-by-token code generation in both REPL and web dashboard
- REPL: characters appear as the model generates them (typing effect)
- Dashboard: Server-Sent Events (SSE) endpoint for live streaming
- Configurable via
use_streaming = trueinpymakebot.toml - Graceful fallback to non-streaming on error
- ๐ Code Explanation Mode:
/explainREPL command and dashboard "Explain" button- Sends generated code to the LLM with a dedicated explanation system prompt
- Returns structured breakdown: overview, step-by-step walkthrough, key concepts, improvements
- ๐ Multi-File Project Generation:
/project <prompt>command scaffolds complete project structures- LLM outputs structured JSON with file paths and contents
- Writes to
generated/<project_name>/with proper directory hierarchy - Security: validates paths (no
.., no absolute paths)
- ๐พ Conversation Persistence: Save and load sessions across restarts
/session save <name>โ serialize conversation history, code, and metadata to JSON/session load <name>โ restore a previous session/session listโ browse saved sessions with timestamps
- โ
CI/CD Pipeline: GitHub Actions workflow with
cargo fmt,cargo clippy, andcargo test
- ๐ Web Dashboard: Real-time browser-based dashboard running alongside the CLI REPL
- Code generation via the web UI (same LLM & config as the REPL)
- Script history sidebar with click-to-view source
- Session stats panel (requests, success rate, API errors)
- Docker container monitoring panel
- WebSocket-powered live execution logs (stdout/stderr in real-time)
- Built with Axum, Askama templates, HTMX, and Tailwind CSS
- Enabled via
enable_dashboard = trueinpymakebot.toml - Access at
http://localhost:3000(port configurable, binds to localhost only) /dashboardREPL command to display the URL
- ๐ง Code Quality: Refactored REPL initialization to eliminate duplication, delta-based dashboard state sync, async I/O in dashboard routes
- ๐ณ Docker Sandbox: Execute AI-generated scripts inside an isolated Docker container (
use_docker = true)- Network-isolated execution (
--network none), read-only script mount - Dependency installation inside the container (via inline venv when
use_venv = true) - Supports both Captured and Interactive execution modes
- Graceful fallback to host execution when Docker is unavailable
- Network-isolated execution (
- ๐ Virtual Environment Isolation: Each script execution runs in a temporary Python venv (
use_venv = true, on by default)- Host mode: temp venv in OS temp dir, auto-cleaned after execution
- Docker mode: venv created inline inside the ephemeral container โ no image mutation
- Prevents dependency conflicts and system Python pollution
- ๐ Multi-Provider LLM Support: Route code generation to HuggingFace (cloud), Ollama (local), or any OpenAI-compatible API
- Configured via
providerfield inpymakebot.toml("huggingface","ollama","openai-compatible") - Auto URL resolution, per-provider auth,
/providerREPL command
- Configured via
- ๐ Static Analysis (Linting): Ruff-powered lint check (
use_linting = true, on by default)- Runs
ruff checkafter syntax check, displays colored diagnostics - Offers auto-refine on lint errors,
/lintREPL command for on-demand checks - Gracefully skipped if
ruffis not installed
- Runs
- ๏ฟฝ๏ธ Security Scanning: Bandit-powered pre-flight security analysis (
use_security_check = true, on by default)- Runs
bandit -f jsonafter lint check, parses findings with severity (LOW/MEDIUM/HIGH) - Blocks execution on HIGH-severity findings (with user override),
/securityREPL command - Gracefully skipped if
banditis not installed
- Runs
- ๏ฟฝ๐ง Configuration File:
pymakebot.tomlsupport with load chain (local โ home โ defaults) - ๐ API Retry: Exponential backoff with jitter on network errors, 429, and 5xx
- โฑ๏ธ Execution Timeout: Configurable timeout kills runaway scripts in Captured mode
- โ
Syntax Check: Pre-execution validation via
py_compilewith auto-refine on errors - ๐ History Limit: Automatic trimming of conversation history to configured max
- ๐ Bug Fixes: UTF-8 safe string slicing, correct success detection (
exit_code == 0), cached regex compilation - ๐งน Code Quality: Zero clippy warnings, 95 tests (88 unit + 7 integration)
- ๐ฎ Interactive Mode: Automatic detection for pygame, input(), tkinter, GUIs
- ๐ Script Management:
/listand/runcommands for previously generated scripts - ๐ฏ Enhanced AI Prompts: Better code generation with self-contained scripts (no external files)
- ๐ง Token Limit Increase: 4096 tokens for complete game implementations
- ๐งน Smart Code Extraction: Multiple fallback strategies for markdown cleanup
- ๐ Comprehensive Documentation: 7 new documentation files
- Multi-turn conversation support with history
- Dependency detection and auto-installation
- Colored terminal output with syntax highlighting
- Session logging and metrics tracking
- Enhanced command system (/save, /history, /stats, /refine)
- Basic code generation via HuggingFace API
- Simple Python script execution
- Core REPL interface
Made with โค๏ธ by Alvaro Serero, Ali Dabale, Chloรฉ Daunas and Ovia Chanemouganandam