Skip to main content

Universal Loop Engineering System — iterative AI execution for any LLM provider with tool support

Project description

🔄 LOOP ENGINE

Typing SVG

Generate → Evaluate → Refine → Converge

Python License Providers Free

Anthropic OpenAI Google Groq OpenRouter Ollama


Perfect for • Claude • Kiro • Cursor • Codex • LangChain • n8n • Any AI Workflow


🎬 See It In Action

from loop_engine import run_loop

result = run_loop(
    task="Create a FastAPI user auth endpoint",
    success_criteria="JWT tokens, password hashing, type hints",
    failure_criteria="Hardcoded secrets, no validation",
    max_iterations=5
)
# ✨ Automatically iterates until perfect!

🔥 How It Works

Loop Engine Flow Animation

⚡ Why Loop Engine Beats Single-Shot AI

🤖 Traditional AI 🔄 Loop Engine
One attempt only ✅ Iterates until perfect
Manual re-prompting ✅ Automatic refinement
No quality control ✅ Built-in scoring (1-10)
Often misses requirements ✅ Checks YOUR criteria
Generic output ✅ Converges to YOUR standards
Unsafe code changes ✅ Git isolation (optional sandbox)
No validation ✅ Test execution integration

Install

pip install loop-engine[all]  # All providers
# or
pip install loop-engine       # Just core

Set API key (any provider):

export ANTHROPIC_API_KEY="your_key"
# or OPENAI_API_KEY, GOOGLE_API_KEY, etc.

Quick Start

CLI

loop-engine run  # Interactive mode

Python

from loop_engine import run_loop

result = run_loop(
    task="Create a FastAPI user auth endpoint",
    success_criteria="JWT tokens, password hashing, type hints, error handling",
    failure_criteria="Hardcoded secrets, no validation, missing docstrings",
    max_iterations=5,
    provider="anthropic"  # auto-detects if not specified
)

print(result.final.output)
print(f"Quality: {result.final.quality_score}/10")

Supported Providers

Provider Models Setup
Anthropic Claude 3.5 Sonnet, Claude 3 Opus ANTHROPIC_API_KEY
OpenAI GPT-4, GPT-4o OPENAI_API_KEY
Google Gemini 2.0 Flash, Gemini 1.5 Pro GOOGLE_API_KEY
OpenRouter 200+ models OPENROUTER_API_KEY
Groq Llama 3.3, Mixtral (ultra-fast) GROQ_API_KEY
DeepSeek DeepSeek Chat, DeepSeek Coder DEEPSEEK_API_KEY
AWS Bedrock Claude, Llama on AWS AWS credentials
Azure OpenAI GPT-4 on Azure AZURE_OPENAI_API_KEY
Ollama Local models (free) Ollama running locally

Built-in Tools

Enable with --tools or enable_tools=True:

  • read_file - Read file contents
  • write_file - Write to files
  • list_directory - List directory contents
  • execute_command - Run shell commands
  • search_files - Find files by pattern
  • create_directory - Create directories

Test Execution (NEW!)

Run tests automatically during iterations:

result = run_loop(
    task="Write a function to validate emails",
    success_criteria="Regex validation, type hints, passes tests",
    failure_criteria="No validation, tests fail",
    test_command="pytest tests/test_email.py",  # ✨ NEW!
    max_iterations=5
)
# Tests run each iteration - quality score boosted if they pass!

Git Isolation (NEW!)

Safe code modifications in isolated environment:

result = run_loop(
    task="Refactor auth module to use async/await",
    success_criteria="All async, passes tests",
    failure_criteria="Breaking changes",
    enable_tools=True,
    test_command="pytest tests/",
    use_isolation=True,  # 🔒 Safe isolation!
    isolation_path=".",  # Your git repo
    max_iterations=8
)
# Creates temporary worktree → AI edits → Tests → Merges if good!

How Git Isolation Works:

  1. Creates temporary copy (worktree) of your code
  2. AI modifies the COPY, not your real files
  3. Runs tests in isolation
  4. If successful → merges back to main
  5. If fails → deletes copy, your code untouched

When to use:

  • ✅ Automated refactoring of production code
  • ✅ Large multi-file changes
  • ✅ When you want safety guarantees
  • ❌ Simple code generation (overkill)

Custom Tools

from loop_engine import register_custom_tool

def my_tool(arg: str) -> dict:
    return {"result": f"Processed: {arg}"}

register_custom_tool(
    name="my_tool",
    func=my_tool,
    definition={
        "name": "my_tool",
        "description": "My custom tool",
        "parameters": {
            "type": "object",
            "properties": {
                "arg": {"type": "string", "description": "Argument"}
            },
            "required": ["arg"]
        }
    }
)

Examples

Check /examples directory:

  • basic_example.py - Simple usage (2 seconds)
  • tools_example.py - File operations with tools
  • complete_system_test.py - Full system validation

Best Practices

For Simple Tasks (Fast)

# Just basic loop - 2-5 seconds per iteration
run_loop(task, success, failure, max_iterations=3)

For Code with Tests

# Add test execution for validation
run_loop(
    task, success, failure,
    test_command="pytest tests/",
    max_iterations=5
)

For Production Code (Maximum Safety)

# Full safety: isolation + tests
run_loop(
    task, success, failure,
    enable_tools=True,
    test_command="pytest tests/",
    use_isolation=True,  # Safe sandbox
    isolation_path=".",
    max_iterations=10
)

Tips for Best Results

  1. Be specific: "TypeScript, uses async/await, <200 lines" > "good code"
  2. Set hard failures: "No eval(), no hardcoded secrets"
  3. Start with 3-5 iterations: Most tasks converge quickly
  4. Use tools for file ops: Enable tools when working with existing code
  5. Add context: Provide project structure, patterns, requirements

Configuration

Create ~/.loop-engine/config.yaml:

max_iterations: 5
convergence_threshold: 8
provider: auto

tools:
  enabled: false
  allowed_tools: [all]

providers:
  anthropic:
    model: claude-sonnet-4-20250514
    max_tokens: 4000

Or use loop-engine init to generate automatically.


License

MIT License - see LICENSE file


Support

  • Examples: /examples directory
  • Issues: GitHub Issues
  • Config: loop-engine status to see current setup

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

loop_prompting-2.1.0.tar.gz (29.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

loop_prompting-2.1.0-py3-none-any.whl (32.5 kB view details)

Uploaded Python 3

File details

Details for the file loop_prompting-2.1.0.tar.gz.

File metadata

  • Download URL: loop_prompting-2.1.0.tar.gz
  • Upload date:
  • Size: 29.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for loop_prompting-2.1.0.tar.gz
Algorithm Hash digest
SHA256 38784f35736a105e464d400d8d23ec59c362510f75386dc40d17d47d2a3b7884
MD5 2025c3beecdbfc8cc58536348bcde997
BLAKE2b-256 3d0898e00e358e3bf672d78942a4799be355c9063d0d455430476a9ab155a6e9

See more details on using hashes here.

File details

Details for the file loop_prompting-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: loop_prompting-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 32.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for loop_prompting-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 db32eea0c075425168fcfb1cb5f6a20c89d6ec093da787c596740f56a154dfb7
MD5 678967187edd8a515dbfdb23f981557f
BLAKE2b-256 d32820dbba99769bc3c207431b330025c4a8188111507c83f57faed945987a62

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page