{"record":{"id":"aaa75d342012cf29","repo":"langchain-ai/deepagents","slug":"statebackend-must-be-used-inside-a-langgraph-graph","errorCode":null,"errorMessage":"StateBackend must be used inside a LangGraph graph execution (e.g. via create_deep_agent). It cannot read or write state outside of a graph context. To pre-populate files, pass them on invoke: agent.invoke({\"messages\": [...], \"files\": {...}})","messagePattern":"StateBackend must be used inside a LangGraph graph execution \\(e\\.g\\. via create_deep_agent\\)\\. It cannot read or write state outside of a graph context\\. To pre-populate files, pass them on invoke: agent\\.invoke\\((.+?)\\}\\)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"libs/deepagents/deepagents/backends/state.py","lineNumber":68,"sourceCode":"    def __init__(self) -> None:\n        \"\"\"Initialize StateBackend.\"\"\"\n\n    # ------------------------------------------------------------------\n    # Internal helpers for reading / writing state via config keys\n    # ------------------------------------------------------------------\n\n    def _get_config(self) -> RunnableConfig:\n        \"\"\"Return the current LangGraph config, with a clear error if missing.\"\"\"\n        try:\n            config = get_config()\n        except RuntimeError:\n            msg = (\n                \"StateBackend must be used inside a LangGraph graph execution \"\n                \"(e.g. via create_deep_agent). It cannot read or write state \"\n                \"outside of a graph context. To pre-populate files, pass them \"\n                'on invoke: agent.invoke({\"messages\": [...], \"files\": {...}})'\n            )\n            raise RuntimeError(msg) from None\n        configurable = config.get(\"configurable\", {})\n        if CONFIG_KEY_READ not in configurable:\n            msg = (\n                \"StateBackend requires CONFIG_KEY_READ / CONFIG_KEY_SEND in \"\n                \"the LangGraph config. Make sure the backend is used inside \"\n                \"a graph node or tool, not called directly. To pre-populate \"\n                \"files, pass them on invoke: \"\n                'agent.invoke({\"messages\": [...], \"files\": {...}})'\n            )\n            raise RuntimeError(msg)\n        return config\n\n    def _read_files(self) -> dict[str, Any]:\n        \"\"\"Read the current `files` channel via Pregel internals.\n\n        Uses `CONFIG_KEY_READ` to read state directly — this lets us\n        initialize StateBackend once and fetch state on demand from any\n        graph context (tools, middleware nodes, etc.).","sourceCodeStart":50,"sourceCodeEnd":86,"githubUrl":"https://github.com/langchain-ai/deepagents/blob/a1af029e6e73cb17c36bff823d227747b28e91e1/libs/deepagents/deepagents/backends/state.py#L50-L86","documentation":"`StateBackend` stores agent files in the LangGraph graph state, so it can only operate while a graph node is executing with a proper `RunnableConfig` in context. `_get_config` raises this `RuntimeError` when it cannot find a config (no graph execution context), meaning `_read_files` or `_send_files_update` was called outside a graph run. The message explains the remedy: pre-populate files on `invoke`, not by calling the backend directly.","triggerScenarios":"Instantiating `StateBackend` and calling `read`/`write`/`delete`/`ls` (which reach `_get_config` via `_read_files`/`_send_files_update`) directly in application code, outside `create_deep_agent(...).invoke(...)`; calling it from a plain script, test, or thread without a LangGraph runtime context.","commonSituations":"Trying to inspect or seed files before invoking the agent; unit-testing the backend without a fake graph config; background threads/callbacks that outlive the graph node and lose the config context.","solutions":["Only use StateBackend inside graph execution — build the agent with `create_deep_agent` and call `agent.invoke({'messages': [...], 'files': {...}})` to pre-populate files","In tests, use the project's fake config fixtures that inject CONFIG_KEY_READ/CONFIG_KEY_SEND (see error 616) or use a standalone backend (FilesystemBackend/StoreBackend) outside graphs","If you need direct file access, switch to a backend that doesn't depend on graph state","Ensure async/background work runs within the graph node's context, not after it returns"],"exampleFix":"// before\nbackend = StateBackend()\nbackend.write('/a.txt', 'hello')  # RuntimeError\n\n// after\nagent = create_deep_agent(backend=StateBackend(), tools=[...])\nagent.invoke({'messages': [{'role': 'user', 'content': 'hi'}], 'files': {'/a.txt': 'hello'}})","handlingStrategy":"try-catch","validationCode":"def state_backend_usable(config) -> bool:\n    return config is not None and CONFIG_KEY_READ in config.get('configurable', {}) and CONFIG_KEY_SEND in config.get('configurable', {})","typeGuard":null,"tryCatchPattern":"try:\n    backend.write('/a.txt', 'x')\nexcept RuntimeError as e:\n    if 'graph execution' in str(e):\n        agent.invoke({'messages': [...], 'files': {'/a.txt': 'x'}})  # seed via invoke instead\n    else:\n        raise","preventionTips":["Never call StateBackend from application code; route all file access through agent tools","Seed files with `agent.invoke({'messages': [...], 'files': {...}})`","Use FilesystemBackend or StoreBackend when you need file I/O outside a graph run","Keep background/async work inside the graph node so the config context stays available"],"tags":["python","langgraph","state-backend","misuse","runtime-error"],"backgroundTag":"api-called-outside-context","analyzedSha":"a1af029e6e73cb17c36bff823d227747b28e91e1","analyzedAt":"2026-08-29T11:43:24.718Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}