An AI-Powered Python Code Generator Built with Rust
๐ฎ Now with Interactive Mode for games, GUIs, and programs requiring user input!
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)
- 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
- Interactive Mode ๐ฎ: Automatically detects and runs interactive programs (pygame games, user input, GUIs)
- Syntax Check & Auto-Refine: Validates code with
py_compilebefore execution; offers to auto-fix syntax errors via AI - 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
- 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
- File Management: Save generated code to files with
/savecommand - History Tracking: View conversation history with
/history - Session Stats: Monitor performance with
/stats
- Rust (1.70+): Install Rust
- Python 3: For executing generated scripts
- HuggingFace Token: Required for API access (free tier available)
- Clone the repository:
git clone https://github.com/Ali-Gatorre/Rust_project.git
cd Rust_project/project_code- Set up HuggingFace Token:
Create a
.envfile in theproject_codedirectory:
echo "HF_TOKEN=your_huggingface_token_here" > .envGet your token from HuggingFace Settings
- Build and run:
cargo build --release
cargo run| 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 |
> 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? (o/n) : o
--- 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? (o/n) : o
โ Dependencies installed successfully
----------- Generated Code -----------
import pygame
# ... game code ...
-----------------------------------
Execute this script? (o/n) : o
๐ฎ 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.
project_code/
โโโ src/
โ โโโ main.rs # Entry point; loads .env and config
โ โโโ config.rs # AppConfig with TOML deserialization
โ โโโ api.rs # HuggingFace API client with retry/backoff
โ โโโ interface.rs # Interactive REPL with syntax check and auto-refine
โ โโโ python_exec.rs # Python execution engine with timeout
โ โโโ utils.rs # Code extraction, import parsing, UTF-8 utils
โ โโโ logger.rs # Logging and metrics
โโโ generated/ # Generated Python scripts
โโโ logs/ # Session logs
โโโ Cargo.toml # Rust dependencies
โโโ pymakebot.toml # Optional configuration file
- Language: Rust 2021 Edition
- AI Model: Qwen/Qwen2.5-Coder-32B-Instruct (HuggingFace) โ 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 jitter
HF_TOKEN: Your HuggingFace API token (required, via.envfile)
Create an optional pymakebot.toml in the project directory or your home directory. All fields are optional โ missing fields use defaults:
# AI model settings
model = "Qwen/Qwen2.5-Coder-32B-Instruct"
api_url = "https://router.huggingface.co/v1/chat/completions"
max_tokens = 16284
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
# 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
# File locations
log_dir = "logs"
generated_dir = "generated"Load order: ./pymakebot.toml โ ~/pymakebot.toml โ built-in defaults
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:
- Review generated code before execution
- Use in a sandboxed environment
- Don't commit your
.envfile - Monitor API usage to avoid unexpected costs
- Be cautious with file system operations in generated code
Safety Features:
- Syntax check via
py_compilebefore execution catches errors early - Execution timeout prevents runaway scripts
- Dependency detection warns about non-standard imports before install
Limitations:
- Requires HuggingFace Pro for heavy usage (free tier has rate limits)
- Generated code quality depends on prompt clarity
Contributions are welcome! Areas for improvement:
- Implement virtual environment isolation per script
- Support for additional AI models (OpenAI, Anthropic, etc.)
- Web UI using Tauri or similar
- Support for other programming languages
Complete guides available:
- DEMO_EXAMPLES.md - Battle-tested examples perfect for demos and presentations
- DEFENSE_CHEATSHEET.md - Quick reference for project defense/presentations
- QUICK_REFERENCE.md - Command cheat sheet and feature overview
- INTERACTIVE_MODE.md - Technical deep dive into interactive execution
- EXAMPLES.md - Usage examples and patterns
- FIX_SUMMARY.md - Technical implementation details
- ARCHITECTURE_DIAGRAM.md - Visual system diagrams
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: Ali-Gatorre
- Project: Rust_project
- ๐ง 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, 66 tests (59 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