openevolve

algorithmicsuperintelligenceApache-2.0活跃维护

开源复现 DeepMind AlphaEvolve 的进化式编码 Agent,用遗传算法和分布式进化自动搜索并优化代码,适合做算法发现与程序自动改进。

Open-source implementation of AlphaEvolve

v0.4.1发布于 2026-11-02 06:35 UTC7,748star +19 / 7 天1,216fork同步于 2026-11-10 05:32 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/algorithmicsuperintelligence/openevolve.git
cd openevolve
pip install -e .
export OPENAI_API_KEY="your-gemini-api-key"
python openevolve-run.py examples/function_minimization/initial_program.py examples/function_minimization/evaluator.py --config examples/function_minimization/config.yaml --iterations 50
硬件要求按 README 说明

README 未说明显存或 GPU 型号要求;运行本身只需 Python 3.10+ 和可访问的 LLM,示例默认调用 Google Gemini(有免费额度),也提供 Docker 镜像。

支持 Apple Silicon有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 LLM 变异程序并做进化搜索的开源 AlphaEvolve 实现,把可打分的优化问题交给它自动找算法

开源复现 DeepMind AlphaEvolve 的进化式编码 Agent,用遗传算法和分布式进化自动搜索并优化代码,适合做算法发现与程序自动改进。

核心能力

  • 用 MAP-Elites 按特征维度保留多样化程序
  • 多岛屿种群加周期迁移,避免过早收敛
  • 支持多模型加权集成,兼容 OpenAI 接口与 Claude Code、Copilot、Codex CLI
  • 把报错和评估器输出回灌到下一代提示词
  • 用 EVOLVE-BLOCK 注释标记待进化代码块,全流程可复现

容易踩的坑

示例默认用 Gemini,但环境变量名是 OPENAI_API_KEY,换其他厂商要改 config.yaml 里的 api_base 和模型;在 macOS 和 Windows 上以库方式调用必须加 main 保护,因为多进程用 spawn;要进化的代码需用 EVOLVE-BLOCK-START/END 注释标出,否则不会按预期变异。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README
这个条目还没有人工点评。如果它对你很有用,欢迎到 提交仓库 页写下你的使用经验。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    最近发版

    5 个版本v0.4.1
    1. v0.4.1最新正式版2026-11-02 · 2026-11-02 06:35 UTC

      Highlights

      • Mixed evolution modes (#580, thanks @SUPR1M3): full_rewrite_probability makes a share of diff-based iterations ask for a full rewrite instead. The mode used is recorded on each program and in the evolution trace. Default 0.0.
      • AlphaEvolve interoperability (#519, #520, #522, #526, #527, #529, #532, #534, #535, #540, #541): opt-in adapters run Google's AlphaEvolve examples and evaluators locally, and export limited settings and Python bundles the other way.
      • Competitive evolution (#505): alternating competitive evolution with phase checkpoints.
      • Codex app-server provider (#512): use a ChatGPT subscription as the LLM backend, with no API key.
      • Per-island setup: per-island system messages (#496) and per-island initial programs (#547).
      • Runs that generate nothing now fail (#545): if no iteration produces a candidate, OpenEvolve.run raises EvolutionFailedError and the CLI exits with code 1, rather than presenting the seed as the evolved result.
      • Rewritten README (#580): shorter, and it now leads with research using OpenEvolve. Detailed guides moved to docs/.

      New options

      • --evaluator-args forwards keyword arguments to evaluate() (#506)
      • logger_prefix and --logger-prefix tell parallel runs apart in the logs (#507)
      • checkpoint_on_improvement saves a checkpoint when a new best is found (#461)
      • evolution_trace.include_failures logs failed iterations, including timeouts and crashes, to <trace name>_failures.jsonl (#580)
      • metadata["llm_model"] records which model generated each program (#580)

      Bug fixes

      Evolution and database

      • Novelty-rejected programs are dropped from the database (#528)
      • Island migrants are chosen before any are moved (#524)
      • New island maps are initialized when resuming checkpoints (#530)
      • Checkpoint feature statistics are retained during construction (#510)
      • Inspiration sampling fills the available slots in small islands and bounds neighbors per feature dimension (#508, #509)
      • Early stopping honors patience with a zero convergence threshold and skips failed evaluations in the plateau count (#566, #502)
      • Explicit zero iteration budgets are honored (#531)
      • Very large finite metrics no longer overflow fallback fitness averages (#583)

      LLM and workers

      • Model sampling and request seeds vary per iteration in workers, so runs stay reproducible and parallel iterations don't repeat the same response (#559, #582)
      • Ensemble weights are validated and safely normalized, zero primary-model weights are preserved, and zero-weight judges are skipped (#570, #533, #567)
      • CLI backends: Claude Code gets the prompt over stdin and failed responses are rejected, text pipes use UTF-8, and the Codex process stops before its pipes close (#497, #576, #577, #578)
      • Requests use AsyncOpenAI rather than a sync client in an executor (#513)
      • Custom clients no longer need a model field (#568)
      • All top-level config fields reach worker processes (#517), the worker event loop is preserved (#556), and callable evaluators work in subprocess workers (#423)

      Parsing and evaluation

      • Only whole lines count as SEARCH/REPLACE markers (#546)
      • Full-rewrite code fences handle CRLF, whitespace after the language, literal languages and language-tag fallback (#491, #523, #544)
      • Java declarations are recognized before generic imports (#560)
      • Boolean flags survive cascade evaluation, invalid LLM judge metrics are ignored, and partial judge ensembles keep valid feedback (#572, #573, #511)
      • Embedding vector shapes are preserved after provider failures (#571)
      • Top-program metrics in prompts use a neutral label (#539)

      Evolution trace and visualizer

      • Children whose parent left the archive are still traced (#581)
      • Trace payloads are snapshotted, and JSON export metadata can be reused (#579, #575)
      • HDF5 metadata lists round-trip, and strings that look like JSON stay strings (#580)
      • The visualizer normalizes checkpoint paths before discovery (#525)
    2. v0.4.02026-09-28 · 2026-09-28 03:29 UTC
      查看更新说明

      Highlights

      • Pluggable island selection and population strategies (#493): an optional island selector plus decision-returning hooks for admission, MAP-Elites cell replacement, archive membership, eviction and migration. ProgramDatabase validates the decisions and still owns every mutation. Default behaviour is unchanged.
      • LLM token usage tracking (#490): prompt_tokens, completion_tokens and total_tokens are captured from OpenAI-compatible responses, carried back from workers, stored in program metadata and prompt logs, and reported per iteration and as a run total.
      • GitHub Copilot CLI backend (#482): a copilot_cli provider that drives copilot -p non-interactively, using the CLI's own login, so no API key is needed.
      • Opt-in EVOLVE-BLOCK enforcement (#494): with enforce_evolve_blocks: true, every edit outside the EVOLVE-BLOCK-START/END regions is reverted to the parent code before evaluation, and responses that change or remove the markers are rejected. Markers are now recognised after any comment syntax (#, //, /*, --, %), so evolve blocks work in C, Java and other languages. Default false.
      • Custom embedding endpoint (#494): database.embedding_api_base (or OPENAI_EMBEDDING_BASE_URL) points novelty embeddings at any OpenAI-compatible endpoint, such as OpenRouter or a local server.

      Bug fixes

      • Malformed SEARCH/REPLACE diffs are rejected (#494, thanks @brriorda): an extra or unmatched =======, <<<<<<< SEARCH or >>>>>>> REPLACE line used to be written into the candidate program. The whole response is now rejected before anything is applied. Custom diff_pattern values keep their own grammar.
      • Unapplied and no-op diffs are no longer evaluated (#494): a SEARCH block that matched nothing was skipped silently, so the unchanged parent was evaluated again as a "new" child. Responses where no block matches, or where the result equals the parent (including identical full rewrites), are now reported as errors, and partial matches log a warning. SEARCH lines also match when they differ only in trailing whitespace.
      • Timed-out evaluations no longer hang the worker (#485): evaluations run on a dedicated executor, so a timed-out stage returns promptly instead of blocking asyncio.run() shutdown.
      • NOT_NOVEL responses are parsed correctly (#486), including explained and Markdown-wrapped answers.
      • Non-streaming chat completions (#494): requests are sent with stream=False. Endpoints that stream by default no longer fail with 'str' object has no attribute 'choices', and a raw streamed response now raises a clear error.

      Security

      • Visualizer debug mode is off by default (#494): the Flask debugger is now opt-in with --debug.

      Performance

      • Checkpoints create the programs/ directory once per save instead of once per program (#478).

      Docs

      • Corrected the OpenEvolve config usage examples (#479).
      • Documented enforce_evolve_blocks and embedding_api_base.

      Behaviour changes to note

      • Diffs that change nothing, and full rewrites identical to the parent, are now rejected instead of evaluated.
      • extract_diffs and apply_diff raise ValueError on malformed delimiters when using the default diff pattern.

      Closes #106, #346, #422, #426, #436.

      Full changelog: https://github.com/algorithmicsuperintelligence/openevolve/compare/v0.3.2...v0.4.0

    3. v0.3.22026-07-18 · 2026-07-18 13:16 UTC
      查看更新说明

      Bug fixes

      Booleans in metrics are flags, not scores. bool is a subclass of int, so a naive isinstance(value, (int, float)) check silently treated True/False as 1.0/0.0. OpenEvolve's own evaluator emits timeout: True as a metric, so this was not a hypothetical input.

      • Fitness math (utils/metrics_utils.py) — the significant one. When an evaluation timed out, evaluator.py returns {"error": 0.0, "timeout": True}, which safe_numeric_average scored as 0.5 — handing a program that failed outright a mid-range fitness and letting it compete for survival in the MAP-Elites database. Both safe_numeric_average() and get_fitness_score() now exclude booleans, so it correctly scores 0.0. combined_score precedence and feature-dimension exclusion are unaffected.
      • Formatting (utils/format_utils.py) — boolean metrics render as timeout=True rather than a meaningless timeout=1.0000, and are skipped when computing improvements (a flag flipping False → True is not a +1.0000 improvement).

      Cleanup

      • Removed the module-level _format_metrics / _format_improvement helpers from controller.py. They were dead code — never called, since the controller imports the shared format_utils versions — and confusingly already contained the bool fix the live path lacked.

      Docs

      • README: switched the PyPI downloads badge to the pepy.tech monthly badge, and dropped the GitHub stars badge (GitHub already displays the star count).

      Full changelog: https://github.com/algorithmicsuperintelligence/openevolve/compare/v0.3.1...v0.3.2

    4. v0.3.12026-07-14 · 2026-07-14 00:49 UTC
      查看更新说明

      Bug fixes

      • llm.provider was silently dropped (#472): LLMConfig propagates shared settings to each per-model LLMModelConfig via a shared_config dict, but that dict omitted provider. Every model kept provider=None, so LLMEnsemble routed them all to the OpenAI backend regardless of the config — a config with provider: claude_code crashed with a missing-OPENAI_API_KEY error, making examples/claude_code_quickstart unusable. An explicit per-model provider still takes precedence.

      Features

      • run_evolution() accepts target_score and checkpoint_path (#457): both already existed on controller.run() but were not exposed, so library users could not resume from a checkpoint or stop at a target score.

      New example

      • examples/background_blur: evolving a hot function behind a hard quality gate — the score is a speedup, but fidelity is pass/fail, so a fast-but-wrong candidate scores zero. Deterministic and numpy-only (no webcam, GPU, model or dataset). Demonstrates cascade evaluation (cheap smoke → quality gate → benchmark, so timing is only spent on candidates that are already correct), artifacts that tell the model why it was rejected, and a (complexity, ssim) MAP-Elites grid.

        It documents two traps worth knowing about:

        • The obvious quality gate is exploitable. Grading mean and worst-frame SSIM lets a "blur frame 0's background and reuse it forever" candidate score 47x while leaving a visible person-shaped ghost — it damages one region and the frame average hides it. Grading the worst 16×16 region catches it. The cheats are encoded as tests so they must lose.
        • Timing-as-fitness needs care. Caching a single baseline measurement lets a transiently loaded machine inflate every later speedup.

      Full changelog: https://github.com/algorithmicsuperintelligence/openevolve/compare/v0.3.0...v0.3.1

    5. v0.3.02026-07-05 · 2026-07-05 06:33 UTC
      查看更新说明

      Bug fixes

      • MAP-Elites eviction (#454): cell owners are now protected during population eviction — non-elite/homeless programs are removed first, preserving diversity.
      • Zombie programs (#454): programs displaced from their MAP-Elites cell are removed instead of lingering as unsampleable entries that consume population slots.
      • Program sampling (#452): removed dead iteration.py, sized inspirations by num_diverse_programs, and deduplicated inspirations against the top/diverse programs shown in the prompt.
      • Library API: fixed run_evolution() with a lambda evaluator raising SyntaxError (return <lambda>(...)); the lambda is now serialized into a self-contained, subprocess-safe evaluator module.
      • Initial program artifacts: artifacts produced while evaluating the initial program are now stored (original PR #462).

      Testing / CI

      • Integration tests now run against the public codelion/dhara-250m model (served via optillm) instead of the gated gemma, with a bounded max_tokens.
      • The full integration suite runs in CI (no longer skipping real-LLM tests), with HF model caching and the math-verify dependency optillm omits.
      • New Frame SAST workflow scans PR-changed Python files for high/critical issues.

      Full changelog: https://github.com/algorithmicsuperintelligence/openevolve/compare/v0.2.27...v0.3.0

    README 原文

    未翻译

    OpenEvolve

    The most advanced open-source evolutionary coding agent

    Turn your LLMs into autonomous code optimizers that discover breakthrough algorithms

    Quick Start • Used In Research • Examples • Docs • Discussions


    OpenEvolve is an open-source implementation of Google DeepMind's AlphaEvolve. It uses LLMs to mutate programs and evolves them with MAP-Elites and island populations, so you can point it at any problem you can score. It has become a standard tool and baseline for LLM-driven algorithm discovery: cited in hundreds of research papers, with 7,600+ GitHub stars, 1,200+ forks, 80+ contributors and 17,000+ monthly PyPI downloads.

    Used In Research

    Producing new results

    PaperHow OpenEvolve is used
    New Bounds for Zarankiewicz Numbers via Reinforced LLM Evolutionary SearchNew bounds in extremal combinatorics, obtained with OpenEvolve
    Let the Barbarians In: How AI Can Accelerate Systems Performance ResearchTen systems performance case studies, using OpenEvolve among other tools
    Algorithmic Algorithm Development with LLMsContraction order optimization for tensor networks
    Even with AI, Bijection Discovery is Still HardCombinatorial bijection discovery

    Security research

    PaperHow OpenEvolve is used
    Trojan Hippo BenchAdaptive red-teaming benchmark for persistent memory attacks on LLM agents
    Divide and InjectRefining indirect prompt injection fragments
    LLM-Guided Prompt Evolution for Password GuessingEvolving prompts that maximize cracking rate
    Targeted Black-Box Attacks on Perceptual Hash AlgorithmsEvolutionary attack framework based on GigaEvo and OpenEvolve

    Building on OpenEvolve

    PaperRelationship
    Hill Sampling for Test-Time ScalingBuilds on OpenEvolve's problems and evaluators
    CodeEvolve: Runtime-Enriched Target SelectionExtends OpenEvolve for Java and Salesforce Apex
    GraphIRNeural architecture search states integrated into OpenEvolve
    SwarmEvolve: Latent Agent Swarms for Evolutionary Discovery and Optimization · CodeUses OpenEvolve's problems and evaluators for 16 AlphaEvolve problems, and benchmarks against OpenEvolve

    New evolutionary agents also routinely benchmark against OpenEvolve, including HarnessTTT, FrugalEvo, SEDIMA, EvoDuet, LoongFlow and AscendOptimizer.

    Using OpenEvolve in your work? Open a pull request to add it here, and see Citation.

    Results

    DomainAchievementExample
    GPU optimizationHardware-optimized kernel discovery, with 2-3x speedups on real hardwareMLX Metal Kernels
    MathematicsState-of-the-art circle packing (n=26)Circle Packing
    Algorithm designAdaptive sorting algorithmsRust Adaptive Sort
    Scientific computingAutomated filter designSignal Processing
    Multi-languagePython, Rust, R, Metal shadersAll Examples
    Generation 1Generation 190Generation 460 (final)
    InitialProgressFinal
    Random placementLearning structureState-of-the-art result

    Compared with manual optimization:

    AspectManual OptimizationOpenEvolve
    Time to solutionDays to weeksHours
    Exploration breadthLimited by human creativityUnlimited LLM creativity
    ReproducibilityHard to replicateFully deterministic
    Multi-objectiveComplex tradeoffsAutomatic Pareto optimization
    ScalingDoesn't scaleParallel evolution across islands

    Quick Start

    Requires Python 3.10+ and access to an LLM.

    git clone https://github.com/algorithmicsuperintelligence/openevolve.git
    cd openevolve
    pip install -e .
    
    # The example uses Google Gemini by default (free tier available)
    # Get your API key from: https://aistudio.google.com/apikey
    export OPENAI_API_KEY="your-gemini-api-key"  # Yes, use OPENAI_API_KEY
    
    python openevolve-run.py examples/function_minimization/initial_program.py \
      examples/function_minimization/evaluator.py \
      --config examples/function_minimization/config.yaml \
      --iterations 50
    

    To use another provider, change api_base and the model in config.yaml. See LLM Providers.

    Or use it as a library (pip install openevolve):

    from openevolve import evolve_function
    
    def bubble_sort(arr):
        for i in range(len(arr)):
            for j in range(len(arr) - 1):
                if arr[j] > arr[j + 1]:
                    arr[j], arr[j + 1] = arr[j + 1], arr[j]
        return arr
    
    if __name__ == "__main__":
        result = evolve_function(
            bubble_sort,
            test_cases=[([3, 1, 2], [1, 2, 3]), ([5, 2, 8], [2, 5, 8])],
            iterations=50,
        )
        print(result.best_code)
    

    run_evolution also takes inline code and an evaluator function. The __main__ guard is required on macOS and Windows, where multiprocessing uses spawn.

    A Docker image is available too:

    docker pull ghcr.io/algorithmicsuperintelligence/openevolve:latest
    
    docker run --rm -v $(pwd):/app ghcr.io/algorithmicsuperintelligence/openevolve:latest \
      examples/function_minimization/initial_program.py \
      examples/function_minimization/evaluator.py --iterations 100
    

    How It Works

    OpenEvolve Architecture

    • Quality-diversity evolution: MAP-Elites keeps diverse programs across feature dimensions.
    • Island populations: separate populations with periodic migration prevent premature convergence.
    • LLM ensembles: weighted combinations of models, from any OpenAI-compatible API or the Claude Code, GitHub Copilot and Codex CLIs.
    • Artifact feedback: errors and evaluator output feed the next generation's prompt.
    • Reproducibility: every component is seeded.

    Mark the code to evolve with EVOLVE-BLOCK-START and EVOLVE-BLOCK-END comments. More in How It Works.

    Good fits are performance optimization, algorithm discovery, scientific computing, competitive programming and multi-objective problems.

    Examples

    ProjectDomainWhat it evolves
    Function MinimizationOptimizationRandom search to simulated annealing
    Circle PackingMathematicsThe n=26 AlphaEvolve task
    AlphaEvolve Math ProblemsMathematicsProblems from AlphaEvolve's appendices
    MLX GPU KernelsHardwareApple Silicon Metal kernels
    Rust Adaptive SortAlgorithmsData-aware sorting
    Symbolic RegressionScienceEquation discovery on LLM-SRBench
    Prompt OptimizationLLMsPrompts instead of code
    Online JudgeProgrammingCompetitive programming solutions
    Web Scraper + OptiLLMAI integrationTest-time compute

    Running Google's AlphaEvolve examples? See the interoperability walkthrough.

    Documentation

    Articles:

    Contributing

    Contributions are welcome. See the Contributing Guide and good first issue labels.

    Citation

    If you use OpenEvolve in your research, please cite:

    @software{openevolve,
      title = {OpenEvolve: an open-source evolutionary coding agent},
      author = {Asankhaya Sharma},
      year = {2025},
      publisher = {GitHub},
      url = {https://github.com/algorithmicsuperintelligence/openevolve}
    }