Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Optional: add your free HuggingFace token for higher rate limits
# Get one at https://huggingface.co/settings/tokens
HF_TOKEN=hf_your_token_here
191 changes: 109 additions & 82 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,121 +1,148 @@
# Codex-Clone: Open-Source AI Code Generator
# Free AI Code Generator

A free, open-source command-line tool that generates code from natural language prompts using CodeLlama or StarCoder models.
Generate code from plain English — **completely free**, no credit card required.

## Features
Powered by open-source models via three backends:

- 🚀 **Free & Open-Source** - No API keys required
- 💻 **Local Execution** - Run completely offline
- 🎯 **Multiple Languages** - Python, JavaScript, Go, Rust, C++, etc.
- ⚡ **GPU Acceleration** - Faster generation with CUDA
- 💾 **Save to File** - Direct output to code files
| Backend | Cost | Setup |
|---------|------|-------|
| HuggingFace Inference API | Free (rate-limited) | Just install & run |
| Ollama | Free (local) | Install Ollama, pull a model |
| Local model | Free (download once) | Download 3-15 GB of weights |

## Requirements
## Quick Start

- Python 3.8+
- PyTorch
- Transformers library
- CUDA-capable GPU (optional, but recommended)
```bash
git clone https://github.com/yourusername/free-claude-code.git
cd free-claude-code
pip install -r requirements.txt

# Generate code immediately — no signup, no API key
python codex_cli.py generate -p "Write a function to check if a string is a palindrome"
```

## Installation

```bash
# Clone the repository
git clone https://github.com/yourusername/codex-clone.git
cd codex-clone

# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Accept HuggingFace terms for CodeLlama
huggingface-cli login
# For web UI
pip install gradio

# For local model inference
pip install torch transformers accelerate
```

## Quick Start
## Usage

### Generate Python code
```bash
python codex_cli.py --prompt "Write a function to calculate fibonacci numbers" --language python
```
### Command-line

### Generate JavaScript code
```bash
python codex_cli.py -p "Create a function to validate email addresses" -l javascript
```
# Generate code (uses HuggingFace API by default — free)
python codex_cli.py generate -p "sort a list of dicts by a key" -l python

### Save to file
```bash
python codex_cli.py -p "Write a REST API endpoint" -l python -o api.py
# Interactive chat mode — refine code across multiple turns
python codex_cli.py chat

# Save output to a file
python codex_cli.py generate -p "REST API with Flask" -l python -o server.py

# Use a different model
python codex_cli.py generate -p "binary search" -m deepseek

# Use local Ollama (must have ollama running: ollama serve)
python codex_cli.py generate -p "fibonacci" -b ollama -m codellama

# List all available models
python codex_cli.py models
```

## Usage
### Options

```
Usage: codex_cli.py [OPTIONS]

Options:
-p, --prompt TEXT Natural language description (required)
-l, --language TEXT Programming language [default: python]
--length INTEGER Max tokens to generate [default: 256]
--temperature FLOAT Creativity (0.0-1.0) [default: 0.7]
-o, --output PATH Save to file
--help Show help
generate:
-p, --prompt TEXT What code to generate (required)
-l, --language TEXT Programming language [default: python]
-b, --backend TEXT hf | ollama | local [default: hf]
-m, --model TEXT Model key (see: codex-cli models)
--length INTEGER Max tokens [default: 512]
--temperature FLOAT Creativity 0.0-1.0 [default: 0.7]
-o, --output PATH Save to file
--token TEXT HuggingFace API token (or set HF_TOKEN env var)

chat:
-l, --language TEXT Starting language [default: python]
-b, --backend TEXT hf | ollama | local [default: hf]
-m, --model TEXT Model key

Chat commands:
exit Quit
clear Reset conversation history
lang <name> Switch language
```

## Models
### Web UI

The tool supports multiple open-source models:

1. **CodeLlama** (Recommended)
- Better code quality
- Meta/Facebook trained
- Requires HuggingFace login
```bash
pip install gradio
python app.py
# Opens at http://localhost:7860
```

2. **StarCoder**
- No login required
- Good performance
- Faster inference on CPU
## Available Models

Switch models by editing `MODEL_NAME` in `codex_cli.py`:
| Key | Model | Size |
|-----|-------|------|
| starcoder2 | bigcode/starcoder2-3b | 3B |
| deepseek | deepseek-ai/deepseek-coder-1.3b-instruct | 1.3B |
| codellama | codellama/CodeLlama-7b-Instruct-hf | 7B |
| phi2 | microsoft/phi-2 | 2.7B |
| mistral | mistralai/Mistral-7B-Instruct-v0.2 | 7B |
| tinyllama | TinyLlama/TinyLlama-1.1B-Chat-v1.0 | 1.1B |

```python
MODEL_NAME = "bigcode/starcoder" # Use StarCoder instead
```
## Optional: HuggingFace Token

## Performance Tips
The free tier works without a token, but rate-limits after a few requests.
For higher limits (still free), get a token at https://huggingface.co/settings/tokens

- Use GPU: `CUDA_VISIBLE_DEVICES=0 python codex_cli.py ...`
- Lower temperature for consistent code: `--temperature 0.3`
- Increase length for complex code: `--length 512`
```bash
cp .env.example .env
# Edit .env and add your token
```

## Limitations
Or pass it directly:
```bash
python codex_cli.py generate -p "your prompt" --token hf_xxxx
# or
export HF_TOKEN=hf_xxxx
```

- Generated code should be reviewed before use
- Larger models (13B, 34B) require more VRAM
- First run downloads ~7-15GB of model weights
## Using Ollama (fully local, no internet needed after setup)

## Contributing
```bash
# 1. Install Ollama from https://ollama.com
# 2. Pull a model
ollama pull codellama
# 3. Run
python codex_cli.py generate -p "quicksort in C++" -l cpp -b ollama -m codellama
```

Contributions welcome! Areas for improvement:
- Support for more models
- Fine-tuning for specific languages
- Web UI
- Streaming output
## Examples

## License
```bash
# Python utility
python codex_cli.py generate -p "parse a CSV file and return rows as dicts" -l python

MIT License - See LICENSE file
# JavaScript async function
python codex_cli.py generate -p "fetch JSON from an API with retry logic" -l javascript

## Disclaimer
# SQL query
python codex_cli.py generate -p "find all customers who placed more than 3 orders in the last 30 days" -l sql

This tool generates code suggestions. Always review generated code for correctness and security before deploying to production.
# Shell script
python codex_cli.py generate -p "backup a directory to S3 with date-stamped folder" -l bash -o backup.sh
```

## Resources
## License

- [CodeLlama Documentation](https://ai.meta.com/blog/code-llama-large-language-model-for-code/)
- [StarCoder](https://huggingface.co/bigcode/starcoder)
- [Transformers Library](https://huggingface.co/docs/transformers/)
MIT — see LICENSE file.
97 changes: 97 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""
Free AI Code Generator — Gradio Web UI
Run: python app.py
"""

import os
import gradio as gr
from codex_cli import HFInferenceBackend, OllamaBackend, MODELS, _format_prompt


def generate_code(
prompt: str,
language: str,
model_key: str,
backend: str,
temperature: float,
max_tokens: int,
hf_token: str,
) -> str:
if not prompt.strip():
return "Please enter a prompt."

try:
if backend == "HuggingFace API (free)":
gen = HFInferenceBackend(model_key=model_key, api_token=hf_token or None)
else:
gen = OllamaBackend(model=model_key)

formatted = _format_prompt(prompt, language)
return gen.generate(formatted, max_length=max_tokens, temperature=temperature)
except Exception as e:
return f"Error: {e}"


with gr.Blocks(title="Free AI Code Generator", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# Free AI Code Generator
Generate code from plain English — powered by open-source models via HuggingFace or Ollama.
**No API key required** for the free HuggingFace tier (rate-limited).
Add your [HuggingFace token](https://huggingface.co/settings/tokens) for higher limits.
"""
)

with gr.Row():
with gr.Column(scale=2):
prompt_box = gr.Textbox(
label="Describe what you want",
placeholder="Write a function that reverses a linked list",
lines=4,
)
with gr.Row():
language = gr.Dropdown(
["python", "javascript", "typescript", "go", "rust", "java",
"c++", "c#", "ruby", "bash", "sql"],
value="python", label="Language"
)
model_key = gr.Dropdown(
list(MODELS.keys()), value="starcoder2", label="Model"
)
with gr.Row():
backend = gr.Radio(
["HuggingFace API (free)", "Ollama (local)"],
value="HuggingFace API (free)", label="Backend"
)
with gr.Accordion("Advanced", open=False):
temperature = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Temperature")
max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens")
hf_token = gr.Textbox(
label="HuggingFace token (optional)",
placeholder="hf_...",
type="password",
)
generate_btn = gr.Button("Generate", variant="primary")

with gr.Column(scale=3):
output_code = gr.Code(label="Generated Code", language="python", lines=25)

generate_btn.click(
fn=generate_code,
inputs=[prompt_box, language, model_key, backend, temperature, max_tokens, hf_token],
outputs=output_code,
)

gr.Examples(
examples=[
["Write a binary search function", "python", "starcoder2"],
["Create a REST API endpoint for user login", "javascript", "starcoder2"],
["Implement a stack using two queues", "go", "deepseek"],
["Write a SQL query to find duplicate emails", "sql", "phi2"],
],
inputs=[prompt_box, language, model_key],
)

if __name__ == "__main__":
demo.launch(share=False)
Loading