libs/langchain_v1/langchain/agents/middleware/types.py PYTHON 2,204 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 2,204.
1"""Types for middleware and agents."""23from __future__ import annotations45import warnings6from collections.abc import Awaitable, Callable, Sequence7from dataclasses import dataclass, field, replace8from inspect import iscoroutinefunction9from typing import (10    TYPE_CHECKING,11    Annotated,12    Any,13    Generic,14    Literal,15    NotRequired,16    Required,17    cast,18    overload,19)2021# Needed as top level import for Pydantic schema generation on AgentState22from langchain_core.messages import (23    AIMessage,24    AnyMessage,25    BaseMessage,26    SystemMessage,27    ToolMessage,28)29from langgraph.channels.ephemeral_value import EphemeralValue30from langgraph.graph.message import add_messages31from langgraph.prebuilt.tool_node import ToolCallRequest, ToolCallWrapper32from langgraph.runtime import Runtime33from langgraph.types import Command, TracePolicy, omit_payload34from langgraph.typing import ContextT35from typing_extensions import TypedDict, TypeVar, Unpack3637if TYPE_CHECKING:38    from langchain_core.language_models.chat_models import BaseChatModel39    from langchain_core.tools import BaseTool40    from langgraph.stream._mux import TransformerFactory4142    from langchain.agents.structured_output import ResponseFormat4344__all__ = [45    "AgentMiddleware",46    "AgentState",47    "ContextT",48    "ExtendedModelResponse",49    "InputAgentState",50    "ModelCallResult",51    "ModelRequest",52    "ModelResponse",53    "OmitFromSchema",54    "OutputAgentState",55    "ResponseT",56    "StateT_co",57    "ToolCallRequest",58    "ToolCallWrapper",59    "TracePolicy",60    "after_agent",61    "after_model",62    "before_agent",63    "before_model",64    "dynamic_prompt",65    "hook_config",66    "omit_payload",67    "wrap_tool_call",68]6970JumpTo = Literal["tools", "model", "end"]71"""Destination to jump to when a middleware node returns."""7273ResponseT = TypeVar("ResponseT", default=Any)747576class _ModelRequestOverrides(TypedDict, total=False):77    """Possible overrides for `ModelRequest.override()` method."""7879    model: BaseChatModel80    system_message: SystemMessage | None81    messages: list[AnyMessage]82    tool_choice: Any | None83    tools: list[BaseTool | dict[str, Any]]84    response_format: ResponseFormat[Any] | None85    model_settings: dict[str, Any]86    state: AgentState[Any]878889@dataclass(init=False)90class ModelRequest(Generic[ContextT]):91    """Model request information for the agent.9293    Type Parameters:94        ContextT: The type of the runtime context.9596            Defaults to `None` if not specified.97    """9899    model: BaseChatModel100    messages: list[AnyMessage]  # excluding system message101    system_message: SystemMessage | None102    tool_choice: Any | None103    tools: list[BaseTool | dict[str, Any]]104    response_format: ResponseFormat[Any] | None105    state: AgentState[Any]106    runtime: Runtime[ContextT]107    model_settings: dict[str, Any] = field(default_factory=dict)108109    def __init__(110        self,111        *,112        model: BaseChatModel,113        messages: list[AnyMessage],114        system_message: SystemMessage | None = None,115        system_prompt: str | None = None,116        tool_choice: Any | None = None,117        tools: list[BaseTool | dict[str, Any]] | None = None,118        response_format: ResponseFormat[Any] | None = None,119        state: AgentState[Any] | None = None,120        runtime: Runtime[ContextT] | None = None,121        model_settings: dict[str, Any] | None = None,122    ) -> None:123        """Initialize `ModelRequest` with backward compatibility for `system_prompt`.124125        Args:126            model: The chat model to use.127            messages: List of messages (excluding system prompt).128            tool_choice: Tool choice configuration.129            tools: List of available tools.130            response_format: Response format specification.131            state: Agent state.132            runtime: Runtime context.133            model_settings: Additional model settings.134            system_message: System message instance (preferred).135            system_prompt: System prompt string (deprecated, converted to `SystemMessage`).136137        Raises:138            ValueError: If both `system_prompt` and `system_message` are provided.139        """140        # Handle system_prompt/system_message conversion and validation141        if system_prompt is not None and system_message is not None:142            msg = "Cannot specify both system_prompt and system_message"143            raise ValueError(msg)144145        if system_prompt is not None:146            system_message = SystemMessage(content=system_prompt)147148        object.__setattr__(self, "model", model)149        object.__setattr__(self, "messages", messages)150        object.__setattr__(self, "system_message", system_message)151        object.__setattr__(self, "tool_choice", tool_choice)152        object.__setattr__(self, "tools", tools if tools is not None else [])153        object.__setattr__(self, "response_format", response_format)154        object.__setattr__(self, "state", state if state is not None else {"messages": []})155        object.__setattr__(self, "runtime", runtime)156        object.__setattr__(157            self, "model_settings", model_settings if model_settings is not None else {}158        )159160    @property161    def system_prompt(self) -> str | None:162        """Get system prompt text from system_message.163164        Returns:165            The content of the system message if present, otherwise `None`.166        """167        if self.system_message is None:168            return None169        return self.system_message.text170171    def __setattr__(self, name: str, value: Any) -> None:172        """Set an attribute with a deprecation warning.173174        Direct attribute assignment on `ModelRequest` is deprecated. Use the175        `override()` method instead to create a new request with modified attributes.176177        Args:178            name: Attribute name.179            value: Attribute value.180        """181        # Special handling for system_prompt - convert to system_message182        if name == "system_prompt":183            warnings.warn(184                "Direct attribute assignment to ModelRequest.system_prompt is deprecated. "185                "Use request.override(system_message=SystemMessage(...)) instead to create "186                "a new request with the modified system message.",187                DeprecationWarning,188                stacklevel=2,189            )190            if value is None:191                object.__setattr__(self, "system_message", None)192            else:193                object.__setattr__(self, "system_message", SystemMessage(content=value))194            return195196        warnings.warn(197            f"Direct attribute assignment to ModelRequest.{name} is deprecated. "198            f"Use request.override({name}=...) instead to create a new request "199            f"with the modified attribute.",200            DeprecationWarning,201            stacklevel=2,202        )203        object.__setattr__(self, name, value)204205    def override(self, **overrides: Unpack[_ModelRequestOverrides]) -> ModelRequest[ContextT]:206        """Replace the request with a new request with the given overrides.207208        Returns a new `ModelRequest` instance with the specified attributes replaced.209210        This follows an immutable pattern, leaving the original request unchanged.211212        Args:213            **overrides: Keyword arguments for attributes to override.214215                Supported keys:216217                - `model`: `BaseChatModel` instance218                - `system_prompt`: deprecated, use `system_message` instead219                - `system_message`: `SystemMessage` instance220                - `messages`: `list` of messages221                - `tool_choice`: Tool choice configuration222                - `tools`: `list` of available tools223                - `response_format`: Response format specification224                - `model_settings`: Additional model settings225                - `state`: Agent state dictionary226227        Returns:228            New `ModelRequest` instance with specified overrides applied.229230        Examples:231            !!! example "Create a new request with different model"232233                ```python234                new_request = request.override(model=different_model)235                ```236237            !!! example "Override system message (preferred)"238239                ```python240                from langchain_core.messages import SystemMessage241242                new_request = request.override(243                    system_message=SystemMessage(content="New instructions")244                )245                ```246247            !!! example "Override multiple attributes"248249                ```python250                new_request = request.override(251                    model=ChatOpenAI(model="gpt-5.5"),252                    system_message=SystemMessage(content="New instructions"),253                )254                ```255256        Raises:257            ValueError: If both `system_prompt` and `system_message` are provided.258        """259        # Handle system_prompt/system_message conversion260        if "system_prompt" in overrides and "system_message" in overrides:261            msg = "Cannot specify both system_prompt and system_message"262            raise ValueError(msg)263264        if "system_prompt" in overrides:265            system_prompt = cast("str | None", overrides.pop("system_prompt"))  # type: ignore[typeddict-item]266            if system_prompt is None:267                overrides["system_message"] = None268            else:269                overrides["system_message"] = SystemMessage(content=system_prompt)270271        return replace(self, **overrides)272273274@dataclass275class ModelResponse(Generic[ResponseT]):276    """Response from model execution including messages and optional structured output.277278    The result will usually contain a single `AIMessage`, but may include an additional279    `ToolMessage` if the model used a tool for structured output.280281    Type Parameters:282        ResponseT: The type of the structured response. Defaults to `Any` if not specified.283    """284285    result: list[BaseMessage]286    """List of messages from model execution."""287288    structured_response: ResponseT | None = None289    """Parsed structured output if `response_format` was specified, `None` otherwise."""290291292@dataclass293class ExtendedModelResponse(Generic[ResponseT]):294    """Model response with an optional 'Command' from 'wrap_model_call' middleware.295296    Use this to return a 'Command' alongside the model response from a297    'wrap_model_call' handler. The command is applied as an additional state298    update after the model node completes, using the graph's reducers (e.g.299    'add_messages' for the 'messages' key).300301    Because each 'Command' is applied through the reducer, messages in the302    command are **added alongside** the model response messages rather than303    replacing them. For non-reducer state fields, later commands overwrite304    earlier ones (outermost middleware wins over inner).305306    Type Parameters:307        ResponseT: The type of the structured response. Defaults to 'Any' if not specified.308    """309310    model_response: ModelResponse[ResponseT]311    """The underlying model response."""312313    command: Command[Any] | None = None314    """Optional command to apply as an additional state update."""315316317ModelCallResult = ModelResponse[ResponseT] | AIMessage | ExtendedModelResponse[ResponseT]318"""Return type for model call handlers.319320Middleware can return either:321322- `ModelResponse`: Full response with messages and optional structured output323- `AIMessage`: Simplified return for simple use cases324- `ExtendedModelResponse`: Response with an optional `Command` for additional state updates325    `goto`, `resume`, and `graph` are not yet supported on these commands.326    A `NotImplementedError` will be raised if you try to use them.327"""328329330@dataclass331class OmitFromSchema:332    """Annotation used to mark state attributes as omitted from input or output schemas."""333334    input: bool = True335    """Whether to omit the attribute from the input schema."""336337    output: bool = True338    """Whether to omit the attribute from the output schema."""339340341OmitFromInput = OmitFromSchema(input=True, output=False)342"""Annotation used to mark state attributes as omitted from input schema."""343344OmitFromOutput = OmitFromSchema(input=False, output=True)345"""Annotation used to mark state attributes as omitted from output schema."""346347PrivateStateAttr = OmitFromSchema(input=True, output=True)348"""Annotation used to mark state attributes as purely internal for a given middleware."""349350351class AgentState(TypedDict, Generic[ResponseT]):352    """State schema for the agent."""353354    messages: Required[Annotated[list[AnyMessage], add_messages]]355    jump_to: NotRequired[Annotated[JumpTo | None, EphemeralValue, PrivateStateAttr]]356    structured_response: NotRequired[Annotated[ResponseT, OmitFromInput]]357358359class InputAgentState(TypedDict):360    """Input state schema for the agent."""361362    messages: Required[Annotated[list[AnyMessage | dict[str, Any]], add_messages]]363364365class OutputAgentState(TypedDict, Generic[ResponseT]):366    """Output state schema for the agent."""367368    messages: Required[Annotated[list[AnyMessage], add_messages]]369    structured_response: NotRequired[ResponseT]370371372# Deprecated aliases kept for backwards compatibility with external consumers that373# imported the previously private names. Remove in a future release.374_InputAgentState = InputAgentState375_OutputAgentState = OutputAgentState376377378StateT = TypeVar("StateT", bound=AgentState[Any], default=AgentState[Any])379StateT_co = TypeVar("StateT_co", bound=AgentState[Any], default=AgentState[Any], covariant=True)380StateT_contra = TypeVar("StateT_contra", bound=AgentState[Any], contravariant=True)381382383class _DefaultAgentState(AgentState[Any]):384    """AgentMiddleware default state."""385386387class AgentMiddleware(Generic[StateT, ContextT, ResponseT]):388    """Base middleware class for an agent.389390    Subclass this and implement any of the defined methods to customize agent behavior391    between steps in the main agent loop.392393    Type Parameters:394        StateT: The type of the agent state. Defaults to `AgentState[Any]`.395        ContextT: The type of the runtime context. Defaults to `None`.396        ResponseT: The type of the structured response. Defaults to `Any`.397    """398399    state_schema: type[StateT] = cast("type[StateT]", _DefaultAgentState)400    """The schema for state passed to the middleware nodes."""401402    tools: Sequence[BaseTool]403    """Additional tools registered by the middleware."""404405    trace_policy: TracePolicy | None = None406    """Optional trace policy for this middleware's hook spans (`wrap_model_call`/407    `wrap_tool_call` and the `before_*`/`after_*` node hooks).408409    By default (`None`), hook spans are traced normally. Set a `TracePolicy` to shape410    what they record -- e.g. `TracePolicy(process_inputs=omit_payload)` to drop the411    conversation `messages`/`state` payload while keeping the span and its timing.412    Messages are still captured on the inner model-call span.413    """414415    transformers: Sequence[TransformerFactory] = ()416    """Stream transformer factories registered by the middleware.417418    Each entry is a scope-aware factory invoked as `factory(scope)` so every419    invocation receives a fresh instance. Factories are merged with the420    `transformers` argument of [`create_agent`][langchain.agents.create_agent]421    at graph compile time, after the `ToolCallTransformer` and before any422    user-supplied entries.423    """424425    @property426    def name(self) -> str:427        """The name of the middleware instance.428429        Defaults to the class name, but can be overridden for custom naming.430        """431        return self.__class__.__name__432433    def before_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:434        """Logic to run before the agent execution starts.435436        Args:437            state: The current agent state.438            runtime: The runtime context.439440        Returns:441            Agent state updates to apply before agent execution.442        """443444    async def abefore_agent(445        self, state: StateT, runtime: Runtime[ContextT]446    ) -> dict[str, Any] | None:447        """Async logic to run before the agent execution starts.448449        Args:450            state: The current agent state.451            runtime: The runtime context.452453        Returns:454            Agent state updates to apply before agent execution.455        """456457    def before_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:458        """Logic to run before the model is called.459460        Args:461            state: The current agent state.462            runtime: The runtime context.463464        Returns:465            Agent state updates to apply before model call.466        """467468    async def abefore_model(469        self, state: StateT, runtime: Runtime[ContextT]470    ) -> dict[str, Any] | None:471        """Async logic to run before the model is called.472473        Args:474            state: The agent state.475            runtime: The runtime context.476477        Returns:478            Agent state updates to apply before model call.479        """480481    def after_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:482        """Logic to run after the model is called.483484        Args:485            state: The current agent state.486            runtime: The runtime context.487488        Returns:489            Agent state updates to apply after model call.490        """491492    async def aafter_model(493        self, state: StateT, runtime: Runtime[ContextT]494    ) -> dict[str, Any] | None:495        """Async logic to run after the model is called.496497        Args:498            state: The current agent state.499            runtime: The runtime context.500501        Returns:502            Agent state updates to apply after model call.503        """504505    def wrap_model_call(506        self,507        request: ModelRequest[ContextT],508        handler: Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]],509    ) -> ModelResponse[ResponseT] | AIMessage | ExtendedModelResponse[ResponseT]:510        """Intercept and control model execution via handler callback.511512        Async version is `awrap_model_call`513514        The handler callback executes the model request and returns a `ModelResponse`.515        Middleware can call the handler multiple times for retry logic, skip calling516        it to short-circuit, or modify the request/response. Multiple middleware517        compose with first in list as outermost layer.518519        Args:520            request: Model request to execute (includes state and runtime).521            handler: Callback that executes the model request and returns522                `ModelResponse`.523524                Call this to execute the model.525526                Can be called multiple times for retry logic.527528                Can skip calling it to short-circuit.529530        Returns:531            The model call result.532533        Examples:534            !!! example "Retry on error"535536                ```python537                def wrap_model_call(self, request, handler):538                    for attempt in range(3):539                        try:540                            return handler(request)541                        except Exception:542                            if attempt == 2:543                                raise544                ```545546            !!! example "Rewrite response"547548                ```python549                def wrap_model_call(self, request, handler):550                    response = handler(request)551                    ai_msg = response.result[0]552                    return ModelResponse(553                        result=[AIMessage(content=f"[{ai_msg.content}]")],554                        structured_response=response.structured_response,555                    )556                ```557558            !!! example "Error to fallback"559560                ```python561                def wrap_model_call(self, request, handler):562                    try:563                        return handler(request)564                    except Exception:565                        return ModelResponse(result=[AIMessage(content="Service unavailable")])566                ```567568            !!! example "Cache/short-circuit"569570                ```python571                def wrap_model_call(self, request, handler):572                    if cached := get_cache(request):573                        return cached  # Short-circuit with cached result574                    response = handler(request)575                    save_cache(request, response)576                    return response577                ```578579            !!! example "Simple `AIMessage` return (converted automatically)"580581                ```python582                def wrap_model_call(self, request, handler):583                    response = handler(request)584                    # Can return AIMessage directly for simple cases585                    return AIMessage(content="Simplified response")586                ```587        """588        msg = (589            "Synchronous implementation of wrap_model_call is not available. "590            "You are likely encountering this error because you defined only the async version "591            "(awrap_model_call) and invoked your agent in a synchronous context "592            "(e.g., using `stream()` or `invoke()`). "593            "To resolve this, either: "594            "(1) subclass AgentMiddleware and implement the synchronous wrap_model_call method, "595            "(2) use the @wrap_model_call decorator on a standalone sync function, or "596            "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."597        )598        raise NotImplementedError(msg)599600    async def awrap_model_call(601        self,602        request: ModelRequest[ContextT],603        handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],604    ) -> ModelResponse[ResponseT] | AIMessage | ExtendedModelResponse[ResponseT]:605        """Intercept and control async model execution via handler callback.606607        The handler callback executes the model request and returns a `ModelResponse`.608609        Middleware can call the handler multiple times for retry logic, skip calling610        it to short-circuit, or modify the request/response. Multiple middleware611        compose with first in list as outermost layer.612613        Args:614            request: Model request to execute (includes state and runtime).615            handler: Async callback that executes the model request and returns616                `ModelResponse`.617618                Call this to execute the model.619620                Can be called multiple times for retry logic.621622                Can skip calling it to short-circuit.623624        Returns:625            The model call result.626627        Examples:628            !!! example "Retry on error"629630                ```python631                async def awrap_model_call(self, request, handler):632                    for attempt in range(3):633                        try:634                            return await handler(request)635                        except Exception:636                            if attempt == 2:637                                raise638                ```639        """640        msg = (641            "Asynchronous implementation of awrap_model_call is not available. "642            "You are likely encountering this error because you defined only the sync version "643            "(wrap_model_call) and invoked your agent in an asynchronous context "644            "(e.g., using `astream()` or `ainvoke()`). "645            "To resolve this, either: "646            "(1) subclass AgentMiddleware and implement the asynchronous awrap_model_call method, "647            "(2) use the @wrap_model_call decorator on a standalone async function, or "648            "(3) invoke your agent synchronously using `stream()` or `invoke()`."649        )650        raise NotImplementedError(msg)651652    def after_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:653        """Logic to run after the agent execution completes.654655        Args:656            state: The current agent state.657            runtime: The runtime context.658659        Returns:660            Agent state updates to apply after agent execution.661        """662663    async def aafter_agent(664        self, state: StateT, runtime: Runtime[ContextT]665    ) -> dict[str, Any] | None:666        """Async logic to run after the agent execution completes.667668        Args:669            state: The current agent state.670            runtime: The runtime context.671672        Returns:673            Agent state updates to apply after agent execution.674        """675676    def wrap_tool_call(677        self,678        request: ToolCallRequest,679        handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],680    ) -> ToolMessage | Command[Any]:681        """Intercept tool execution for retries, monitoring, or modification.682683        Async version is `awrap_tool_call`684685        Multiple middleware compose automatically (first defined = outermost).686687        Exceptions propagate unless `handle_tool_errors` is configured on `ToolNode`.688689        Args:690            request: Tool call request with call `dict`, `BaseTool`, state, and runtime.691692                Access state via `request.state` and runtime via `request.runtime`.693            handler: `Callable` to execute the tool (can be called multiple times).694695        Returns:696            `ToolMessage` or `Command` (the final result).697698        The handler `Callable` can be invoked multiple times for retry logic.699700        Each call to handler is independent and stateless.701702        Examples:703            !!! example "Modify request before execution"704705                ```python706                def wrap_tool_call(self, request, handler):707                    modified_call = {708                        **request.tool_call,709                        "args": {710                            **request.tool_call["args"],711                            "value": request.tool_call["args"]["value"] * 2,712                        },713                    }714                    request = request.override(tool_call=modified_call)715                    return handler(request)716                ```717718            !!! example "Retry on error (call handler multiple times)"719720                ```python721                def wrap_tool_call(self, request, handler):722                    for attempt in range(3):723                        try:724                            result = handler(request)725                            if is_valid(result):726                                return result727                        except Exception:728                            if attempt == 2:729                                raise730                    return result731                ```732733            !!! example "Conditional retry based on response"734735                ```python736                def wrap_tool_call(self, request, handler):737                    for attempt in range(3):738                        result = handler(request)739                        if isinstance(result, ToolMessage) and result.status != "error":740                            return result741                        if attempt < 2:742                            continue743                        return result744                ```745        """746        msg = (747            "Synchronous implementation of wrap_tool_call is not available. "748            "You are likely encountering this error because you defined only the async version "749            "(awrap_tool_call) and invoked your agent in a synchronous context "750            "(e.g., using `stream()` or `invoke()`). "751            "To resolve this, either: "752            "(1) subclass AgentMiddleware and implement the synchronous wrap_tool_call method, "753            "(2) use the @wrap_tool_call decorator on a standalone sync function, or "754            "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."755        )756        raise NotImplementedError(msg)757758    async def awrap_tool_call(759        self,760        request: ToolCallRequest,761        handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],762    ) -> ToolMessage | Command[Any]:763        """Intercept and control async tool execution via handler callback.764765        The handler callback executes the tool call and returns a `ToolMessage` or766        `Command`. Middleware can call the handler multiple times for retry logic, skip767        calling it to short-circuit, or modify the request/response. Multiple middleware768        compose with first in list as outermost layer.769770        Args:771            request: Tool call request with call `dict`, `BaseTool`, state, and runtime.772773                Access state via `request.state` and runtime via `request.runtime`.774            handler: Async callable to execute the tool and returns `ToolMessage` or775                `Command`.776777                Call this to execute the tool.778779                Can be called multiple times for retry logic.780781                Can skip calling it to short-circuit.782783        Returns:784            `ToolMessage` or `Command` (the final result).785786        The handler `Callable` can be invoked multiple times for retry logic.787788        Each call to handler is independent and stateless.789790        Examples:791            !!! example "Async retry on error"792793                ```python794                async def awrap_tool_call(self, request, handler):795                    for attempt in range(3):796                        try:797                            result = await handler(request)798                            if is_valid(result):799                                return result800                        except Exception:801                            if attempt == 2:802                                raise803                    return result804                ```805806                ```python807                async def awrap_tool_call(self, request, handler):808                    if cached := await get_cache_async(request):809                        return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])810                    result = await handler(request)811                    await save_cache_async(request, result)812                    return result813                ```814        """815        msg = (816            "Asynchronous implementation of awrap_tool_call is not available. "817            "You are likely encountering this error because you defined only the sync version "818            "(wrap_tool_call) and invoked your agent in an asynchronous context "819            "(e.g., using `astream()` or `ainvoke()`). "820            "To resolve this, either: "821            "(1) subclass AgentMiddleware and implement the asynchronous awrap_tool_call method, "822            "(2) use the @wrap_tool_call decorator on a standalone async function, or "823            "(3) invoke your agent synchronously using `stream()` or `invoke()`."824        )825        raise NotImplementedError(msg)826827828_SyncCallableWithStateAndRuntime = Callable[829    [StateT_contra, Runtime[ContextT]], dict[str, Any] | Command[Any] | None830]831_AsyncCallableWithStateAndRuntime = Callable[832    [StateT_contra, Runtime[ContextT]], Awaitable[dict[str, Any] | Command[Any] | None]833]834_CallableWithStateAndRuntime = (835    _SyncCallableWithStateAndRuntime[StateT_contra, ContextT]836    | _AsyncCallableWithStateAndRuntime[StateT_contra, ContextT]837)838839_SyncCallableReturningSystemMessage = Callable[[ModelRequest[ContextT]], str | SystemMessage]840_AsyncCallableReturningSystemMessage = Callable[841    [ModelRequest[ContextT]], Awaitable[str | SystemMessage]842]843_CallableReturningSystemMessage = (844    _SyncCallableReturningSystemMessage[ContextT] | _AsyncCallableReturningSystemMessage[ContextT]845)846847# Sync/async signatures for `wrap_model_call` interception; see `@wrap_model_call`.848_SyncCallableReturningModelResponse = Callable[849    [ModelRequest[ContextT], Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]]],850    ModelCallResult,851]852_AsyncCallableReturningModelResponse = Callable[853    [854        ModelRequest[ContextT],855        Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],856    ],857    Awaitable[ModelCallResult],858]859_CallableReturningModelResponse = (860    _SyncCallableReturningModelResponse[ContextT, ResponseT]861    | _AsyncCallableReturningModelResponse[ContextT, ResponseT]862)863864# Sync/async signatures for `wrap_tool_call` interception; see `@wrap_tool_call`.865_SyncCallableReturningToolResponse = Callable[866    [ToolCallRequest, Callable[[ToolCallRequest], ToolMessage | Command[Any]]],867    ToolMessage | Command[Any],868]869_AsyncCallableReturningToolResponse = Callable[870    [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],871    Awaitable[ToolMessage | Command[Any]],872]873_CallableReturningToolResponse = (874    _SyncCallableReturningToolResponse | _AsyncCallableReturningToolResponse875)876877878CallableT = TypeVar("CallableT", bound=Callable[..., Any])879880881def hook_config(882    *,883    can_jump_to: list[JumpTo] | None = None,884) -> Callable[[CallableT], CallableT]:885    """Decorator to configure hook behavior in middleware methods.886887    Use this decorator on `before_model` or `after_model` methods in middleware classes888    to configure their behavior. Currently supports specifying which destinations they889    can jump to, which establishes conditional edges in the agent graph.890891    Args:892        can_jump_to: Optional list of valid jump destinations.893894            Can be:895896            - `'tools'`: Jump to the tools node897            - `'model'`: Jump back to the model node898            - `'end'`: Jump to the end of the graph899900    Returns:901        Decorator function that marks the method with configuration metadata.902903    Examples:904        !!! example "Using decorator on a class method"905906            ```python907            class MyMiddleware(AgentMiddleware):908                @hook_config(can_jump_to=["end", "model"])909                def before_model(self, state: AgentState) -> dict[str, Any] | None:910                    if some_condition(state):911                        return {"jump_to": "end"}912                    return None913            ```914915        Alternative: Use the `can_jump_to` parameter in `before_model`/`after_model`916        decorators:917918        ```python919        @before_model(can_jump_to=["end"])920        def conditional_middleware(state: AgentState) -> dict[str, Any] | None:921            if should_exit(state):922                return {"jump_to": "end"}923            return None924        ```925    """926927    def decorator(func: CallableT) -> CallableT:928        if can_jump_to is not None:929            func.__can_jump_to__ = can_jump_to  # type: ignore[attr-defined]930        return func931932    return decorator933934935@overload936def before_model(937    func: _CallableWithStateAndRuntime[StateT, ContextT],938) -> AgentMiddleware[StateT, ContextT]: ...939940941@overload942def before_model(943    func: None = None,944    *,945    state_schema: type[StateT] | None = None,946    tools: list[BaseTool] | None = None,947    can_jump_to: list[JumpTo] | None = None,948    name: str | None = None,949) -> Callable[950    [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]951]: ...952953954def before_model(955    func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,956    *,957    state_schema: type[StateT] | None = None,958    tools: list[BaseTool] | None = None,959    can_jump_to: list[JumpTo] | None = None,960    name: str | None = None,961) -> (962    Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]963    | AgentMiddleware[StateT, ContextT]964):965    """Decorator used to dynamically create a middleware with the `before_model` hook.966967    Args:968        func: The function to be decorated.969970            Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime971                context972        state_schema: Optional custom state schema type.973974            If not provided, uses the default `AgentState` schema.975        tools: Optional list of additional tools to register with this middleware.976        can_jump_to: Optional list of valid jump destinations for conditional edges.977978            Valid values are: `'tools'`, `'model'`, `'end'`979        name: Optional name for the generated middleware class.980981            If not provided, uses the decorated function's name.982983    Returns:984        Either an `AgentMiddleware` instance (if func is provided directly) or a985            decorator function that can be applied to a function it is wrapping.986987    The decorated function should return:988989    - `dict[str, Any]` - State updates to merge into the agent state990    - `Command` - A command to control flow (e.g., jump to different node)991    - `None` - No state updates or flow control992993    Examples:994        !!! example "Basic usage"995996            ```python997            @before_model998            def log_before_model(state: AgentState, runtime: Runtime) -> None:999                print(f"About to call model with {len(state['messages'])} messages")1000            ```10011002        !!! example "With conditional jumping"10031004            ```python1005            @before_model(can_jump_to=["end"])1006            def conditional_before_model(1007                state: AgentState, runtime: Runtime1008            ) -> dict[str, Any] | None:1009                if some_condition(state):1010                    return {"jump_to": "end"}1011                return None1012            ```10131014        !!! example "With custom state schema"10151016        Use a custom state schema when your middleware needs to read or write additional1017        state fields that aren't part of the default agent state.10181019            ```python1020            @before_model(state_schema=MyCustomState)1021            def custom_before_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1022                return {"custom_field": "updated_value"}1023            ```10241025        !!! example "Streaming custom events before model call"10261027            Use `runtime.stream_writer` to emit custom events before each model invocation.1028            Events are received when streaming with `stream_mode="custom"`.10291030            ```python1031            @before_model1032            async def notify_model_call(state: AgentState, runtime: Runtime) -> None:1033                '''Notify user before model is called.'''1034                runtime.stream_writer(1035                    {1036                        "type": "status",1037                        "message": "Thinking...",1038                    }1039                )1040            ```1041    """10421043    def decorator(1044        func: _CallableWithStateAndRuntime[StateT, ContextT],1045    ) -> AgentMiddleware[StateT, ContextT]:1046        is_async = iscoroutinefunction(func)10471048        func_can_jump_to = (1049            can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1050        )10511052        if is_async:10531054            async def async_wrapped(1055                _self: AgentMiddleware[StateT, ContextT],1056                state: StateT,1057                runtime: Runtime[ContextT],1058            ) -> dict[str, Any] | Command[Any] | None:1059                # `iscoroutinefunction` narrows `func` at runtime, but type checkers1060                # cannot narrow this sync-or-async callable union.1061                return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1062                    state, runtime1063                )10641065            # Preserve can_jump_to metadata on the wrapped function1066            if func_can_jump_to:1067                async_wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]10681069            middleware_name = name or cast(1070                "str", getattr(func, "__name__", "BeforeModelMiddleware")1071            )10721073            # `type(...)` builds the correct middleware subclass at runtime, but1074            # type checkers cannot infer its generic `AgentMiddleware` parameters.1075            return cast(1076                "AgentMiddleware[StateT, ContextT]",1077                type(1078                    middleware_name,1079                    (AgentMiddleware,),1080                    {1081                        "state_schema": state_schema or AgentState,1082                        "tools": tools or [],1083                        "abefore_model": async_wrapped,1084                    },1085                )(),1086            )10871088        def wrapped(1089            _self: AgentMiddleware[StateT, ContextT],1090            state: StateT,1091            runtime: Runtime[ContextT],1092        ) -> dict[str, Any] | Command[Any] | None:1093            # `iscoroutinefunction` narrows `func` at runtime, but type checkers1094            # cannot narrow this sync-or-async callable union.1095            return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)10961097        # Preserve can_jump_to metadata on the wrapped function1098        if func_can_jump_to:1099            wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]11001101        # Use function name as default if no name provided1102        middleware_name = name or cast("str", getattr(func, "__name__", "BeforeModelMiddleware"))11031104        # `type(...)` builds the correct middleware subclass at runtime, but1105        # type checkers cannot infer its generic `AgentMiddleware` parameters.1106        return cast(1107            "AgentMiddleware[StateT, ContextT]",1108            type(1109                middleware_name,1110                (AgentMiddleware,),1111                {1112                    "state_schema": state_schema or AgentState,1113                    "tools": tools or [],1114                    "before_model": wrapped,1115                },1116            )(),1117        )11181119    if func is not None:1120        return decorator(func)1121    return decorator112211231124@overload1125def after_model(1126    func: _CallableWithStateAndRuntime[StateT, ContextT],1127) -> AgentMiddleware[StateT, ContextT]: ...112811291130@overload1131def after_model(1132    func: None = None,1133    *,1134    state_schema: type[StateT] | None = None,1135    tools: list[BaseTool] | None = None,1136    can_jump_to: list[JumpTo] | None = None,1137    name: str | None = None,1138) -> Callable[1139    [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]1140]: ...114111421143def after_model(1144    func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,1145    *,1146    state_schema: type[StateT] | None = None,1147    tools: list[BaseTool] | None = None,1148    can_jump_to: list[JumpTo] | None = None,1149    name: str | None = None,1150) -> (1151    Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]1152    | AgentMiddleware[StateT, ContextT]1153):1154    """Decorator used to dynamically create a middleware with the `after_model` hook.11551156    Args:1157        func: The function to be decorated.11581159            Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime1160            context1161        state_schema: Optional custom state schema type.11621163            If not provided, uses the default `AgentState` schema.1164        tools: Optional list of additional tools to register with this middleware.1165        can_jump_to: Optional list of valid jump destinations for conditional edges.11661167            Valid values are: `'tools'`, `'model'`, `'end'`1168        name: Optional name for the generated middleware class.11691170            If not provided, uses the decorated function's name.11711172    Returns:1173        Either an `AgentMiddleware` instance (if func is provided) or a decorator1174            function that can be applied to a function.11751176    The decorated function should return:11771178    - `dict[str, Any]` - State updates to merge into the agent state1179    - `Command` - A command to control flow (e.g., jump to different node)1180    - `None` - No state updates or flow control11811182    Examples:1183        !!! example "Basic usage for logging model responses"11841185            ```python1186            @after_model1187            def log_latest_message(state: AgentState, runtime: Runtime) -> None:1188                print(state["messages"][-1].content)1189            ```11901191        !!! example "With custom state schema"11921193        Use a custom state schema when your middleware needs to read or write additional1194        state fields that aren't part of the default agent state.11951196            ```python1197            @after_model(state_schema=MyCustomState, name="MyAfterModelMiddleware")1198            def custom_after_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1199                return {"custom_field": "updated_after_model"}1200            ```12011202        !!! example "Streaming custom events after model call"12031204            Use `runtime.stream_writer` to emit custom events after model responds.1205            Events are received when streaming with `stream_mode="custom"`.12061207            ```python1208            @after_model1209            async def notify_model_response(state: AgentState, runtime: Runtime) -> None:1210                '''Notify user after model has responded.'''1211                last_message = state["messages"][-1]1212                has_tool_calls = hasattr(last_message, "tool_calls") and last_message.tool_calls1213                runtime.stream_writer(1214                    {1215                        "type": "status",1216                        "message": "Using tools..." if has_tool_calls else "Response ready!",1217                    }1218                )1219            ```1220    """12211222    def decorator(1223        func: _CallableWithStateAndRuntime[StateT, ContextT],1224    ) -> AgentMiddleware[StateT, ContextT]:1225        is_async = iscoroutinefunction(func)1226        # Extract can_jump_to from decorator parameter or from function metadata1227        func_can_jump_to = (1228            can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1229        )12301231        if is_async:12321233            async def async_wrapped(1234                _self: AgentMiddleware[StateT, ContextT],1235                state: StateT,1236                runtime: Runtime[ContextT],1237            ) -> dict[str, Any] | Command[Any] | None:1238                # `iscoroutinefunction` narrows `func` at runtime, but type checkers1239                # cannot narrow this sync-or-async callable union.1240                return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1241                    state, runtime1242                )12431244            # Preserve can_jump_to metadata on the wrapped function1245            if func_can_jump_to:1246                async_wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]12471248            middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))12491250            # `type(...)` builds the correct middleware subclass at runtime, but1251            # type checkers cannot infer its generic `AgentMiddleware` parameters.1252            return cast(1253                "AgentMiddleware[StateT, ContextT]",1254                type(1255                    middleware_name,1256                    (AgentMiddleware,),1257                    {1258                        "state_schema": state_schema or AgentState,1259                        "tools": tools or [],1260                        "aafter_model": async_wrapped,1261                    },1262                )(),1263            )12641265        def wrapped(1266            _self: AgentMiddleware[StateT, ContextT],1267            state: StateT,1268            runtime: Runtime[ContextT],1269        ) -> dict[str, Any] | Command[Any] | None:1270            # `iscoroutinefunction` narrows `func` at runtime, but type checkers1271            # cannot narrow this sync-or-async callable union.1272            return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)12731274        # Preserve can_jump_to metadata on the wrapped function1275        if func_can_jump_to:1276            wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]12771278        # Use function name as default if no name provided1279        middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))12801281        # `type(...)` builds the correct middleware subclass at runtime, but1282        # type checkers cannot infer its generic `AgentMiddleware` parameters.1283        return cast(1284            "AgentMiddleware[StateT, ContextT]",1285            type(1286                middleware_name,1287                (AgentMiddleware,),1288                {1289                    "state_schema": state_schema or AgentState,1290                    "tools": tools or [],1291                    "after_model": wrapped,1292                },1293            )(),1294        )12951296    if func is not None:1297        return decorator(func)1298    return decorator129913001301@overload1302def before_agent(1303    func: _CallableWithStateAndRuntime[StateT, ContextT],1304) -> AgentMiddleware[StateT, ContextT]: ...130513061307@overload1308def before_agent(1309    func: None = None,1310    *,1311    state_schema: type[StateT] | None = None,1312    tools: list[BaseTool] | None = None,1313    can_jump_to: list[JumpTo] | None = None,1314    name: str | None = None,1315) -> Callable[1316    [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]1317]: ...131813191320def before_agent(1321    func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,1322    *,1323    state_schema: type[StateT] | None = None,1324    tools: list[BaseTool] | None = None,1325    can_jump_to: list[JumpTo] | None = None,1326    name: str | None = None,1327) -> (1328    Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]1329    | AgentMiddleware[StateT, ContextT]1330):1331    """Decorator used to dynamically create a middleware with the `before_agent` hook.13321333    Args:1334        func: The function to be decorated.13351336            Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime1337            context1338        state_schema: Optional custom state schema type.13391340            If not provided, uses the default `AgentState` schema.1341        tools: Optional list of additional tools to register with this middleware.1342        can_jump_to: Optional list of valid jump destinations for conditional edges.13431344            Valid values are: `'tools'`, `'model'`, `'end'`1345        name: Optional name for the generated middleware class.13461347            If not provided, uses the decorated function's name.13481349    Returns:1350        Either an `AgentMiddleware` instance (if func is provided directly) or a1351            decorator function that can be applied to a function it is wrapping.13521353    The decorated function should return:13541355    - `dict[str, Any]` - State updates to merge into the agent state1356    - `Command` - A command to control flow (e.g., jump to different node)1357    - `None` - No state updates or flow control13581359    Examples:1360        !!! example "Basic usage"13611362            ```python1363            @before_agent1364            def log_before_agent(state: AgentState, runtime: Runtime) -> None:1365                print(f"Starting agent with {len(state['messages'])} messages")1366            ```13671368        !!! example "With conditional jumping"13691370            ```python1371            @before_agent(can_jump_to=["end"])1372            def conditional_before_agent(1373                state: AgentState, runtime: Runtime1374            ) -> dict[str, Any] | None:1375                if some_condition(state):1376                    return {"jump_to": "end"}1377                return None1378            ```13791380        !!! example "With custom state schema"13811382        Use a custom state schema when your middleware needs to read or write additional1383        state fields that aren't part of the default agent state.13841385            ```python1386            @before_agent(state_schema=MyCustomState)1387            def custom_before_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1388                return {"custom_field": "initialized_value"}1389            ```13901391        !!! example "Streaming custom events"13921393            Use `runtime.stream_writer` to emit custom events during agent execution.1394            Events are received when streaming with `stream_mode="custom"`.13951396            ```python1397            from langchain.agents import create_agent1398            from langchain.agents.middleware import before_agent, AgentState1399            from langchain.messages import HumanMessage1400            from langgraph.runtime import Runtime140114021403            @before_agent1404            async def notify_start(state: AgentState, runtime: Runtime) -> None:1405                '''Notify user that agent is starting.'''1406                runtime.stream_writer(1407                    {1408                        "type": "status",1409                        "message": "Initializing agent session...",1410                    }1411                )1412                # Perform prerequisite tasks here1413                runtime.stream_writer({"type": "status", "message": "Agent ready!"})141414151416            agent = create_agent(1417                model="openai:gpt-5.2",1418                tools=[...],1419                middleware=[notify_start],1420            )14211422            # Consume with stream_mode="custom" to receive events1423            async for mode, event in agent.astream(1424                {"messages": [HumanMessage("Hello")]},1425                stream_mode=["updates", "custom"],1426            ):1427                if mode == "custom":1428                    print(f"Status: {event}")1429            ```1430    """14311432    def decorator(1433        func: _CallableWithStateAndRuntime[StateT, ContextT],1434    ) -> AgentMiddleware[StateT, ContextT]:1435        is_async = iscoroutinefunction(func)14361437        func_can_jump_to = (1438            can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1439        )14401441        if is_async:14421443            async def async_wrapped(1444                _self: AgentMiddleware[StateT, ContextT],1445                state: StateT,1446                runtime: Runtime[ContextT],1447            ) -> dict[str, Any] | Command[Any] | None:1448                # `iscoroutinefunction` narrows `func` at runtime, but type checkers1449                # cannot narrow this sync-or-async callable union.1450                return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1451                    state, runtime1452                )14531454            # Preserve can_jump_to metadata on the wrapped function1455            if func_can_jump_to:1456                async_wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]14571458            middleware_name = name or cast(1459                "str", getattr(func, "__name__", "BeforeAgentMiddleware")1460            )14611462            # `type(...)` builds the correct middleware subclass at runtime, but1463            # type checkers cannot infer its generic `AgentMiddleware` parameters.1464            return cast(1465                "AgentMiddleware[StateT, ContextT]",1466                type(1467                    middleware_name,1468                    (AgentMiddleware,),1469                    {1470                        "state_schema": state_schema or AgentState,1471                        "tools": tools or [],1472                        "abefore_agent": async_wrapped,1473                    },1474                )(),1475            )14761477        def wrapped(1478            _self: AgentMiddleware[StateT, ContextT],1479            state: StateT,1480            runtime: Runtime[ContextT],1481        ) -> dict[str, Any] | Command[Any] | None:1482            # `iscoroutinefunction` narrows `func` at runtime, but type checkers1483            # cannot narrow this sync-or-async callable union.1484            return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)14851486        # Preserve can_jump_to metadata on the wrapped function1487        if func_can_jump_to:1488            wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]14891490        # Use function name as default if no name provided1491        middleware_name = name or cast("str", getattr(func, "__name__", "BeforeAgentMiddleware"))14921493        # `type(...)` builds the correct middleware subclass at runtime, but1494        # type checkers cannot infer its generic `AgentMiddleware` parameters.1495        return cast(1496            "AgentMiddleware[StateT, ContextT]",1497            type(1498                middleware_name,1499                (AgentMiddleware,),1500                {1501                    "state_schema": state_schema or AgentState,1502                    "tools": tools or [],1503                    "before_agent": wrapped,1504                },1505            )(),1506        )15071508    if func is not None:1509        return decorator(func)1510    return decorator151115121513@overload1514def after_agent(1515    func: _CallableWithStateAndRuntime[StateT, ContextT],1516) -> AgentMiddleware[StateT, ContextT]: ...151715181519@overload1520def after_agent(1521    func: None = None,1522    *,1523    state_schema: type[StateT] | None = None,1524    tools: list[BaseTool] | None = None,1525    can_jump_to: list[JumpTo] | None = None,1526    name: str | None = None,1527) -> Callable[1528    [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]1529]: ...153015311532def after_agent(1533    func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,1534    *,1535    state_schema: type[StateT] | None = None,1536    tools: list[BaseTool] | None = None,1537    can_jump_to: list[JumpTo] | None = None,1538    name: str | None = None,1539) -> (1540    Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]1541    | AgentMiddleware[StateT, ContextT]1542):1543    """Decorator used to dynamically create a middleware with the `after_agent` hook.15441545    Async version is `aafter_agent`.15461547    Args:1548        func: The function to be decorated.15491550            Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime1551            context1552        state_schema: Optional custom state schema type.15531554            If not provided, uses the default `AgentState` schema.1555        tools: Optional list of additional tools to register with this middleware.1556        can_jump_to: Optional list of valid jump destinations for conditional edges.15571558            Valid values are: `'tools'`, `'model'`, `'end'`1559        name: Optional name for the generated middleware class.15601561            If not provided, uses the decorated function's name.15621563    Returns:1564        Either an `AgentMiddleware` instance (if func is provided) or a decorator1565            function that can be applied to a function.15661567    The decorated function should return:15681569    - `dict[str, Any]` - State updates to merge into the agent state1570    - `Command` - A command to control flow (e.g., jump to different node)1571    - `None` - No state updates or flow control15721573    Examples:1574        !!! example "Basic usage for logging agent completion"15751576            ```python1577            @after_agent1578            def log_completion(state: AgentState, runtime: Runtime) -> None:1579                print(f"Agent completed with {len(state['messages'])} messages")1580            ```15811582        !!! example "With custom state schema"15831584        Use a custom state schema when your middleware needs to read or write additional1585        state fields that aren't part of the default agent state.15861587            ```python1588            @after_agent(state_schema=MyCustomState, name="MyAfterAgentMiddleware")1589            def custom_after_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1590                return {"custom_field": "finalized_value"}1591            ```15921593        !!! example "Streaming custom events on completion"15941595            Use `runtime.stream_writer` to emit custom events when agent completes.1596            Events are received when streaming with `stream_mode="custom"`.15971598            ```python1599            @after_agent1600            async def notify_completion(state: AgentState, runtime: Runtime) -> None:1601                '''Notify user that agent has completed.'''1602                runtime.stream_writer(1603                    {1604                        "type": "status",1605                        "message": "Agent execution complete!",1606                        "total_messages": len(state["messages"]),1607                    }1608                )1609            ```1610    """16111612    def decorator(1613        func: _CallableWithStateAndRuntime[StateT, ContextT],1614    ) -> AgentMiddleware[StateT, ContextT]:1615        is_async = iscoroutinefunction(func)1616        # Extract can_jump_to from decorator parameter or from function metadata1617        func_can_jump_to = (1618            can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1619        )16201621        if is_async:16221623            async def async_wrapped(1624                _self: AgentMiddleware[StateT, ContextT],1625                state: StateT,1626                runtime: Runtime[ContextT],1627            ) -> dict[str, Any] | Command[Any] | None:1628                # `iscoroutinefunction` narrows `func` at runtime, but type checkers1629                # cannot narrow this sync-or-async callable union.1630                return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1631                    state, runtime1632                )16331634            # Preserve can_jump_to metadata on the wrapped function1635            if func_can_jump_to:1636                async_wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]16371638            middleware_name = name or cast("str", getattr(func, "__name__", "AfterAgentMiddleware"))16391640            # `type(...)` builds the correct middleware subclass at runtime, but1641            # type checkers cannot infer its generic `AgentMiddleware` parameters.1642            return cast(1643                "AgentMiddleware[StateT, ContextT]",1644                type(1645                    middleware_name,1646                    (AgentMiddleware,),1647                    {1648                        "state_schema": state_schema or AgentState,1649                        "tools": tools or [],1650                        "aafter_agent": async_wrapped,1651                    },1652                )(),1653            )16541655        def wrapped(1656            _self: AgentMiddleware[StateT, ContextT],1657            state: StateT,1658            runtime: Runtime[ContextT],1659        ) -> dict[str, Any] | Command[Any] | None:1660            # `iscoroutinefunction` narrows `func` at runtime, but type checkers1661            # cannot narrow this sync-or-async callable union.1662            return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)16631664        # Preserve can_jump_to metadata on the wrapped function1665        if func_can_jump_to:1666            wrapped.__can_jump_to__ = func_can_jump_to  # type: ignore[attr-defined]16671668        # Use function name as default if no name provided1669        middleware_name = name or cast("str", getattr(func, "__name__", "AfterAgentMiddleware"))16701671        # `type(...)` builds the correct middleware subclass at runtime, but1672        # type checkers cannot infer its generic `AgentMiddleware` parameters.1673        return cast(1674            "AgentMiddleware[StateT, ContextT]",1675            type(1676                middleware_name,1677                (AgentMiddleware,),1678                {1679                    "state_schema": state_schema or AgentState,1680                    "tools": tools or [],1681                    "after_agent": wrapped,1682                },1683            )(),1684        )16851686    if func is not None:1687        return decorator(func)1688    return decorator168916901691@overload1692def dynamic_prompt(1693    func: _CallableReturningSystemMessage[ContextT],1694) -> AgentMiddleware[StateT, ContextT]: ...169516961697@overload1698def dynamic_prompt(1699    func: None = None,1700) -> Callable[1701    [_CallableReturningSystemMessage[ContextT]],1702    AgentMiddleware[StateT, ContextT],1703]: ...170417051706def dynamic_prompt(1707    func: _CallableReturningSystemMessage[ContextT] | None = None,1708) -> (1709    Callable[1710        [_CallableReturningSystemMessage[ContextT]],1711        AgentMiddleware[StateT, ContextT],1712    ]1713    | AgentMiddleware[StateT, ContextT]1714):1715    """Decorator used to dynamically generate system prompts for the model.17161717    This is a convenience decorator that creates middleware using `wrap_model_call`1718    specifically for dynamic prompt generation. The decorated function should return1719    a string that will be set as the system prompt for the model request.17201721    Args:1722        func: The function to be decorated.17231724            Must accept: `request: ModelRequest` - Model request (contains state and1725            runtime)17261727    Returns:1728        Either an `AgentMiddleware` instance (if func is provided) or a decorator1729            function that can be applied to a function.17301731    The decorated function should return:1732        - `str` – The system prompt string to use for the model request1733        - `SystemMessage` – A complete system message to use for the model request17341735    Examples:1736        Basic usage with dynamic content:17371738        ```python1739        @dynamic_prompt1740        def my_prompt(request: ModelRequest) -> str:1741            user_name = request.runtime.context.get("user_name", "User")1742            return f"You are a helpful assistant helping {user_name}."1743        ```17441745        Using state to customize the prompt:17461747        ```python1748        @dynamic_prompt1749        def context_aware_prompt(request: ModelRequest) -> str:1750            msg_count = len(request.state["messages"])1751            if msg_count > 10:1752                return "You are in a long conversation. Be concise."1753            return "You are a helpful assistant."1754        ```17551756        Using with agent:17571758        ```python1759        agent = create_agent(model, middleware=[my_prompt])1760        ```1761    """17621763    def decorator(1764        func: _CallableReturningSystemMessage[ContextT],1765    ) -> AgentMiddleware[StateT, ContextT]:1766        is_async = iscoroutinefunction(func)17671768        if is_async:17691770            async def async_wrapped(1771                _self: AgentMiddleware[StateT, ContextT],1772                request: ModelRequest[ContextT],1773                handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[Any]]],1774            ) -> ModelResponse[Any] | AIMessage:1775                prompt = await cast("_AsyncCallableReturningSystemMessage[ContextT]", func)(request)1776                if isinstance(prompt, SystemMessage):1777                    request = request.override(system_message=prompt)1778                else:1779                    request = request.override(system_message=SystemMessage(content=prompt))1780                return await handler(request)17811782            middleware_name = cast("str", getattr(func, "__name__", "DynamicPromptMiddleware"))17831784            # `type(...)` builds the correct middleware subclass at runtime, but1785            # type checkers cannot infer its generic `AgentMiddleware` parameters.1786            return cast(1787                "AgentMiddleware[StateT, ContextT]",1788                type(1789                    middleware_name,1790                    (AgentMiddleware,),1791                    {1792                        "state_schema": AgentState,1793                        "tools": [],1794                        "awrap_model_call": async_wrapped,1795                    },1796                )(),1797            )17981799        def wrapped(1800            _self: AgentMiddleware[StateT, ContextT],1801            request: ModelRequest[ContextT],1802            handler: Callable[[ModelRequest[ContextT]], ModelResponse[Any]],1803        ) -> ModelResponse[Any] | AIMessage:1804            prompt = cast("_SyncCallableReturningSystemMessage[ContextT]", func)(request)1805            if isinstance(prompt, SystemMessage):1806                request = request.override(system_message=prompt)1807            else:1808                request = request.override(system_message=SystemMessage(content=prompt))1809            return handler(request)18101811        async def async_wrapped_from_sync(1812            _self: AgentMiddleware[StateT, ContextT],1813            request: ModelRequest[ContextT],1814            handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[Any]]],1815        ) -> ModelResponse[Any] | AIMessage:1816            # Delegate to sync function1817            prompt = cast("_SyncCallableReturningSystemMessage[ContextT]", func)(request)1818            if isinstance(prompt, SystemMessage):1819                request = request.override(system_message=prompt)1820            else:1821                request = request.override(system_message=SystemMessage(content=prompt))1822            return await handler(request)18231824        middleware_name = cast("str", getattr(func, "__name__", "DynamicPromptMiddleware"))18251826        # `type(...)` builds the correct middleware subclass at runtime, but1827        # type checkers cannot infer its generic `AgentMiddleware` parameters.1828        return cast(1829            "AgentMiddleware[StateT, ContextT]",1830            type(1831                middleware_name,1832                (AgentMiddleware,),1833                {1834                    "state_schema": AgentState,1835                    "tools": [],1836                    "wrap_model_call": wrapped,1837                    "awrap_model_call": async_wrapped_from_sync,1838                },1839            )(),1840        )18411842    if func is not None:1843        return decorator(func)1844    return decorator184518461847@overload1848def wrap_model_call(1849    func: _CallableReturningModelResponse[ContextT, ResponseT],1850) -> AgentMiddleware[StateT, ContextT]: ...185118521853@overload1854def wrap_model_call(1855    func: None = None,1856    *,1857    state_schema: type[StateT] | None = None,1858    tools: list[BaseTool] | None = None,1859    name: str | None = None,1860) -> Callable[1861    [_CallableReturningModelResponse[ContextT, ResponseT]],1862    AgentMiddleware[StateT, ContextT],1863]: ...186418651866def wrap_model_call(1867    func: _CallableReturningModelResponse[ContextT, ResponseT] | None = None,1868    *,1869    state_schema: type[StateT] | None = None,1870    tools: list[BaseTool] | None = None,1871    name: str | None = None,1872) -> (1873    Callable[1874        [_CallableReturningModelResponse[ContextT, ResponseT]],1875        AgentMiddleware[StateT, ContextT],1876    ]1877    | AgentMiddleware[StateT, ContextT]1878):1879    """Create middleware with `wrap_model_call` hook from a function.18801881    Converts a function with handler callback into middleware that can intercept model1882    calls, implement retry logic, handle errors, and rewrite responses.18831884    Args:1885        func: Function accepting (request, handler) that calls handler(request)1886            to execute the model and returns `ModelResponse` or `AIMessage`.18871888            Request contains state and runtime.1889        state_schema: Custom state schema.18901891            Defaults to `AgentState`.1892        tools: Additional tools to register with this middleware.1893        name: Middleware class name.18941895            Defaults to function name.18961897    Returns:1898        `AgentMiddleware` instance if func provided, otherwise a decorator.18991900    Examples:1901        !!! example "Basic retry logic"19021903            ```python1904            @wrap_model_call1905            def retry_on_error(request, handler):1906                max_retries = 31907                for attempt in range(max_retries):1908                    try:1909                        return handler(request)1910                    except Exception:1911                        if attempt == max_retries - 1:1912                            raise1913            ```19141915        !!! example "Model fallback"19161917            ```python1918            @wrap_model_call1919            def fallback_model(request, handler):1920                # Try primary model1921                try:1922                    return handler(request)1923                except Exception:1924                    pass19251926                # Try fallback model1927                request = request.override(model=fallback_model_instance)1928                return handler(request)1929            ```19301931        !!! example "Rewrite response content (full `ModelResponse`)"19321933            ```python1934            @wrap_model_call1935            def uppercase_responses(request, handler):1936                response = handler(request)1937                ai_msg = response.result[0]1938                return ModelResponse(1939                    result=[AIMessage(content=ai_msg.content.upper())],1940                    structured_response=response.structured_response,1941                )1942            ```19431944        !!! example "Simple `AIMessage` return (converted automatically)"19451946            ```python1947            @wrap_model_call1948            def simple_response(request, handler):1949                # AIMessage is automatically converted to ModelResponse1950                return AIMessage(content="Simple response")1951            ```1952    """19531954    def decorator(1955        func: _CallableReturningModelResponse[ContextT, ResponseT],1956    ) -> AgentMiddleware[StateT, ContextT]:1957        is_async = iscoroutinefunction(func)19581959        if is_async:19601961            async def async_wrapped(1962                _self: AgentMiddleware[StateT, ContextT],1963                request: ModelRequest[ContextT],1964                handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],1965            ) -> ModelCallResult[ResponseT]:1966                return await cast(1967                    "_AsyncCallableReturningModelResponse[ContextT, ResponseT]", func1968                )(request, handler)19691970            middleware_name = name or cast(1971                "str", getattr(func, "__name__", "WrapModelCallMiddleware")1972            )19731974            # `type(...)` builds the correct middleware subclass at runtime, but1975            # type checkers cannot infer its generic `AgentMiddleware` parameters.1976            return cast(1977                "AgentMiddleware[StateT, ContextT]",1978                type(1979                    middleware_name,1980                    (AgentMiddleware,),1981                    {1982                        "state_schema": state_schema or AgentState,1983                        "tools": tools or [],1984                        "awrap_model_call": async_wrapped,1985                    },1986                )(),1987            )19881989        def wrapped(1990            _self: AgentMiddleware[StateT, ContextT],1991            request: ModelRequest[ContextT],1992            handler: Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]],1993        ) -> ModelCallResult[ResponseT]:1994            return cast("_SyncCallableReturningModelResponse[ContextT, ResponseT]", func)(1995                request, handler1996            )19971998        middleware_name = name or cast("str", getattr(func, "__name__", "WrapModelCallMiddleware"))19992000        # `type(...)` builds the correct middleware subclass at runtime, but

Code quality findings 23

Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(func: CallableT) -> CallableT:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped_from_sync(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def decorator(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def async_wrapped(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def wrapped(

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings