{"record":{"id":"cdf0ee1bc0b1a6f8","repo":"microsoft/autogen","slug":"string-based-function-with-requirement-objects-are","errorCode":null,"errorMessage":"String based function with requirement objects are not directly callable","messagePattern":"String based function with requirement objects are not directly callable","errorType":"exception","errorClass":"NotImplementedError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py","lineNumber":126,"sourceCode":"        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\n    def from_callable(\n        cls, func: Callable[P, T], python_packages: Sequence[str] = [], global_imports: Sequence[Import] = []\n    ) -> FunctionWithRequirements[T, P]:\n        return cls(python_packages=python_packages, global_imports=global_imports, func=func)\n\n    @staticmethod\n    def from_str(\n        func: str, python_packages: Sequence[str] = [], global_imports: Sequence[Import] = []\n    ) -> FunctionWithRequirementsStr:","sourceCodeStart":108,"sourceCodeEnd":144,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py#L108-L144","documentation":"FunctionWithRequirementsStr intentionally implements __call__ to raise NotImplementedError: it is a description of code to be executed inside a code executor (with its declared python_packages), not a callable in the current process. Calling `f(...)` locally is always an error by design — the compiled function exists only for inspection/transport.","triggerScenarios":"`f = FunctionWithRequirementsStr(...); f(1, 2)` anywhere in application or test code; passing the object to an API that invokes its arguments (map, pandas.apply, a callback parameter typed Callable).","commonSituations":"Treating FunctionWithRequirementsStr interchangeably with FunctionWithRequirements (whose func IS callable); unit tests trying to assert on behavior by calling it directly instead of running it in a code executor.","solutions":["Execute it via a code executor (e.g. LocalCommandLineCodeExecutor / container executor) that receives functions_with_requirements, rather than calling it in-process.","If you need a locally callable version, use FunctionWithRequirements.from_callable with a real Python function.","Type-annotate executor inputs so type checkers flag direct calls (FunctionWithRequirementsStr is not Callable)."],"exampleFix":"# before\nf = FunctionWithRequirementsStr(\"def run(x): return x * 2\")\nresult = f(3)  # NotImplementedError\n\n# after\nfrom autogen_core.code_executor import LocalCommandLineCodeExecutor\nexecutor = LocalCommandLineCodeExecutor(functions=[f_to_executor_format])\n# hand f to the executor's function list; it runs in the executor, not in-process","handlingStrategy":"type-guard","validationCode":"def is_directly_callable(f: object) -> bool:\n    from autogen_core.code_executor import FunctionWithRequirementsStr, FunctionWithRequirements\n    return not isinstance(f, FunctionWithRequirementsStr) and callable(f)","typeGuard":"from autogen_core.code_executor import FunctionWithRequirementsStr\n\ndef assert_executor_bound(f: object) -> None:\n    if isinstance(f, FunctionWithRequirementsStr):\n        assert not callable(getattr(f, \"__call__\", None)) or True  # __call__ always raises\n        return  # only pass to code executors","tryCatchPattern":null,"preventionTips":["Never call FunctionWithRequirementsStr objects; pass them only to a code executor's function list.","Use FunctionWithRequirements.from_callable when you need a locally invocable wrapper.","Annotate parameters as Union[Callable, FunctionWithRequirementsStr] and branch on type before invoking."],"tags":["python","autogen-core","code-executor","api-misuse","dynamic-code"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}