Skip to content

Alvaro5/python-maker-bot

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

70 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿค– Python Maker Bot v0.4.0

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.


โœจ Features

๐ŸŽฏ Core Functionality

  • 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

๐Ÿ”„ Advanced Capabilities

  • 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_compile before execution; offers to auto-fix syntax errors via AI
  • Static Analysis (Linting) ๐Ÿ”: Runs ruff on generated code to catch quality issues before execution; offers auto-refine on lint errors
  • Security Scanning ๐Ÿ›ก๏ธ: Runs bandit as 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 ๐Ÿ“–: /explain command and dashboard button for step-by-step code breakdowns
  • Multi-File Projects ๐Ÿ“: /project command 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

๐ŸŽจ User Experience

  • Colored Output: Syntax-highlighted code display with colorized terminal output
  • Web Dashboard: Browser-based UI for code generation and monitoring (/dashboard command)
  • File Management: Save generated code to files with /save command
  • History Tracking: View conversation history with /history
  • Session Stats: Monitor performance with /stats

๐Ÿš€ Quick Start

Prerequisites

  • Rust (1.80+): Install Rust โ€” requires LazyLock support
  • 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

Installation

  1. Clone the repository:
git clone https://github.com/Alvaro5/python-maker-bot.git
cd python-maker-bot
  1. Set up HuggingFace Token: Create a .env file in the repository root:
echo "HF_TOKEN=your_huggingface_token_here" > .env

Get your token from HuggingFace Settings

  1. Build and run:
cargo build --release
cargo run
  1. (Optional) Build the Docker sandbox image:
docker build -t python-sandbox .

Then enable it in pymakebot.toml:

use_docker = true

๐Ÿ“– Usage Guide

Interactive Commands

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

Example Session

> 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

Multi-Turn Refinement

> Create a simple calculator
[Code generated...]

> /refine
What would you like to change or add? Add division by zero handling
[Improved code generated...]

Interactive Programs (NEW in v0.2!)

> 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.


๐Ÿ—๏ธ Architecture

Project Structure

.
โ”œโ”€โ”€ 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

Technology Stack

  • 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 calls
    • tokio: Async runtime
    • serde/serde_json: JSON serialization
    • toml/dirs: Configuration file support
    • wait-timeout: Execution timeout
    • colored: Terminal color output
    • regex: Code extraction (cached with LazyLock)
    • chrono: Timestamps
    • rand: Retry jitter
    • axum: Web framework for the dashboard (with WebSocket support)
    • askama: Compile-time HTML templates
    • htmx: Lightweight frontend interactivity (loaded via CDN)

๐Ÿ”ง Configuration

Environment Variables

  • HF_TOKEN: Your HuggingFace API token (required when provider = "huggingface", via .env file)
  • LLM_API_KEY: Optional API key for Ollama proxies or OpenAI-compatible providers (via .env file)

Configuration File (pymakebot.toml)

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

Example: Using Ollama (local)

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.

Example: OpenAI-compatible endpoint

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.


๐Ÿ“Š Logging and Metrics

Session Logs

All sessions are logged to logs/session_TIMESTAMP.log with:

  • API requests and responses
  • Execution results
  • Errors and warnings

Metrics Tracked

  • Total API requests
  • Successful vs failed executions
  • API errors
  • Success rate percentage

View anytime with /stats


๐Ÿ›ก๏ธ Security Considerations

โš ๏ธ Important: This tool executes AI-generated code automatically.

Best Practices:

  1. Enable Docker sandbox (use_docker = true) to isolate generated code from your host
  2. Review generated code before execution
  3. Don't commit your .env file
  4. Monitor API usage to avoid unexpected costs
  5. 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: ruff lint check catches code quality issues and unused imports before execution
  • Security scanning: bandit pre-flight scan detects unsafe patterns (exec(), shell=True, hardcoded passwords, etc.) and blocks HIGH-severity findings
  • Syntax check via py_compile before 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

๐Ÿค Contributing

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

๐Ÿ“ฆ Library Usage

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(())
}

๐Ÿ“ License

MIT License - see LICENSE file for details


๐Ÿ™ Acknowledgments

  • HuggingFace for providing the inference API
  • Qwen Team for the excellent code generation model
  • Rust community for amazing libraries

๐Ÿ“ž Contact


๐Ÿ”„ Version History

v0.4.0 (Current โ€” April 2026)

  • โšก 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 = true in pymakebot.toml
    • Graceful fallback to non-streaming on error
  • ๐Ÿ“– Code Explanation Mode: /explain REPL 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, and cargo test

v0.3.0 (February 2026)

  • ๐ŸŒ 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 = true in pymakebot.toml
    • Access at http://localhost:3000 (port configurable, binds to localhost only)
    • /dashboard REPL command to display the URL
  • ๐Ÿ”ง Code Quality: Refactored REPL initialization to eliminate duplication, delta-based dashboard state sync, async I/O in dashboard routes

v0.2.2 (February 2026)

  • ๐Ÿณ 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
  • ๐Ÿ 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 provider field in pymakebot.toml ("huggingface", "ollama", "openai-compatible")
    • Auto URL resolution, per-provider auth, /provider REPL command
  • ๐Ÿ” Static Analysis (Linting): Ruff-powered lint check (use_linting = true, on by default)
    • Runs ruff check after syntax check, displays colored diagnostics
    • Offers auto-refine on lint errors, /lint REPL command for on-demand checks
    • Gracefully skipped if ruff is not installed
  • ๏ฟฝ๏ธ Security Scanning: Bandit-powered pre-flight security analysis (use_security_check = true, on by default)
    • Runs bandit -f json after lint check, parses findings with severity (LOW/MEDIUM/HIGH)
    • Blocks execution on HIGH-severity findings (with user override), /security REPL command
    • Gracefully skipped if bandit is not installed
  • ๏ฟฝ๐Ÿ”ง Configuration File: pymakebot.toml support 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_compile with 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)

v0.2.1 (December 2025)

  • ๐ŸŽฎ Interactive Mode: Automatic detection for pygame, input(), tkinter, GUIs
  • ๐Ÿ“‚ Script Management: /list and /run commands 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

v0.2.0 (December 2025)

  • 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)

v0.1.0 (Initial)

  • 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

About

AI-powered Python code generator built in Rust: multi-provider LLMs, Docker sandbox, real-time web dashboard, ruff/bandit analysis, RAG, streaming

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Rust 84.8%
  • HTML 14.9%
  • Dockerfile 0.3%