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

openevolve
algorithmicsuperintelligenceApache-2.0活跃维护开源复现 DeepMind AlphaEvolve 的进化式编码 Agent,用遗传算法和分布式进化自动搜索并优化代码,适合做算法发现与程序自动改进。
Open-source implementation of AlphaEvolve
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 50README 未说明显存或 GPU 型号要求;运行本身只需 Python 3.10+ 和可访问的 LLM,示例默认调用 Google Gemini(有免费额度),也提供 Docker 镜像。
用 LLM 变异程序并做进化搜索的开源 AlphaEvolve 实现,把可打分的优化问题交给它自动找算法
开源复现 DeepMind AlphaEvolve 的进化式编码 Agent,用遗传算法和分布式进化自动搜索并优化代码,适合做算法发现与程序自动改进。
核心能力
- 用 MAP-Elites 按特征维度保留多样化程序
- 多岛屿种群加周期迁移,避免过早收敛
- 支持多模型加权集成,兼容 OpenAI 接口与 Claude Code、Copilot、Codex CLI
- 把报错和评估器输出回灌到下一代提示词
- 用 EVOLVE-BLOCK 注释标记待进化代码块,全流程可复现
容易踩的坑
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
- v0.4.1最新正式版2026-11-02 · 2026-11-02 06:35 UTC
Highlights
- Mixed evolution modes (#580, thanks @SUPR1M3):
full_rewrite_probabilitymakes 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. Default0.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.runraisesEvolutionFailedErrorand 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-argsforwards keyword arguments toevaluate()(#506)logger_prefixand--logger-prefixtell parallel runs apart in the logs (#507)checkpoint_on_improvementsaves a checkpoint when a new best is found (#461)evolution_trace.include_failureslogs 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
AsyncOpenAIrather 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)
- Mixed evolution modes (#580, thanks @SUPR1M3):
- 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.
ProgramDatabasevalidates the decisions and still owns every mutation. Default behaviour is unchanged. - LLM token usage tracking (#490):
prompt_tokens,completion_tokensandtotal_tokensare 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_cliprovider that drivescopilot -pnon-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 theEVOLVE-BLOCK-START/ENDregions 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. Defaultfalse. - Custom embedding endpoint (#494):
database.embedding_api_base(orOPENAI_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
=======,<<<<<<< SEARCHor>>>>>>> REPLACEline used to be written into the candidate program. The whole response is now rejected before anything is applied. Customdiff_patternvalues 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_NOVELresponses 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
OpenEvolveconfig usage examples (#479). - Documented
enforce_evolve_blocksandembedding_api_base.
Behaviour changes to note
- Diffs that change nothing, and full rewrites identical to the parent, are now rejected instead of evaluated.
extract_diffsandapply_diffraiseValueErroron 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
- 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.
- v0.3.22026-07-18 · 2026-07-18 13:16 UTC
查看更新说明
Bug fixes
Booleans in metrics are flags, not scores.
boolis a subclass ofint, so a naiveisinstance(value, (int, float))check silently treatedTrue/Falseas1.0/0.0. OpenEvolve's own evaluator emitstimeout: Trueas a metric, so this was not a hypothetical input.- Fitness math (
utils/metrics_utils.py) — the significant one. When an evaluation timed out,evaluator.pyreturns{"error": 0.0, "timeout": True}, whichsafe_numeric_averagescored as 0.5 — handing a program that failed outright a mid-range fitness and letting it compete for survival in the MAP-Elites database. Bothsafe_numeric_average()andget_fitness_score()now exclude booleans, so it correctly scores 0.0.combined_scoreprecedence and feature-dimension exclusion are unaffected. - Formatting (
utils/format_utils.py) — boolean metrics render astimeout=Truerather than a meaninglesstimeout=1.0000, and are skipped when computing improvements (a flag flippingFalse → Trueis not a+1.0000improvement).
Cleanup
- Removed the module-level
_format_metrics/_format_improvementhelpers fromcontroller.py. They were dead code — never called, since the controller imports the sharedformat_utilsversions — 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
- Fitness math (
- v0.3.12026-07-14 · 2026-07-14 00:49 UTC
查看更新说明
Bug fixes
llm.providerwas silently dropped (#472):LLMConfigpropagates shared settings to each per-modelLLMModelConfigvia ashared_configdict, but that dict omittedprovider. Every model keptprovider=None, soLLMEnsemblerouted them all to the OpenAI backend regardless of the config — a config withprovider: claude_codecrashed with a missing-OPENAI_API_KEYerror, makingexamples/claude_code_quickstartunusable. An explicit per-modelproviderstill takes precedence.
Features
run_evolution()acceptstarget_scoreandcheckpoint_path(#457): both already existed oncontroller.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
- 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 bynum_diverse_programs, and deduplicated inspirations against the top/diverse programs shown in the prompt. - Library API: fixed
run_evolution()with a lambda evaluator raisingSyntaxError(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-250mmodel (served via optillm) instead of the gated gemma, with a boundedmax_tokens. - The full integration suite runs in CI (no longer skipping real-LLM tests), with HF model caching and the
math-verifydependency 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
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
| Paper | How OpenEvolve is used |
|---|---|
| New Bounds for Zarankiewicz Numbers via Reinforced LLM Evolutionary Search | New bounds in extremal combinatorics, obtained with OpenEvolve |
| Let the Barbarians In: How AI Can Accelerate Systems Performance Research | Ten systems performance case studies, using OpenEvolve among other tools |
| Algorithmic Algorithm Development with LLMs | Contraction order optimization for tensor networks |
| Even with AI, Bijection Discovery is Still Hard | Combinatorial bijection discovery |
Security research
| Paper | How OpenEvolve is used |
|---|---|
| Trojan Hippo Bench | Adaptive red-teaming benchmark for persistent memory attacks on LLM agents |
| Divide and Inject | Refining indirect prompt injection fragments |
| LLM-Guided Prompt Evolution for Password Guessing | Evolving prompts that maximize cracking rate |
| Targeted Black-Box Attacks on Perceptual Hash Algorithms | Evolutionary attack framework based on GigaEvo and OpenEvolve |
Building on OpenEvolve
| Paper | Relationship |
|---|---|
| Hill Sampling for Test-Time Scaling | Builds on OpenEvolve's problems and evaluators |
| CodeEvolve: Runtime-Enriched Target Selection | Extends OpenEvolve for Java and Salesforce Apex |
| GraphIR | Neural architecture search states integrated into OpenEvolve |
| SwarmEvolve: Latent Agent Swarms for Evolutionary Discovery and Optimization · Code | Uses 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
| Domain | Achievement | Example |
|---|---|---|
| GPU optimization | Hardware-optimized kernel discovery, with 2-3x speedups on real hardware | MLX Metal Kernels |
| Mathematics | State-of-the-art circle packing (n=26) | Circle Packing |
| Algorithm design | Adaptive sorting algorithms | Rust Adaptive Sort |
| Scientific computing | Automated filter design | Signal Processing |
| Multi-language | Python, Rust, R, Metal shaders | All Examples |
| Generation 1 | Generation 190 | Generation 460 (final) |
|---|---|---|
![]() | ![]() | ![]() |
| Random placement | Learning structure | State-of-the-art result |
Compared with manual optimization:
| Aspect | Manual Optimization | OpenEvolve |
|---|---|---|
| Time to solution | Days to weeks | Hours |
| Exploration breadth | Limited by human creativity | Unlimited LLM creativity |
| Reproducibility | Hard to replicate | Fully deterministic |
| Multi-objective | Complex tradeoffs | Automatic Pareto optimization |
| Scaling | Doesn't scale | Parallel 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

- 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
| Project | Domain | What it evolves |
|---|---|---|
| Function Minimization | Optimization | Random search to simulated annealing |
| Circle Packing | Mathematics | The n=26 AlphaEvolve task |
| AlphaEvolve Math Problems | Mathematics | Problems from AlphaEvolve's appendices |
| MLX GPU Kernels | Hardware | Apple Silicon Metal kernels |
| Rust Adaptive Sort | Algorithms | Data-aware sorting |
| Symbolic Regression | Science | Equation discovery on LLM-SRBench |
| Prompt Optimization | LLMs | Prompts instead of code |
| Online Judge | Programming | Competitive programming solutions |
| Web Scraper + OptiLLM | AI integration | Test-time compute |
Running Google's AlphaEvolve examples? See the interoperability walkthrough.
Documentation
- How It Works: the evolution pipeline and its features
- LLM Providers: provider setup and cost
- Configuration: options, evaluator arguments, prompt templates, island and population strategies, artifacts, and the visualizer
- System Messages: the guidance that matters most for good results
- Showcase: worked before-and-after examples
- FAQ and Roadmap
Articles:
- Towards Open Evolutionary Agents
- OpenEvolve: GPU Kernel Discovery
- OpenEvolve: Evolutionary Coding with LLMs
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}
}


