{"record":{"id":"05b331d9bc67f3ff","repo":"langchain-ai/deepagents","slug":"agent-initialization-failed","errorCode":null,"errorMessage":"Agent initialization failed","messagePattern":"Agent initialization failed","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"libs/acp/deepagents_acp/server.py","lineNumber":966,"sourceCode":"            TextContentBlock\n            | ImageContentBlock\n            | AudioContentBlock\n            | ResourceContentBlock\n            | EmbeddedResourceContentBlock\n        ],\n        session_id: str,\n        message_id: str | None = None,  # noqa: ARG002  # ACP protocol interface parameter\n        **kwargs: Any,  # noqa: ARG002  # ACP protocol interface parameter\n    ) -> PromptResponse:\n        \"\"\"Process a user prompt and stream the agent response.\"\"\"\n        if self._agent is None or (\n            self._agent_session_id is not None and self._agent_session_id != session_id\n        ):\n            self._reset_agent(session_id)\n\n        if self._agent is None:\n            msg = \"Agent initialization failed\"\n            raise RuntimeError(msg)\n\n        if getattr(self._agent, \"checkpointer\", None) is None:\n            self._agent.checkpointer = MemorySaver()  # Guarded by getattr check above\n        agent = self._agent\n\n        # Reset cancellation flag for new prompt\n        self._cancelled = False\n\n        # Convert ACP content blocks to LangChain multimodal content format\n        content_blocks = []\n\n        for block in prompt:\n            if isinstance(block, TextContentBlock):\n                content_blocks.extend(convert_text_block_to_content_blocks(block))\n            elif isinstance(block, ImageContentBlock):\n                content_blocks.extend(convert_image_block_to_content_blocks(block))\n            elif isinstance(block, AudioContentBlock):\n                content_blocks.extend(convert_audio_block_to_content_blocks(block))","sourceCodeStart":948,"sourceCodeEnd":984,"githubUrl":"https://github.com/langchain-ai/deepagents/blob/a1af029e6e73cb17c36bff823d227747b28e91e1/libs/acp/deepagents_acp/server.py#L948-L984","documentation":"`ServerConnection.prompt` raises this RuntimeError when, after attempting to reset/create the agent for the session, `self._agent` is still None. The agent is produced by the user-supplied `_agent_factory`; a factory that returns None (or a reset that never assigns) leaves the server unable to serve any prompt. It is a defensive guard, so hitting it means the configured agent factory is broken or incompatible.","triggerScenarios":"Calling `prompt()` on an ACP server connection where `_reset_agent(session_id)` (libs/acp/deepagents_acp/server.py:962) left `self._agent` as None — typically because the `agent_factory` callable returned None instead of a LangGraph/DeepAgent instance, or the factory was misconfigured so no agent was ever constructed.","commonSituations":"Passing `lambda ctx: None` or a factory with a broken return path when constructing the ACP server; a factory that swallows exceptions and returns None; using an agent object type the reset logic doesn't handle so re-initialization silently fails; reusing a session id after `_forget_session` cleared `_agent` and the factory no longer rebuilds it.","solutions":["Inspect your `agent_factory` and ensure it always returns a compiled agent (never None) for every `AgentSessionContext`","Wrap factory internals so exceptions propagate instead of being caught and falling through to a None return","Verify the object passed as the factory is actually callable returning an agent, not the agent itself (a bare CompiledStateGraph is accepted directly)","Reproduce with a minimal script: construct the server with your factory, call `_reset_agent('test')`, and print the returned agent to confirm it is non-None"],"exampleFix":"# before\nserver = ACPServerConnection(agent_factory=lambda ctx: None)\n# after\ndef make_agent(ctx: AgentSessionContext):\n    return create_deep_agent(model=my_model, tools=[...])\nserver = ACPServerConnection(agent_factory=make_agent)","handlingStrategy":"validation","validationCode":"agent = agent_factory(ctx)\nif agent is None:\n    raise RuntimeError(\"agent_factory must return an agent, got None\")\nassert callable(getattr(agent, \"ainvoke\", None)) or isinstance(agent, CompiledStateGraph)","typeGuard":"def is_agent(obj: object) -> bool:\n    return obj is not None and (callable(getattr(obj, \"astream\", None)) or hasattr(obj, \"ainvoke\"))","tryCatchPattern":"try:\n    resp = await conn.prompt(blocks, session_id)\nexcept RuntimeError as exc:\n    if \"Agent initialization failed\" in str(exc):\n        logging.exception(\"ACP agent factory returned no agent; check agent_factory\")\n    raise","preventionTips":["Always return a real agent from agent_factory — never None on any code path","Test the factory in isolation: assert it returns a non-None agent for a representative AgentSessionContext","Let exceptions from factory internals propagate instead of swallowing them","Reuse the factory example from the ACP docs/server tests rather than hand-rolling one"],"tags":["acp","agent-initialization","factory","runtime-error"],"backgroundTag":"agent-factory-returned-null","analyzedSha":"a1af029e6e73cb17c36bff823d227747b28e91e1","analyzedAt":"2026-08-29T11:43:24.718Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}