{"record":{"id":"b1687b48b592797c","repo":"microsoft/autogen","slug":"could-not-compile-function-e","errorCode":null,"errorMessage":"Could not compile function: {e}","messagePattern":"Could not compile function: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py","lineNumber":117,"sourceCode":"\n    def __init__(self, func: str, python_packages: Sequence[str] = [], global_imports: Sequence[Import] = []):\n        self.func = func\n        self.python_packages = python_packages\n        self.global_imports = global_imports\n\n        module_name = \"func_module\"\n        loader = _StringLoader(func)\n        spec = spec_from_loader(module_name, loader)\n        if spec is None:\n            raise ValueError(\"Could not create spec\")\n        module = module_from_spec(spec)\n        if spec.loader is None:\n            raise ValueError(\"Could not create loader\")\n\n        try:\n            spec.loader.exec_module(module)\n        except Exception as e:\n            raise ValueError(f\"Could not compile function: {e}\") from e\n\n        functions = inspect.getmembers(module, inspect.isfunction)\n        if len(functions) != 1:\n            raise ValueError(\"The string must contain exactly one function\")\n\n        self._func_name, self.compiled_func = functions[0]\n\n    def __call__(self, *args: Any, **kwargs: Any) -> None:\n        raise NotImplementedError(\"String based function with requirement objects are not directly callable\")\n\n\n@dataclass\nclass FunctionWithRequirements(Generic[T, P]):\n    func: Callable[P, T]\n    python_packages: Sequence[str] = field(default_factory=list)\n    global_imports: Sequence[Import] = field(default_factory=list)\n\n    @classmethod","sourceCodeStart":99,"sourceCodeEnd":135,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py#L99-L135","documentation":"FunctionWithRequirementsStr executes your source string as a module (spec.loader.exec_module) at construction time and wraps any exception raised during execution — syntax errors, missing imports, or top-level runtime errors — in ValueError('Could not compile function: <original error>'). The original exception is chained (`from e`), so the full traceback of your actual mistake is preserved one level down.","triggerScenarios":"Passing a string whose code imports a package not installed in the current process (`import numpy` without numpy), has a syntax error, or raises at module level (e.g. a constant computed by calling something undefined). Note: the import runs in YOUR interpreter, not in the later code-execution sandbox.","commonSituations":"Listing packages in python_packages=['numpy'] for the remote executor while numpy is absent locally; LLM- or template-generated code strings with typos; strings copied from files with smart quotes or indentation damage.","solutions":["Read the chained exception (`e.__cause__`) — it contains the real SyntaxError/ModuleNotFoundError with line info.","Install the imported packages in the local environment or vendor the imports lazily inside the function body.","Validate the string first: `compile(func_string, '<func>', 'exec')` catches syntax errors cheaply before constructing.","Keep the string to exactly one function with no top-level executable code besides imports/defs."],"exampleFix":"# before\nf = FunctionWithRequirementsStr(\n    \"def transform(x):\\n    import numpy as np\\n    return np.array(x)\",\n    python_packages=[\"numpy\"],\n)  # ValueError: Could not compile function: ModuleNotFoundError: numpy (if numpy missing locally)\n\n# after (import only what exists locally, or install numpy first)\nf = FunctionWithRequirementsStr(\n    \"def transform(x):\\n    return [float(v) for v in x]\",\n    python_packages=[],\n)","handlingStrategy":"validation","validationCode":"def compiles_cleanly(source: str) -> bool:\n    try:\n        compile(source, \"<func>\", \"exec\")\n        return True\n    except SyntaxError:\n        return False\n\nassert compiles_cleanly(func_string)","typeGuard":null,"tryCatchPattern":"try:\n    f = FunctionWithRequirementsStr(src)\nexcept ValueError as e:\n    cause = e.__cause__  # the real SyntaxError / ModuleNotFoundError\n    raise RuntimeError(f\"function string failed to load: {cause}\") from cause","preventionTips":["Ensure every package imported at the top of the string is installed in the local interpreter too.","compile() the string before handing it to FunctionWithRequirementsStr to surface syntax errors early.","Prefer FunctionWithRequirements.from_callable when the function already exists locally as code."],"tags":["python","autogen-core","code-executor","dynamic-code","imports"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}