microsoft/autogen · error · ValueError

The string must contain exactly one function

Error message

The string must contain exactly one function

What it means

After executing the module, FunctionWithRequirementsStr enumerates module-level functions with inspect.getmembers(..., inspect.isfunction) and requires exactly one. Zero functions (only statements/classes), two or more defs (e.g. a helper function), or a string where the target is a lambda assigned to a name all break the count. Imports do not count: an `import`ed function is a module attribute only if it is a plain function, which can also skew the count.

Source

Thrown at python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py:121

        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)

    @classmethod
    def from_callable(
        cls, func: Callable[P, T], python_packages: Sequence[str] = [], global_imports: Sequence[Import] = []
    ) -> FunctionWithRequirements[T, P]:
        return cls(python_packages=python_packages, global_imports=global_imports, func=func)

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Ensure the string defines exactly one top-level `def` and no other function definitions.
  2. Inline helpers as nested functions inside the single def.
  3. If multiple functions are genuinely needed, wrap them in a class or pass each as its own FunctionWithRequirementsStr.

Example fix

# before (two functions)
f = FunctionWithRequirementsStr("def helper(v): return v * 2\ndef main(x): return helper(x) + 1")

# after (single function, helper nested)
f = FunctionWithRequirementsStr(
    "def main(x):\n    def helper(v): return v * 2\n    return helper(x) + 1"
)
Defensive patterns

Strategy: validation

Validate before calling

import ast

def defines_exactly_one_function(source: str) -> bool:
    tree = ast.parse(source)
    return sum(isinstance(n, ast.FunctionDef) for n in tree.body) == 1

Prevention

When it happens

Trigger: Passing "x = 1" (no def), a string with "def helper(): ..." plus "def main(): ..." (two functions), or a string that does `from math import sqrt` (sqrt is a builtin, not isfunction, so safe) versus `from mymod import util` where util is a Python function (counts as a second function).

Common situations: Refactoring a single function into main + helpers without merging them into one def; embedding decorators defined in the same string; copy-pasting a multi-function module into the func parameter.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/5da4e8a00df09fc9. Report an issue: GitHub.