langchain-ai/deepagents · error · ExtensionError

Could not construct middleware {middleware!r}: {exc}

Error message

Could not construct middleware {middleware!r}: {exc}

What it means

`register_middleware` accepts either an `AgentMiddleware` class or instance. A class is instantiated with no arguments; if that constructor call (or any construction path) raises, the error is wrapped in `ExtensionError` with the middleware repr and original message. This surfaces constructor problems (missing required args, import failures, bad config) at registration time with provenance.

Source

Thrown at libs/code/deepagents_code/extensions/api.py:112

        """Install LangChain middleware on the agent.

        A class is instantiated without arguments. Pass an instance when
        construction requires configuration.

        Args:
            middleware: Middleware class or instance.

        Raises:
            ExtensionError: If `middleware` is invalid or cannot be constructed.
        """
        self._ensure_active()
        from langchain.agents.middleware.types import AgentMiddleware

        try:
            instance = middleware() if isinstance(middleware, type) else middleware
        except Exception as exc:
            msg = f"Could not construct middleware {middleware!r}: {exc}"
            raise ExtensionError(msg) from exc
        if not isinstance(instance, AgentMiddleware):
            kind = type(instance).__name__
            msg = f"Registered middleware must be an AgentMiddleware, got {kind}"
            raise ExtensionError(msg)
        self._registry.add_middleware(instance, self._source)

    def register_tool(self, tool: BaseTool | Callable[..., Any]) -> None:
        """Expose an LLM-callable tool.

        Plain callables are converted using LangChain's tool schema inference.

        Args:
            tool: Tool instance or plain callable.

        Raises:
            ExtensionError: If a callable cannot be converted into a tool.
        """
        self._ensure_active()

View on GitHub (pinned to a1af029e6e)

Solutions

  1. Pass a configured instance instead of a bare class: `api.register_middleware(MyMiddleware(required_arg=...))`.
  2. Fix the underlying exception shown after the colon (missing arg, missing dependency, bad config).
  3. Ensure a no-arg constructor exists if you intend to register the class itself.
  4. Wrap construction in a try/except in the extension factory to log and degrade gracefully.

Example fix

# before
api.register_middleware(RetryMiddleware)  # __init__ requires max_retries

# after
api.register_middleware(RetryMiddleware(max_retries=3))
Defensive patterns

Strategy: try-catch

Validate before calling

def middleware_instantiates(mw) -> bool:
    if isinstance(mw, type):
        try:
            mw()
            return True
        except Exception:
            return False
    return True  # already an instance

Type guard

def is_instantiable_middleware_class(mw) -> bool:
    return isinstance(mw, type) and issubclass(mw, AgentMiddleware)

Try / catch

try:
    api.register_middleware(MyMiddleware)
except ExtensionError as exc:
    logger.error("middleware registration failed: %s", exc)
    api.register_middleware(MyMiddleware(required=config_value))  # fallback: pass config

Prevention

When it happens

Trigger: Registering a middleware class whose `__init__` requires arguments; a class whose `__init__` raises (network init, missing dependency, invalid config); passing a factory callable that is not a class but truthy as a type.

Common situations: Third-party middleware requiring a constructor parameter in a newer version; a middleware importing an optional dependency that is not installed; config-driven middleware built with required fields left unset.

Related errors


AI-assisted analysis of langchain-ai/deepagents@a1af029e6e (2026-08-29). Data as JSON: /api/errors/d9c37ce8223049fc. Report an issue: GitHub.