{"record":{"id":"a6048a9f0a5490ab","repo":"huggingface/smolagents","slug":"could-not-find-source-code-for-obj-name-in-i","errorCode":null,"errorMessage":"Could not find source code for {obj.__name__} in IPython history","messagePattern":"Could not find source code for (.+?) in IPython history","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/smolagents/utils.py","lineNumber":421,"sourceCode":"        return dedent(source).strip()\n    except OSError as e:\n        # let's keep track of the exception to raise it if all further methods fail\n        inspect_error = e\n    try:\n        import IPython\n\n        shell = IPython.get_ipython()\n        if not shell:\n            raise ImportError(\"No active IPython shell found\")\n        all_cells = \"\\n\".join(shell.user_ns.get(\"In\", [])).strip()\n        if not all_cells:\n            raise ValueError(\"No code cells found in IPython session\")\n\n        tree = ast.parse(all_cells)\n        for node in ast.walk(tree):\n            if isinstance(node, (ast.ClassDef, ast.FunctionDef)) and node.name == obj.__name__:\n                return dedent(\"\\n\".join(all_cells.split(\"\\n\")[node.lineno - 1 : node.end_lineno])).strip()\n        raise ValueError(f\"Could not find source code for {obj.__name__} in IPython history\")\n    except ImportError:\n        # IPython is not available, let's just raise the original inspect error\n        raise inspect_error\n    except ValueError as e:\n        # IPython is available but we couldn't find the source code, let's raise the error\n        raise e from inspect_error\n\n\ndef encode_image_base64(image):\n    buffered = BytesIO()\n    image.save(buffered, format=\"PNG\")\n    return base64.b64encode(buffered.getvalue()).decode(\"utf-8\")\n\n\ndef make_image_url(base64_image):\n    return f\"data:image/png;base64,{base64_image}\"\n\n","sourceCodeStart":403,"sourceCodeEnd":439,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/utils.py#L403-L439","documentation":"The IPython fallback parsed all notebook cells but no top-level ast.ClassDef/FunctionDef node matches obj.__name__, so the source cannot be recovered. Note it only matches top-level definitions; nested or dynamically built objects will not be found.","triggerScenarios":"The object was created dynamically (type()/factory), renamed, defined inside another function/class, or its name-bearing cell was cleared before get_source ran.","commonSituations":"@tool-wrapped closures whose __name__ differs from any top-level def; tools built by loops generating classes; notebook cells deleted after execution.","solutions":["Define the tool/class as a top-level def/class in a cell (or module) and keep its name unchanged","Assign __source__ manually: MyTool.__source__ = 'class MyTool(Tool): ...'","Move the definition into an importable .py file"],"exampleFix":"# before\nMyTool = type('MyTool', (Tool,), {...})  # never in history\n\n# after\nclass MyTool(Tool):\n    def forward(self, ...): ...","handlingStrategy":"fallback","validationCode":"def object_in_ipython_history(obj) -> bool:\n    import ast, IPython\n    shell = IPython.get_ipython()\n    if not shell:\n        return False\n    cells = '\\n'.join(shell.user_ns.get('In', [])).strip()\n    try:\n        return any(\n            isinstance(n, (ast.ClassDef, ast.FunctionDef)) and n.name == obj.__name__\n            for n in ast.walk(ast.parse(cells))\n        )\n    except SyntaxError:\n        return False","typeGuard":null,"tryCatchPattern":"try:\n    src = get_source(obj)\nexcept ValueError as e:\n    if 'Could not find source code' in str(e):\n        src = getattr(obj, '__source__', None) or f'# source unavailable for {obj.__name__}'","preventionTips":["Define tools as top-level class/def with stable names","Set __source__ on factory-generated tools","Avoid renaming or deleting defining cells before serialization"],"tags":["smolagents","serialization","ipython","dynamic-objects"],"backgroundTag":"source-code-not-found","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}