{"record":{"id":"16b9217648b7fe9b","repo":"huggingface/smolagents","slug":"no-active-ipython-shell-found","errorCode":null,"errorMessage":"No active IPython shell found","messagePattern":"No active IPython shell found","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"src/smolagents/utils.py","lineNumber":412,"sourceCode":"        TODO: handle Python standard REPL\n    \"\"\"\n    if not (isinstance(obj, type) or callable(obj)):\n        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):","sourceCodeStart":394,"sourceCodeEnd":430,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/utils.py#L394-L430","documentation":"When inspect.getsource fails (e.g. object defined in an interactive session), get_source falls back to searching IPython history. If IPython imports but IPython.get_ipython() returns None — no live shell in this process — this ImportError is raised, then re-raised as the original inspect error by the except ImportError handler.","triggerScenarios":"Serializing a tool/class that was defined in a REPL/notebook-in-another-process: inspect has no source file, and get_source runs where no IPython shell exists (plain script, worker process).","commonSituations":"Using @tool in a subprocess or detached worker after pickling from a notebook; reloading modules so inspect loses file mappings; objects created via exec without __source__.","solutions":["Define the tool in a real .py module so inspect.getsource works","Attach a __source__ attribute to dynamically created tools","Run the serialization in the same process/session where the object was defined","When in notebooks, run the defining cell in the same kernel before serializing"],"exampleFix":"# before\n# tool defined with exec in a worker -> get_source fails\n\n# after\n# my_tools.py\ndef search(query: str) -> str:\n    ...\nsearch_tool = tool(search)","handlingStrategy":"fallback","validationCode":"import inspect\ndef has_recoverable_source(obj) -> bool:\n    try:\n        inspect.getsource(obj)\n        return True\n    except (OSError, TypeError):\n        return bool(getattr(obj, '__source__', None)) or _ipython_available_with_history()","typeGuard":"def can_get_source(obj) -> bool:\n    import inspect\n    try:\n        inspect.getsource(obj)\n        return True\n    except Exception:\n        return getattr(obj, '__source__', None) is not None","tryCatchPattern":"try:\n    src = get_source(obj)\nexcept Exception as e:\n    if 'No active IPython' in str(e) or isinstance(e, OSError):\n        src = getattr(obj, '__source__', None) or fallback_repr(obj)","preventionTips":["Define tools in importable .py modules","Attach __source__ to dynamically generated tools","Serialize in the same process where objects were defined"],"tags":["smolagents","serialization","ipython","inspect"],"backgroundTag":"source-code-not-found","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}