{"record":{"id":"e83894b94383edea","repo":"langchain-ai/langchain","slug":"file-is-not-open-use-filecallbackhandler-as-a-con","errorCode":null,"errorMessage":"File is not open. Use FileCallbackHandler as a context manager.","messagePattern":"File is not open\\. Use FileCallbackHandler as a context manager\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/callbacks/file.py","lineNumber":159,"sourceCode":"            RuntimeError: If the file is closed or not available.\n\n        \"\"\"\n        global _GLOBAL_DEPRECATION_WARNED  # noqa: PLW0603\n        if not self._file_opened_in_context and not _GLOBAL_DEPRECATION_WARNED:\n            warn_deprecated(\n                since=\"0.3.67\",\n                pending=True,\n                message=(\n                    \"Using FileCallbackHandler without a context manager is \"\n                    \"deprecated. Use 'with FileCallbackHandler(...) as \"\n                    \"handler:' instead.\"\n                ),\n            )\n            _GLOBAL_DEPRECATION_WARNED = True\n\n        if not hasattr(self, \"file\") or self.file is None or self.file.closed:\n            msg = \"File is not open. Use FileCallbackHandler as a context manager.\"\n            raise RuntimeError(msg)\n\n        print_text(text, file=self.file, color=color, end=end)\n\n    @override\n    def on_chain_start(\n        self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any\n    ) -> None:\n        \"\"\"Print that we are entering a chain.\n\n        Args:\n            serialized: The serialized chain information.\n            inputs: The inputs to the chain.\n            **kwargs: Additional keyword arguments that may contain `'name'`.\n\n        \"\"\"\n        name = (\n            kwargs.get(\"name\")\n            or serialized.get(\"name\", serialized.get(\"id\", [\"<unknown>\"])[-1])","sourceCodeStart":141,"sourceCodeEnd":177,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/callbacks/file.py#L141-L177","documentation":"`FileCallbackHandler.on_text` (langchain_core/callbacks/file.py) raises `RuntimeError('File is not open...')` when the handler's underlying file is missing or closed — i.e. the handler was used without its context manager, so `__enter__` never opened `self.file`. The check fires before every `print_text` call.","triggerScenarios":"Creating `FileCallbackHandler(file_path=...)` and passing it to a chain/agent without wrapping it in `with`, then any callback event that prints text triggers the error; also using the same handler instance after the `with` block has exited and closed the file.","commonSituations":"Migrating old code that constructed the handler directly; registering the handler globally (e.g. via `callbacks=[handler]`) while forgetting the `with` statement; reusing a handler across sessions after file close. The deprecation warning at the top of the region flags exactly this pattern.","solutions":["Use the handler as a context manager: `with FileCallbackHandler(path) as handler: chain.invoke(..., config={'callbacks': [handler]})`","Create a fresh handler instance per run/session instead of reusing one after its `with` block exited","Ensure the `with` block encloses every invoke/agent run that references the handler","Suppress lint pressure to inline the constructor: keep the `with` even when the body is just the invoke call"],"exampleFix":"# before\nhandler = FileCallbackHandler(file_path=\"log.txt\")\nchain.invoke(inputs, config={\"callbacks\": [handler]})\n\n# after\nwith FileCallbackHandler(file_path=\"log.txt\") as handler:\n    chain.invoke(inputs, config={\"callbacks\": [handler]})","handlingStrategy":"validation","validationCode":"def handler_is_usable(handler) -> bool:\n    return getattr(getattr(handler, 'file', None), 'closed', True) is False\n\n# prefer structural prevention: always use `with`","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always construct FileCallbackHandler inside a `with` statement in the same expression scope as the invoke call","Create a new handler per run; never reuse after the context exits","Treat the preceding deprecation warning as the real signal to fix usage"],"tags":["callbacks","file-io","context-manager","deprecation"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}