MCPcopy Create free account
hub / github.com/FareedKhan-dev/ai-long-task / evolve_function

Function evolve_function

api.py:258–345  ·  view source on GitHub ↗

Evolve a specific Python function based on a set of test cases. Args: func: The initial function to evolve. test_cases: A list of (input, expected_output) tuples for validation. iterations: The number of evolution iterations to run. **kwargs: Additional argu

(
    func: Callable, test_cases: List[Tuple[Any, Any]], iterations: int = 100, **kwargs
)

Source from the content-addressed store, hash-verified

256# --- Additional Helper Functions for Common Use Cases ---
257
258def evolve_function(
259 func: Callable, test_cases: List[Tuple[Any, Any]], iterations: int = 100, **kwargs
260) -> EvolutionResult:
261 """
262 Evolve a specific Python function based on a set of test cases.
263
264 Args:
265 func: The initial function to evolve.
266 test_cases: A list of (input, expected_output) tuples for validation.
267 iterations: The number of evolution iterations to run.
268 **kwargs: Additional arguments to pass to the main `run_evolution` function.
269
270 Returns:
271 An EvolutionResult object with the optimized function.
272 """
273
274 # Get the source code of the provided function.
275 func_source = inspect.getsource(func)
276 func_name = func.__name__
277
278 # Ensure the function source has evolution markers. If not, add them around the function body.
279 if "EVOLVE-BLOCK-START" not in func_source:
280 lines = func_source.split("\n")
281 # Find the line where the function is defined.
282 func_def_line = next(i for i, line in enumerate(lines) if line.strip().startswith("def "))
283
284 # A simplified approach to find the end of the function by looking for a change in indentation.
285 indent = len(lines[func_def_line]) - len(lines[func_def_line].lstrip())
286 func_end = len(lines)
287 for i in range(func_def_line + 1, len(lines)):
288 if lines[i].strip() and (len(lines[i]) - len(lines[i].lstrip())) <= indent:
289 func_end = i
290 break
291
292 # Insert evolution markers into the source code.
293 lines.insert(func_def_line + 1, " " * (indent + 4) + "# EVOLVE-BLOCK-START")
294 lines.insert(func_end + 1, " " * (indent + 4) + "# EVOLVE-BLOCK-END")
295 func_source = "\n".join(lines)
296
297 # Create a custom evaluator function that runs the test cases against the evolved code.
298 def evaluator(program_path):
299 import importlib.util
300
301 # Load the evolved program from its file path.
302 spec = importlib.util.spec_from_file_location("evolved", program_path)
303 if spec is None or spec.loader is None:
304 return {"score": 0.0, "error": "Failed to load program"}
305
306 module = importlib.util.module_from_spec(spec)
307 try:
308 spec.loader.exec_module(module)
309 except Exception as e:
310 return {"score": 0.0, "error": f"Failed to execute program: {str(e)}"}
311
312 if not hasattr(module, func_name):
313 return {"score": 0.0, "error": f"Function '{func_name}' not found"}
314
315 evolved_func = getattr(module, func_name)

Callers

nothing calls this directly

Calls 1

run_evolutionFunction · 0.85

Tested by

no test coverage detected