microsoft/autogen · error · ValueError
Could not compile function: {e}
Error message
Could not compile function: {e} What it means
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.
Source
Thrown at python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py:117
def __init__(self, func: str, python_packages: Sequence[str] = [], global_imports: Sequence[Import] = []):
self.func = func
self.python_packages = python_packages
self.global_imports = global_imports
module_name = "func_module"
loader = _StringLoader(func)
spec = spec_from_loader(module_name, loader)
if spec is None:
raise ValueError("Could not create spec")
module = module_from_spec(spec)
if spec.loader is None:
raise ValueError("Could not create loader")
try:
spec.loader.exec_module(module)
except Exception as e:
raise ValueError(f"Could not compile function: {e}") from e
functions = inspect.getmembers(module, inspect.isfunction)
if len(functions) != 1:
raise ValueError("The string must contain exactly one function")
self._func_name, self.compiled_func = functions[0]
def __call__(self, *args: Any, **kwargs: Any) -> None:
raise NotImplementedError("String based function with requirement objects are not directly callable")
@dataclass
class FunctionWithRequirements(Generic[T, P]):
func: Callable[P, T]
python_packages: Sequence[str] = field(default_factory=list)
global_imports: Sequence[Import] = field(default_factory=list)
@classmethodView on GitHub (pinned to 027ecf0a37)
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.
Example fix
# before
f = FunctionWithRequirementsStr(
"def transform(x):\n import numpy as np\n return np.array(x)",
python_packages=["numpy"],
) # ValueError: Could not compile function: ModuleNotFoundError: numpy (if numpy missing locally)
# after (import only what exists locally, or install numpy first)
f = FunctionWithRequirementsStr(
"def transform(x):\n return [float(v) for v in x]",
python_packages=[],
) Defensive patterns
Strategy: validation
Validate before calling
def compiles_cleanly(source: str) -> bool:
try:
compile(source, "<func>", "exec")
return True
except SyntaxError:
return False
assert compiles_cleanly(func_string) Try / catch
try:
f = FunctionWithRequirementsStr(src)
except ValueError as e:
cause = e.__cause__ # the real SyntaxError / ModuleNotFoundError
raise RuntimeError(f"function string failed to load: {cause}") from cause Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- The string must contain exactly one function
- String based function with requirement objects are not direc
- Could not create spec
- Could not create loader
- Message type not found
AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15).
Data as JSON: /api/errors/b1687b48b592797c.
Report an issue: GitHub.