{"record":{"id":"dc6cc1b7209f2032","repo":"huggingface/smolagents","slug":"no-code-cells-found-in-ipython-session","errorCode":null,"errorMessage":"No code cells found in IPython session","messagePattern":"No code cells found in IPython session","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/smolagents/utils.py","lineNumber":415,"sourceCode":"        raise TypeError(f\"Expected class or callable, got {type(obj)}\")\n\n    inspect_error = None\n    try:\n        # Handle dynamically created classes\n        source = getattr(obj, \"__source__\", None) or inspect.getsource(obj)\n        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\")","sourceCodeStart":397,"sourceCodeEnd":433,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/utils.py#L397-L433","documentation":"The IPython fallback in get_source found a shell, but shell.user_ns['In'] joined and stripped is empty — there are no executed input cells to search for the object's definition. This aborts AST scanning of notebook history.","triggerScenarios":"A freshly started IPython kernel (only the auto 'In [1]' empty history) where code calls get_source on an object before any defining cell has run in that kernel.","commonSituations":"Objects imported from modules but inspect failing for another reason, then falling through to an empty notebook history; kernels restarted between definition and serialization.","solutions":["Define the class/tool in a notebook cell and execute it in the same kernel before calling serialization","Prefer defining tools in importable modules so the inspect path succeeds","Set obj.__source__ explicitly for dynamic objects"],"exampleFix":"# before\n# fresh kernel, tool imported from elsewhere with broken inspect info\nagent.to_dict()  # ValueError\n\n# after\n# run in a cell first:\nclass MyTool(Tool):\n    ...\n# then serialize","handlingStrategy":"fallback","validationCode":"def ipython_has_history() -> bool:\n    try:\n        import IPython\n        shell = IPython.get_ipython()\n        return bool(shell and '\\n'.join(shell.user_ns.get('In', [])).strip())\n    except Exception:\n        return False","typeGuard":null,"tryCatchPattern":"try:\n    src = get_source(obj)\nexcept ValueError as e:\n    if 'No code cells' in str(e):\n        src = getattr(obj, '__source__', None)  # or define in a module instead","preventionTips":["Execute the defining cell in the active kernel before serializing","Keep tool definitions in modules, not transient cells"],"tags":["smolagents","serialization","ipython"],"backgroundTag":"source-code-not-found","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}