Evolve arbitrary code with a custom evaluator Args: initial_code: Initial code to evolve evaluator: Function that takes a program path and returns metrics iterations: Number of evolution iterations **kwargs: Additional arguments for run_evolution Return
(
initial_code: str, evaluator: Callable[[str], Dict[str, Any]], iterations: int = 100, **kwargs
)
| 540 | |
| 541 | |
| 542 | def evolve_code( |
| 543 | initial_code: str, evaluator: Callable[[str], Dict[str, Any]], iterations: int = 100, **kwargs |
| 544 | ) -> EvolutionResult: |
| 545 | """ |
| 546 | Evolve arbitrary code with a custom evaluator |
| 547 | |
| 548 | Args: |
| 549 | initial_code: Initial code to evolve |
| 550 | evaluator: Function that takes a program path and returns metrics |
| 551 | iterations: Number of evolution iterations |
| 552 | **kwargs: Additional arguments for run_evolution |
| 553 | |
| 554 | Returns: |
| 555 | EvolutionResult with optimized code |
| 556 | |
| 557 | Example: |
| 558 | initial_code = ''' |
| 559 | def fibonacci(n): |
| 560 | if n <= 1: |
| 561 | return n |
| 562 | return fibonacci(n-1) + fibonacci(n-2) |
| 563 | ''' |
| 564 | |
| 565 | def eval_fib(program_path): |
| 566 | # Evaluate fibonacci implementation |
| 567 | import importlib.util |
| 568 | import time |
| 569 | |
| 570 | spec = importlib.util.spec_from_file_location("fib", program_path) |
| 571 | module = importlib.util.module_from_spec(spec) |
| 572 | spec.loader.exec_module(module) |
| 573 | |
| 574 | try: |
| 575 | start = time.time() |
| 576 | result = module.fibonacci(20) |
| 577 | duration = time.time() - start |
| 578 | |
| 579 | correct = result == 6765 |
| 580 | return { |
| 581 | "score": 1.0 if correct else 0.0, |
| 582 | "runtime": duration, |
| 583 | "correctness": correct |
| 584 | } |
| 585 | except: |
| 586 | return {"score": 0.0} |
| 587 | |
| 588 | result = evolve_code(initial_code, eval_fib, iterations=50) |
| 589 | """ |
| 590 | return run_evolution( |
| 591 | initial_program=initial_code, evaluator=evaluator, iterations=iterations, **kwargs |
| 592 | ) |