Ensure functions have docstrings for documentation
def decorator(func: CallableT) -> CallableT:
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 cast,16 overload,17)1819# Needed as top level import for Pydantic schema generation on AgentState20from langchain_core.messages import (21 AIMessage,22 AnyMessage,23 BaseMessage,24 SystemMessage,25 ToolMessage,26)27from langgraph.channels.ephemeral_value import EphemeralValue28from langgraph.graph.message import add_messages29from langgraph.prebuilt.tool_node import ToolCallRequest, ToolCallWrapper30from langgraph.runtime import Runtime31from langgraph.types import Command, TracePolicy, omit_payload32from langgraph.typing import ContextT33from typing_extensions import NotRequired, Required, TypedDict, TypeVar, Unpack3435if TYPE_CHECKING:36 from langchain_core.language_models.chat_models import BaseChatModel37 from langchain_core.tools import BaseTool38 from langgraph.stream._mux import TransformerFactory3940 from langchain.agents.structured_output import ResponseFormat4142__all__ = [43 "AgentMiddleware",44 "AgentState",45 "ContextT",46 "ExtendedModelResponse",47 "InputAgentState",48 "ModelCallResult",49 "ModelRequest",50 "ModelResponse",51 "OmitFromSchema",52 "OutputAgentState",53 "ResponseT",54 "StateT_co",55 "ToolCallRequest",56 "ToolCallWrapper",57 "TracePolicy",58 "after_agent",59 "after_model",60 "before_agent",61 "before_model",62 "dynamic_prompt",63 "hook_config",64 "omit_payload",65 "wrap_tool_call",66]6768JumpTo = Literal["tools", "model", "end"]69"""Destination to jump to when a middleware node returns."""7071ResponseT = TypeVar("ResponseT", default=Any)727374class _ModelRequestOverrides(TypedDict, total=False):75 """Possible overrides for `ModelRequest.override()` method."""7677 model: BaseChatModel78 system_message: SystemMessage | None79 messages: list[AnyMessage]80 tool_choice: Any | None81 tools: list[BaseTool | dict[str, Any]]82 response_format: ResponseFormat[Any] | None83 model_settings: dict[str, Any]84 state: AgentState[Any]858687@dataclass(init=False)88class ModelRequest(Generic[ContextT]):89 """Model request information for the agent.9091 Type Parameters:92 ContextT: The type of the runtime context.9394 Defaults to `None` if not specified.95 """9697 model: BaseChatModel98 messages: list[AnyMessage] # excluding system message99 system_message: SystemMessage | None100 tool_choice: Any | None101 tools: list[BaseTool | dict[str, Any]]102 response_format: ResponseFormat[Any] | None103 state: AgentState[Any]104 runtime: Runtime[ContextT]105 model_settings: dict[str, Any] = field(default_factory=dict)106107 def __init__(108 self,109 *,110 model: BaseChatModel,111 messages: list[AnyMessage],112 system_message: SystemMessage | None = None,113 system_prompt: str | None = None,114 tool_choice: Any | None = None,115 tools: list[BaseTool | dict[str, Any]] | None = None,116 response_format: ResponseFormat[Any] | None = None,117 state: AgentState[Any] | None = None,118 runtime: Runtime[ContextT] | None = None,119 model_settings: dict[str, Any] | None = None,120 ) -> None:121 """Initialize `ModelRequest` with backward compatibility for `system_prompt`.122123 Args:124 model: The chat model to use.125 messages: List of messages (excluding system prompt).126 tool_choice: Tool choice configuration.127 tools: List of available tools.128 response_format: Response format specification.129 state: Agent state.130 runtime: Runtime context.131 model_settings: Additional model settings.132 system_message: System message instance (preferred).133 system_prompt: System prompt string (deprecated, converted to `SystemMessage`).134135 Raises:136 ValueError: If both `system_prompt` and `system_message` are provided.137 """138 # Handle system_prompt/system_message conversion and validation139 if system_prompt is not None and system_message is not None:140 msg = "Cannot specify both system_prompt and system_message"141 raise ValueError(msg)142143 if system_prompt is not None:144 system_message = SystemMessage(content=system_prompt)145146 with warnings.catch_warnings():147 warnings.simplefilter("ignore", category=DeprecationWarning)148 self.model = model149 self.messages = messages150 self.system_message = system_message151 self.tool_choice = tool_choice152 self.tools = tools if tools is not None else []153 self.response_format = response_format154 self.state = state if state is not None else {"messages": []}155 self.runtime = runtime # type: ignore[assignment]156 self.model_settings = model_settings if model_settings is not None else {}157158 @property159 def system_prompt(self) -> str | None:160 """Get system prompt text from system_message.161162 Returns:163 The content of the system message if present, otherwise `None`.164 """165 if self.system_message is None:166 return None167 return self.system_message.text168169 def __setattr__(self, name: str, value: Any) -> None:170 """Set an attribute with a deprecation warning.171172 Direct attribute assignment on `ModelRequest` is deprecated. Use the173 `override()` method instead to create a new request with modified attributes.174175 Args:176 name: Attribute name.177 value: Attribute value.178 """179 # Special handling for system_prompt - convert to system_message180 if name == "system_prompt":181 warnings.warn(182 "Direct attribute assignment to ModelRequest.system_prompt is deprecated. "183 "Use request.override(system_message=SystemMessage(...)) instead to create "184 "a new request with the modified system message.",185 DeprecationWarning,186 stacklevel=2,187 )188 if value is None:189 object.__setattr__(self, "system_message", None)190 else:191 object.__setattr__(self, "system_message", SystemMessage(content=value))192 return193194 warnings.warn(195 f"Direct attribute assignment to ModelRequest.{name} is deprecated. "196 f"Use request.override({name}=...) instead to create a new request "197 f"with the modified attribute.",198 DeprecationWarning,199 stacklevel=2,200 )201 object.__setattr__(self, name, value)202203 def override(self, **overrides: Unpack[_ModelRequestOverrides]) -> ModelRequest[ContextT]:204 """Replace the request with a new request with the given overrides.205206 Returns a new `ModelRequest` instance with the specified attributes replaced.207208 This follows an immutable pattern, leaving the original request unchanged.209210 Args:211 **overrides: Keyword arguments for attributes to override.212213 Supported keys:214215 - `model`: `BaseChatModel` instance216 - `system_prompt`: deprecated, use `system_message` instead217 - `system_message`: `SystemMessage` instance218 - `messages`: `list` of messages219 - `tool_choice`: Tool choice configuration220 - `tools`: `list` of available tools221 - `response_format`: Response format specification222 - `model_settings`: Additional model settings223 - `state`: Agent state dictionary224225 Returns:226 New `ModelRequest` instance with specified overrides applied.227228 Examples:229 !!! example "Create a new request with different model"230231 ```python232 new_request = request.override(model=different_model)233 ```234235 !!! example "Override system message (preferred)"236237 ```python238 from langchain_core.messages import SystemMessage239240 new_request = request.override(241 system_message=SystemMessage(content="New instructions")242 )243 ```244245 !!! example "Override multiple attributes"246247 ```python248 new_request = request.override(249 model=ChatOpenAI(model="gpt-5.5"),250 system_message=SystemMessage(content="New instructions"),251 )252 ```253254 Raises:255 ValueError: If both `system_prompt` and `system_message` are provided.256 """257 # Handle system_prompt/system_message conversion258 if "system_prompt" in overrides and "system_message" in overrides:259 msg = "Cannot specify both system_prompt and system_message"260 raise ValueError(msg)261262 if "system_prompt" in overrides:263 system_prompt = cast("str | None", overrides.pop("system_prompt")) # type: ignore[typeddict-item]264 if system_prompt is None:265 overrides["system_message"] = None266 else:267 overrides["system_message"] = SystemMessage(content=system_prompt)268269 return replace(self, **overrides)270271272@dataclass273class ModelResponse(Generic[ResponseT]):274 """Response from model execution including messages and optional structured output.275276 The result will usually contain a single `AIMessage`, but may include an additional277 `ToolMessage` if the model used a tool for structured output.278279 Type Parameters:280 ResponseT: The type of the structured response. Defaults to `Any` if not specified.281 """282283 result: list[BaseMessage]284 """List of messages from model execution."""285286 structured_response: ResponseT | None = None287 """Parsed structured output if `response_format` was specified, `None` otherwise."""288289290@dataclass291class ExtendedModelResponse(Generic[ResponseT]):292 """Model response with an optional 'Command' from 'wrap_model_call' middleware.293294 Use this to return a 'Command' alongside the model response from a295 'wrap_model_call' handler. The command is applied as an additional state296 update after the model node completes, using the graph's reducers (e.g.297 'add_messages' for the 'messages' key).298299 Because each 'Command' is applied through the reducer, messages in the300 command are **added alongside** the model response messages rather than301 replacing them. For non-reducer state fields, later commands overwrite302 earlier ones (outermost middleware wins over inner).303304 Type Parameters:305 ResponseT: The type of the structured response. Defaults to 'Any' if not specified.306 """307308 model_response: ModelResponse[ResponseT]309 """The underlying model response."""310311 command: Command[Any] | None = None312 """Optional command to apply as an additional state update."""313314315ModelCallResult = ModelResponse[ResponseT] | AIMessage | ExtendedModelResponse[ResponseT]316"""Return type for model call handlers.317318Middleware can return either:319320- `ModelResponse`: Full response with messages and optional structured output321- `AIMessage`: Simplified return for simple use cases322- `ExtendedModelResponse`: Response with an optional `Command` for additional state updates323 `goto`, `resume`, and `graph` are not yet supported on these commands.324 A `NotImplementedError` will be raised if you try to use them.325"""326327328@dataclass329class OmitFromSchema:330 """Annotation used to mark state attributes as omitted from input or output schemas."""331332 input: bool = True333 """Whether to omit the attribute from the input schema."""334335 output: bool = True336 """Whether to omit the attribute from the output schema."""337338339OmitFromInput = OmitFromSchema(input=True, output=False)340"""Annotation used to mark state attributes as omitted from input schema."""341342OmitFromOutput = OmitFromSchema(input=False, output=True)343"""Annotation used to mark state attributes as omitted from output schema."""344345PrivateStateAttr = OmitFromSchema(input=True, output=True)346"""Annotation used to mark state attributes as purely internal for a given middleware."""347348349class AgentState(TypedDict, Generic[ResponseT]):350 """State schema for the agent."""351352 messages: Required[Annotated[list[AnyMessage], add_messages]]353 jump_to: NotRequired[Annotated[JumpTo | None, EphemeralValue, PrivateStateAttr]]354 structured_response: NotRequired[Annotated[ResponseT, OmitFromInput]]355356357class InputAgentState(TypedDict):358 """Input state schema for the agent."""359360 messages: Required[Annotated[list[AnyMessage | dict[str, Any]], add_messages]]361362363class OutputAgentState(TypedDict, Generic[ResponseT]):364 """Output state schema for the agent."""365366 messages: Required[Annotated[list[AnyMessage], add_messages]]367 structured_response: NotRequired[ResponseT]368369370# Deprecated aliases kept for backwards compatibility with external consumers that371# imported the previously private names. Remove in a future release.372_InputAgentState = InputAgentState373_OutputAgentState = OutputAgentState374375376StateT = TypeVar("StateT", bound=AgentState[Any], default=AgentState[Any])377StateT_co = TypeVar("StateT_co", bound=AgentState[Any], default=AgentState[Any], covariant=True)378StateT_contra = TypeVar("StateT_contra", bound=AgentState[Any], contravariant=True)379380381class _DefaultAgentState(AgentState[Any]):382 """AgentMiddleware default state."""383384385class AgentMiddleware(Generic[StateT, ContextT, ResponseT]):386 """Base middleware class for an agent.387388 Subclass this and implement any of the defined methods to customize agent behavior389 between steps in the main agent loop.390391 Type Parameters:392 StateT: The type of the agent state. Defaults to `AgentState[Any]`.393 ContextT: The type of the runtime context. Defaults to `None`.394 ResponseT: The type of the structured response. Defaults to `Any`.395 """396397 state_schema: type[StateT] = cast("type[StateT]", _DefaultAgentState)398 """The schema for state passed to the middleware nodes."""399400 tools: Sequence[BaseTool]401 """Additional tools registered by the middleware."""402403 trace_policy: TracePolicy | None = None404 """Optional trace policy for this middleware's hook spans (`wrap_model_call`/405 `wrap_tool_call` and the `before_*`/`after_*` node hooks).406407 By default (`None`), hook spans are traced normally. Set a `TracePolicy` to shape408 what they record -- e.g. `TracePolicy(process_inputs=omit_payload)` to drop the409 conversation `messages`/`state` payload while keeping the span and its timing.410 Messages are still captured on the inner model-call span.411 """412413 transformers: Sequence[TransformerFactory] = ()414 """Stream transformer factories registered by the middleware.415416 Each entry is a scope-aware factory invoked as `factory(scope)` so every417 invocation receives a fresh instance. Factories are merged with the418 `transformers` argument of [`create_agent`][langchain.agents.create_agent]419 at graph compile time, after the `ToolCallTransformer` and before any420 user-supplied entries.421 """422423 @property424 def name(self) -> str:425 """The name of the middleware instance.426427 Defaults to the class name, but can be overridden for custom naming.428 """429 return self.__class__.__name__430431 def before_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:432 """Logic to run before the agent execution starts.433434 Args:435 state: The current agent state.436 runtime: The runtime context.437438 Returns:439 Agent state updates to apply before agent execution.440 """441442 async def abefore_agent(443 self, state: StateT, runtime: Runtime[ContextT]444 ) -> dict[str, Any] | None:445 """Async logic to run before the agent execution starts.446447 Args:448 state: The current agent state.449 runtime: The runtime context.450451 Returns:452 Agent state updates to apply before agent execution.453 """454455 def before_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:456 """Logic to run before the model is called.457458 Args:459 state: The current agent state.460 runtime: The runtime context.461462 Returns:463 Agent state updates to apply before model call.464 """465466 async def abefore_model(467 self, state: StateT, runtime: Runtime[ContextT]468 ) -> dict[str, Any] | None:469 """Async logic to run before the model is called.470471 Args:472 state: The agent state.473 runtime: The runtime context.474475 Returns:476 Agent state updates to apply before model call.477 """478479 def after_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:480 """Logic to run after the model is called.481482 Args:483 state: The current agent state.484 runtime: The runtime context.485486 Returns:487 Agent state updates to apply after model call.488 """489490 async def aafter_model(491 self, state: StateT, runtime: Runtime[ContextT]492 ) -> dict[str, Any] | None:493 """Async logic to run after the model is called.494495 Args:496 state: The current agent state.497 runtime: The runtime context.498499 Returns:500 Agent state updates to apply after model call.501 """502503 def wrap_model_call(504 self,505 request: ModelRequest[ContextT],506 handler: Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]],507 ) -> ModelResponse[ResponseT] | AIMessage | ExtendedModelResponse[ResponseT]:508 """Intercept and control model execution via handler callback.509510 Async version is `awrap_model_call`511512 The handler callback executes the model request and returns a `ModelResponse`.513 Middleware can call the handler multiple times for retry logic, skip calling514 it to short-circuit, or modify the request/response. Multiple middleware515 compose with first in list as outermost layer.516517 Args:518 request: Model request to execute (includes state and runtime).519 handler: Callback that executes the model request and returns520 `ModelResponse`.521522 Call this to execute the model.523524 Can be called multiple times for retry logic.525526 Can skip calling it to short-circuit.527528 Returns:529 The model call result.530531 Examples:532 !!! example "Retry on error"533534 ```python535 def wrap_model_call(self, request, handler):536 for attempt in range(3):537 try:538 return handler(request)539 except Exception:540 if attempt == 2:541 raise542 ```543544 !!! example "Rewrite response"545546 ```python547 def wrap_model_call(self, request, handler):548 response = handler(request)549 ai_msg = response.result[0]550 return ModelResponse(551 result=[AIMessage(content=f"[{ai_msg.content}]")],552 structured_response=response.structured_response,553 )554 ```555556 !!! example "Error to fallback"557558 ```python559 def wrap_model_call(self, request, handler):560 try:561 return handler(request)562 except Exception:563 return ModelResponse(result=[AIMessage(content="Service unavailable")])564 ```565566 !!! example "Cache/short-circuit"567568 ```python569 def wrap_model_call(self, request, handler):570 if cached := get_cache(request):571 return cached # Short-circuit with cached result572 response = handler(request)573 save_cache(request, response)574 return response575 ```576577 !!! example "Simple `AIMessage` return (converted automatically)"578579 ```python580 def wrap_model_call(self, request, handler):581 response = handler(request)582 # Can return AIMessage directly for simple cases583 return AIMessage(content="Simplified response")584 ```585 """586 msg = (587 "Synchronous implementation of wrap_model_call is not available. "588 "You are likely encountering this error because you defined only the async version "589 "(awrap_model_call) and invoked your agent in a synchronous context "590 "(e.g., using `stream()` or `invoke()`). "591 "To resolve this, either: "592 "(1) subclass AgentMiddleware and implement the synchronous wrap_model_call method, "593 "(2) use the @wrap_model_call decorator on a standalone sync function, or "594 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."595 )596 raise NotImplementedError(msg)597598 async def awrap_model_call(599 self,600 request: ModelRequest[ContextT],601 handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],602 ) -> ModelResponse[ResponseT] | AIMessage | ExtendedModelResponse[ResponseT]:603 """Intercept and control async model execution via handler callback.604605 The handler callback executes the model request and returns a `ModelResponse`.606607 Middleware can call the handler multiple times for retry logic, skip calling608 it to short-circuit, or modify the request/response. Multiple middleware609 compose with first in list as outermost layer.610611 Args:612 request: Model request to execute (includes state and runtime).613 handler: Async callback that executes the model request and returns614 `ModelResponse`.615616 Call this to execute the model.617618 Can be called multiple times for retry logic.619620 Can skip calling it to short-circuit.621622 Returns:623 The model call result.624625 Examples:626 !!! example "Retry on error"627628 ```python629 async def awrap_model_call(self, request, handler):630 for attempt in range(3):631 try:632 return await handler(request)633 except Exception:634 if attempt == 2:635 raise636 ```637 """638 msg = (639 "Asynchronous implementation of awrap_model_call is not available. "640 "You are likely encountering this error because you defined only the sync version "641 "(wrap_model_call) and invoked your agent in an asynchronous context "642 "(e.g., using `astream()` or `ainvoke()`). "643 "To resolve this, either: "644 "(1) subclass AgentMiddleware and implement the asynchronous awrap_model_call method, "645 "(2) use the @wrap_model_call decorator on a standalone async function, or "646 "(3) invoke your agent synchronously using `stream()` or `invoke()`."647 )648 raise NotImplementedError(msg)649650 def after_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:651 """Logic to run after the agent execution completes.652653 Args:654 state: The current agent state.655 runtime: The runtime context.656657 Returns:658 Agent state updates to apply after agent execution.659 """660661 async def aafter_agent(662 self, state: StateT, runtime: Runtime[ContextT]663 ) -> dict[str, Any] | None:664 """Async logic to run after the agent execution completes.665666 Args:667 state: The current agent state.668 runtime: The runtime context.669670 Returns:671 Agent state updates to apply after agent execution.672 """673674 def wrap_tool_call(675 self,676 request: ToolCallRequest,677 handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],678 ) -> ToolMessage | Command[Any]:679 """Intercept tool execution for retries, monitoring, or modification.680681 Async version is `awrap_tool_call`682683 Multiple middleware compose automatically (first defined = outermost).684685 Exceptions propagate unless `handle_tool_errors` is configured on `ToolNode`.686687 Args:688 request: Tool call request with call `dict`, `BaseTool`, state, and runtime.689690 Access state via `request.state` and runtime via `request.runtime`.691 handler: `Callable` to execute the tool (can be called multiple times).692693 Returns:694 `ToolMessage` or `Command` (the final result).695696 The handler `Callable` can be invoked multiple times for retry logic.697698 Each call to handler is independent and stateless.699700 Examples:701 !!! example "Modify request before execution"702703 ```python704 def wrap_tool_call(self, request, handler):705 modified_call = {706 **request.tool_call,707 "args": {708 **request.tool_call["args"],709 "value": request.tool_call["args"]["value"] * 2,710 },711 }712 request = request.override(tool_call=modified_call)713 return handler(request)714 ```715716 !!! example "Retry on error (call handler multiple times)"717718 ```python719 def wrap_tool_call(self, request, handler):720 for attempt in range(3):721 try:722 result = handler(request)723 if is_valid(result):724 return result725 except Exception:726 if attempt == 2:727 raise728 return result729 ```730731 !!! example "Conditional retry based on response"732733 ```python734 def wrap_tool_call(self, request, handler):735 for attempt in range(3):736 result = handler(request)737 if isinstance(result, ToolMessage) and result.status != "error":738 return result739 if attempt < 2:740 continue741 return result742 ```743 """744 msg = (745 "Synchronous implementation of wrap_tool_call is not available. "746 "You are likely encountering this error because you defined only the async version "747 "(awrap_tool_call) and invoked your agent in a synchronous context "748 "(e.g., using `stream()` or `invoke()`). "749 "To resolve this, either: "750 "(1) subclass AgentMiddleware and implement the synchronous wrap_tool_call method, "751 "(2) use the @wrap_tool_call decorator on a standalone sync function, or "752 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."753 )754 raise NotImplementedError(msg)755756 async def awrap_tool_call(757 self,758 request: ToolCallRequest,759 handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],760 ) -> ToolMessage | Command[Any]:761 """Intercept and control async tool execution via handler callback.762763 The handler callback executes the tool call and returns a `ToolMessage` or764 `Command`. Middleware can call the handler multiple times for retry logic, skip765 calling it to short-circuit, or modify the request/response. Multiple middleware766 compose with first in list as outermost layer.767768 Args:769 request: Tool call request with call `dict`, `BaseTool`, state, and runtime.770771 Access state via `request.state` and runtime via `request.runtime`.772 handler: Async callable to execute the tool and returns `ToolMessage` or773 `Command`.774775 Call this to execute the tool.776777 Can be called multiple times for retry logic.778779 Can skip calling it to short-circuit.780781 Returns:782 `ToolMessage` or `Command` (the final result).783784 The handler `Callable` can be invoked multiple times for retry logic.785786 Each call to handler is independent and stateless.787788 Examples:789 !!! example "Async retry on error"790791 ```python792 async def awrap_tool_call(self, request, handler):793 for attempt in range(3):794 try:795 result = await handler(request)796 if is_valid(result):797 return result798 except Exception:799 if attempt == 2:800 raise801 return result802 ```803804 ```python805 async def awrap_tool_call(self, request, handler):806 if cached := await get_cache_async(request):807 return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])808 result = await handler(request)809 await save_cache_async(request, result)810 return result811 ```812 """813 msg = (814 "Asynchronous implementation of awrap_tool_call is not available. "815 "You are likely encountering this error because you defined only the sync version "816 "(wrap_tool_call) and invoked your agent in an asynchronous context "817 "(e.g., using `astream()` or `ainvoke()`). "818 "To resolve this, either: "819 "(1) subclass AgentMiddleware and implement the asynchronous awrap_tool_call method, "820 "(2) use the @wrap_tool_call decorator on a standalone async function, or "821 "(3) invoke your agent synchronously using `stream()` or `invoke()`."822 )823 raise NotImplementedError(msg)824825826_SyncCallableWithStateAndRuntime = Callable[827 [StateT_contra, Runtime[ContextT]], dict[str, Any] | Command[Any] | None828]829_AsyncCallableWithStateAndRuntime = Callable[830 [StateT_contra, Runtime[ContextT]], Awaitable[dict[str, Any] | Command[Any] | None]831]832_CallableWithStateAndRuntime = (833 _SyncCallableWithStateAndRuntime[StateT_contra, ContextT]834 | _AsyncCallableWithStateAndRuntime[StateT_contra, ContextT]835)836837_SyncCallableReturningSystemMessage = Callable[[ModelRequest[ContextT]], str | SystemMessage]838_AsyncCallableReturningSystemMessage = Callable[839 [ModelRequest[ContextT]], Awaitable[str | SystemMessage]840]841_CallableReturningSystemMessage = (842 _SyncCallableReturningSystemMessage[ContextT] | _AsyncCallableReturningSystemMessage[ContextT]843)844845# Sync/async signatures for `wrap_model_call` interception; see `@wrap_model_call`.846_SyncCallableReturningModelResponse = Callable[847 [ModelRequest[ContextT], Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]]],848 ModelCallResult,849]850_AsyncCallableReturningModelResponse = Callable[851 [852 ModelRequest[ContextT],853 Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],854 ],855 Awaitable[ModelCallResult],856]857_CallableReturningModelResponse = (858 _SyncCallableReturningModelResponse[ContextT, ResponseT]859 | _AsyncCallableReturningModelResponse[ContextT, ResponseT]860)861862# Sync/async signatures for `wrap_tool_call` interception; see `@wrap_tool_call`.863_SyncCallableReturningToolResponse = Callable[864 [ToolCallRequest, Callable[[ToolCallRequest], ToolMessage | Command[Any]]],865 ToolMessage | Command[Any],866]867_AsyncCallableReturningToolResponse = Callable[868 [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],869 Awaitable[ToolMessage | Command[Any]],870]871_CallableReturningToolResponse = (872 _SyncCallableReturningToolResponse | _AsyncCallableReturningToolResponse873)874875876CallableT = TypeVar("CallableT", bound=Callable[..., Any])877878879def hook_config(880 *,881 can_jump_to: list[JumpTo] | None = None,882) -> Callable[[CallableT], CallableT]:883 """Decorator to configure hook behavior in middleware methods.884885 Use this decorator on `before_model` or `after_model` methods in middleware classes886 to configure their behavior. Currently supports specifying which destinations they887 can jump to, which establishes conditional edges in the agent graph.888889 Args:890 can_jump_to: Optional list of valid jump destinations.891892 Can be:893894 - `'tools'`: Jump to the tools node895 - `'model'`: Jump back to the model node896 - `'end'`: Jump to the end of the graph897898 Returns:899 Decorator function that marks the method with configuration metadata.900901 Examples:902 !!! example "Using decorator on a class method"903904 ```python905 class MyMiddleware(AgentMiddleware):906 @hook_config(can_jump_to=["end", "model"])907 def before_model(self, state: AgentState) -> dict[str, Any] | None:908 if some_condition(state):909 return {"jump_to": "end"}910 return None911 ```912913 Alternative: Use the `can_jump_to` parameter in `before_model`/`after_model`914 decorators:915916 ```python917 @before_model(can_jump_to=["end"])918 def conditional_middleware(state: AgentState) -> dict[str, Any] | None:919 if should_exit(state):920 return {"jump_to": "end"}921 return None922 ```923 """924925 def decorator(func: CallableT) -> CallableT:926 if can_jump_to is not None:927 func.__can_jump_to__ = can_jump_to # type: ignore[attr-defined]928 return func929930 return decorator931932933@overload934def before_model(935 func: _CallableWithStateAndRuntime[StateT, ContextT],936) -> AgentMiddleware[StateT, ContextT]: ...937938939@overload940def before_model(941 func: None = None,942 *,943 state_schema: type[StateT] | None = None,944 tools: list[BaseTool] | None = None,945 can_jump_to: list[JumpTo] | None = None,946 name: str | None = None,947) -> Callable[948 [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]949]: ...950951952def before_model(953 func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,954 *,955 state_schema: type[StateT] | None = None,956 tools: list[BaseTool] | None = None,957 can_jump_to: list[JumpTo] | None = None,958 name: str | None = None,959) -> (960 Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]961 | AgentMiddleware[StateT, ContextT]962):963 """Decorator used to dynamically create a middleware with the `before_model` hook.964965 Args:966 func: The function to be decorated.967968 Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime969 context970 state_schema: Optional custom state schema type.971972 If not provided, uses the default `AgentState` schema.973 tools: Optional list of additional tools to register with this middleware.974 can_jump_to: Optional list of valid jump destinations for conditional edges.975976 Valid values are: `'tools'`, `'model'`, `'end'`977 name: Optional name for the generated middleware class.978979 If not provided, uses the decorated function's name.980981 Returns:982 Either an `AgentMiddleware` instance (if func is provided directly) or a983 decorator function that can be applied to a function it is wrapping.984985 The decorated function should return:986987 - `dict[str, Any]` - State updates to merge into the agent state988 - `Command` - A command to control flow (e.g., jump to different node)989 - `None` - No state updates or flow control990991 Examples:992 !!! example "Basic usage"993994 ```python995 @before_model996 def log_before_model(state: AgentState, runtime: Runtime) -> None:997 print(f"About to call model with {len(state['messages'])} messages")998 ```9991000 !!! example "With conditional jumping"10011002 ```python1003 @before_model(can_jump_to=["end"])1004 def conditional_before_model(1005 state: AgentState, runtime: Runtime1006 ) -> dict[str, Any] | None:1007 if some_condition(state):1008 return {"jump_to": "end"}1009 return None1010 ```10111012 !!! example "With custom state schema"10131014 Use a custom state schema when your middleware needs to read or write additional1015 state fields that aren't part of the default agent state.10161017 ```python1018 @before_model(state_schema=MyCustomState)1019 def custom_before_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1020 return {"custom_field": "updated_value"}1021 ```10221023 !!! example "Streaming custom events before model call"10241025 Use `runtime.stream_writer` to emit custom events before each model invocation.1026 Events are received when streaming with `stream_mode="custom"`.10271028 ```python1029 @before_model1030 async def notify_model_call(state: AgentState, runtime: Runtime) -> None:1031 '''Notify user before model is called.'''1032 runtime.stream_writer(1033 {1034 "type": "status",1035 "message": "Thinking...",1036 }1037 )1038 ```1039 """10401041 def decorator(1042 func: _CallableWithStateAndRuntime[StateT, ContextT],1043 ) -> AgentMiddleware[StateT, ContextT]:1044 is_async = iscoroutinefunction(func)10451046 func_can_jump_to = (1047 can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1048 )10491050 if is_async:10511052 async def async_wrapped(1053 _self: AgentMiddleware[StateT, ContextT],1054 state: StateT,1055 runtime: Runtime[ContextT],1056 ) -> dict[str, Any] | Command[Any] | None:1057 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1058 # cannot narrow this sync-or-async callable union.1059 return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1060 state, runtime1061 )10621063 # Preserve can_jump_to metadata on the wrapped function1064 if func_can_jump_to:1065 async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]10661067 middleware_name = name or cast(1068 "str", getattr(func, "__name__", "BeforeModelMiddleware")1069 )10701071 # `type(...)` builds the correct middleware subclass at runtime, but1072 # type checkers cannot infer its generic `AgentMiddleware` parameters.1073 return cast(1074 "AgentMiddleware[StateT, ContextT]",1075 type(1076 middleware_name,1077 (AgentMiddleware,),1078 {1079 "state_schema": state_schema or AgentState,1080 "tools": tools or [],1081 "abefore_model": async_wrapped,1082 },1083 )(),1084 )10851086 def wrapped(1087 _self: AgentMiddleware[StateT, ContextT],1088 state: StateT,1089 runtime: Runtime[ContextT],1090 ) -> dict[str, Any] | Command[Any] | None:1091 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1092 # cannot narrow this sync-or-async callable union.1093 return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)10941095 # Preserve can_jump_to metadata on the wrapped function1096 if func_can_jump_to:1097 wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]10981099 # Use function name as default if no name provided1100 middleware_name = name or cast("str", getattr(func, "__name__", "BeforeModelMiddleware"))11011102 # `type(...)` builds the correct middleware subclass at runtime, but1103 # type checkers cannot infer its generic `AgentMiddleware` parameters.1104 return cast(1105 "AgentMiddleware[StateT, ContextT]",1106 type(1107 middleware_name,1108 (AgentMiddleware,),1109 {1110 "state_schema": state_schema or AgentState,1111 "tools": tools or [],1112 "before_model": wrapped,1113 },1114 )(),1115 )11161117 if func is not None:1118 return decorator(func)1119 return decorator112011211122@overload1123def after_model(1124 func: _CallableWithStateAndRuntime[StateT, ContextT],1125) -> AgentMiddleware[StateT, ContextT]: ...112611271128@overload1129def after_model(1130 func: None = None,1131 *,1132 state_schema: type[StateT] | None = None,1133 tools: list[BaseTool] | None = None,1134 can_jump_to: list[JumpTo] | None = None,1135 name: str | None = None,1136) -> Callable[1137 [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]1138]: ...113911401141def after_model(1142 func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,1143 *,1144 state_schema: type[StateT] | None = None,1145 tools: list[BaseTool] | None = None,1146 can_jump_to: list[JumpTo] | None = None,1147 name: str | None = None,1148) -> (1149 Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]1150 | AgentMiddleware[StateT, ContextT]1151):1152 """Decorator used to dynamically create a middleware with the `after_model` hook.11531154 Args:1155 func: The function to be decorated.11561157 Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime1158 context1159 state_schema: Optional custom state schema type.11601161 If not provided, uses the default `AgentState` schema.1162 tools: Optional list of additional tools to register with this middleware.1163 can_jump_to: Optional list of valid jump destinations for conditional edges.11641165 Valid values are: `'tools'`, `'model'`, `'end'`1166 name: Optional name for the generated middleware class.11671168 If not provided, uses the decorated function's name.11691170 Returns:1171 Either an `AgentMiddleware` instance (if func is provided) or a decorator1172 function that can be applied to a function.11731174 The decorated function should return:11751176 - `dict[str, Any]` - State updates to merge into the agent state1177 - `Command` - A command to control flow (e.g., jump to different node)1178 - `None` - No state updates or flow control11791180 Examples:1181 !!! example "Basic usage for logging model responses"11821183 ```python1184 @after_model1185 def log_latest_message(state: AgentState, runtime: Runtime) -> None:1186 print(state["messages"][-1].content)1187 ```11881189 !!! example "With custom state schema"11901191 Use a custom state schema when your middleware needs to read or write additional1192 state fields that aren't part of the default agent state.11931194 ```python1195 @after_model(state_schema=MyCustomState, name="MyAfterModelMiddleware")1196 def custom_after_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1197 return {"custom_field": "updated_after_model"}1198 ```11991200 !!! example "Streaming custom events after model call"12011202 Use `runtime.stream_writer` to emit custom events after model responds.1203 Events are received when streaming with `stream_mode="custom"`.12041205 ```python1206 @after_model1207 async def notify_model_response(state: AgentState, runtime: Runtime) -> None:1208 '''Notify user after model has responded.'''1209 last_message = state["messages"][-1]1210 has_tool_calls = hasattr(last_message, "tool_calls") and last_message.tool_calls1211 runtime.stream_writer(1212 {1213 "type": "status",1214 "message": "Using tools..." if has_tool_calls else "Response ready!",1215 }1216 )1217 ```1218 """12191220 def decorator(1221 func: _CallableWithStateAndRuntime[StateT, ContextT],1222 ) -> AgentMiddleware[StateT, ContextT]:1223 is_async = iscoroutinefunction(func)1224 # Extract can_jump_to from decorator parameter or from function metadata1225 func_can_jump_to = (1226 can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1227 )12281229 if is_async:12301231 async def async_wrapped(1232 _self: AgentMiddleware[StateT, ContextT],1233 state: StateT,1234 runtime: Runtime[ContextT],1235 ) -> dict[str, Any] | Command[Any] | None:1236 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1237 # cannot narrow this sync-or-async callable union.1238 return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1239 state, runtime1240 )12411242 # Preserve can_jump_to metadata on the wrapped function1243 if func_can_jump_to:1244 async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]12451246 middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))12471248 # `type(...)` builds the correct middleware subclass at runtime, but1249 # type checkers cannot infer its generic `AgentMiddleware` parameters.1250 return cast(1251 "AgentMiddleware[StateT, ContextT]",1252 type(1253 middleware_name,1254 (AgentMiddleware,),1255 {1256 "state_schema": state_schema or AgentState,1257 "tools": tools or [],1258 "aafter_model": async_wrapped,1259 },1260 )(),1261 )12621263 def wrapped(1264 _self: AgentMiddleware[StateT, ContextT],1265 state: StateT,1266 runtime: Runtime[ContextT],1267 ) -> dict[str, Any] | Command[Any] | None:1268 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1269 # cannot narrow this sync-or-async callable union.1270 return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)12711272 # Preserve can_jump_to metadata on the wrapped function1273 if func_can_jump_to:1274 wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]12751276 # Use function name as default if no name provided1277 middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))12781279 # `type(...)` builds the correct middleware subclass at runtime, but1280 # type checkers cannot infer its generic `AgentMiddleware` parameters.1281 return cast(1282 "AgentMiddleware[StateT, ContextT]",1283 type(1284 middleware_name,1285 (AgentMiddleware,),1286 {1287 "state_schema": state_schema or AgentState,1288 "tools": tools or [],1289 "after_model": wrapped,1290 },1291 )(),1292 )12931294 if func is not None:1295 return decorator(func)1296 return decorator129712981299@overload1300def before_agent(1301 func: _CallableWithStateAndRuntime[StateT, ContextT],1302) -> AgentMiddleware[StateT, ContextT]: ...130313041305@overload1306def before_agent(1307 func: None = None,1308 *,1309 state_schema: type[StateT] | None = None,1310 tools: list[BaseTool] | None = None,1311 can_jump_to: list[JumpTo] | None = None,1312 name: str | None = None,1313) -> Callable[1314 [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]1315]: ...131613171318def before_agent(1319 func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,1320 *,1321 state_schema: type[StateT] | None = None,1322 tools: list[BaseTool] | None = None,1323 can_jump_to: list[JumpTo] | None = None,1324 name: str | None = None,1325) -> (1326 Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]1327 | AgentMiddleware[StateT, ContextT]1328):1329 """Decorator used to dynamically create a middleware with the `before_agent` hook.13301331 Args:1332 func: The function to be decorated.13331334 Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime1335 context1336 state_schema: Optional custom state schema type.13371338 If not provided, uses the default `AgentState` schema.1339 tools: Optional list of additional tools to register with this middleware.1340 can_jump_to: Optional list of valid jump destinations for conditional edges.13411342 Valid values are: `'tools'`, `'model'`, `'end'`1343 name: Optional name for the generated middleware class.13441345 If not provided, uses the decorated function's name.13461347 Returns:1348 Either an `AgentMiddleware` instance (if func is provided directly) or a1349 decorator function that can be applied to a function it is wrapping.13501351 The decorated function should return:13521353 - `dict[str, Any]` - State updates to merge into the agent state1354 - `Command` - A command to control flow (e.g., jump to different node)1355 - `None` - No state updates or flow control13561357 Examples:1358 !!! example "Basic usage"13591360 ```python1361 @before_agent1362 def log_before_agent(state: AgentState, runtime: Runtime) -> None:1363 print(f"Starting agent with {len(state['messages'])} messages")1364 ```13651366 !!! example "With conditional jumping"13671368 ```python1369 @before_agent(can_jump_to=["end"])1370 def conditional_before_agent(1371 state: AgentState, runtime: Runtime1372 ) -> dict[str, Any] | None:1373 if some_condition(state):1374 return {"jump_to": "end"}1375 return None1376 ```13771378 !!! example "With custom state schema"13791380 Use a custom state schema when your middleware needs to read or write additional1381 state fields that aren't part of the default agent state.13821383 ```python1384 @before_agent(state_schema=MyCustomState)1385 def custom_before_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1386 return {"custom_field": "initialized_value"}1387 ```13881389 !!! example "Streaming custom events"13901391 Use `runtime.stream_writer` to emit custom events during agent execution.1392 Events are received when streaming with `stream_mode="custom"`.13931394 ```python1395 from langchain.agents import create_agent1396 from langchain.agents.middleware import before_agent, AgentState1397 from langchain.messages import HumanMessage1398 from langgraph.runtime import Runtime139914001401 @before_agent1402 async def notify_start(state: AgentState, runtime: Runtime) -> None:1403 '''Notify user that agent is starting.'''1404 runtime.stream_writer(1405 {1406 "type": "status",1407 "message": "Initializing agent session...",1408 }1409 )1410 # Perform prerequisite tasks here1411 runtime.stream_writer({"type": "status", "message": "Agent ready!"})141214131414 agent = create_agent(1415 model="openai:gpt-5.2",1416 tools=[...],1417 middleware=[notify_start],1418 )14191420 # Consume with stream_mode="custom" to receive events1421 async for mode, event in agent.astream(1422 {"messages": [HumanMessage("Hello")]},1423 stream_mode=["updates", "custom"],1424 ):1425 if mode == "custom":1426 print(f"Status: {event}")1427 ```1428 """14291430 def decorator(1431 func: _CallableWithStateAndRuntime[StateT, ContextT],1432 ) -> AgentMiddleware[StateT, ContextT]:1433 is_async = iscoroutinefunction(func)14341435 func_can_jump_to = (1436 can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1437 )14381439 if is_async:14401441 async def async_wrapped(1442 _self: AgentMiddleware[StateT, ContextT],1443 state: StateT,1444 runtime: Runtime[ContextT],1445 ) -> dict[str, Any] | Command[Any] | None:1446 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1447 # cannot narrow this sync-or-async callable union.1448 return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1449 state, runtime1450 )14511452 # Preserve can_jump_to metadata on the wrapped function1453 if func_can_jump_to:1454 async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]14551456 middleware_name = name or cast(1457 "str", getattr(func, "__name__", "BeforeAgentMiddleware")1458 )14591460 # `type(...)` builds the correct middleware subclass at runtime, but1461 # type checkers cannot infer its generic `AgentMiddleware` parameters.1462 return cast(1463 "AgentMiddleware[StateT, ContextT]",1464 type(1465 middleware_name,1466 (AgentMiddleware,),1467 {1468 "state_schema": state_schema or AgentState,1469 "tools": tools or [],1470 "abefore_agent": async_wrapped,1471 },1472 )(),1473 )14741475 def wrapped(1476 _self: AgentMiddleware[StateT, ContextT],1477 state: StateT,1478 runtime: Runtime[ContextT],1479 ) -> dict[str, Any] | Command[Any] | None:1480 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1481 # cannot narrow this sync-or-async callable union.1482 return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)14831484 # Preserve can_jump_to metadata on the wrapped function1485 if func_can_jump_to:1486 wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]14871488 # Use function name as default if no name provided1489 middleware_name = name or cast("str", getattr(func, "__name__", "BeforeAgentMiddleware"))14901491 # `type(...)` builds the correct middleware subclass at runtime, but1492 # type checkers cannot infer its generic `AgentMiddleware` parameters.1493 return cast(1494 "AgentMiddleware[StateT, ContextT]",1495 type(1496 middleware_name,1497 (AgentMiddleware,),1498 {1499 "state_schema": state_schema or AgentState,1500 "tools": tools or [],1501 "before_agent": wrapped,1502 },1503 )(),1504 )15051506 if func is not None:1507 return decorator(func)1508 return decorator150915101511@overload1512def after_agent(1513 func: _CallableWithStateAndRuntime[StateT, ContextT],1514) -> AgentMiddleware[StateT, ContextT]: ...151515161517@overload1518def after_agent(1519 func: None = None,1520 *,1521 state_schema: type[StateT] | None = None,1522 tools: list[BaseTool] | None = None,1523 can_jump_to: list[JumpTo] | None = None,1524 name: str | None = None,1525) -> Callable[1526 [_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]1527]: ...152815291530def after_agent(1531 func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,1532 *,1533 state_schema: type[StateT] | None = None,1534 tools: list[BaseTool] | None = None,1535 can_jump_to: list[JumpTo] | None = None,1536 name: str | None = None,1537) -> (1538 Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]1539 | AgentMiddleware[StateT, ContextT]1540):1541 """Decorator used to dynamically create a middleware with the `after_agent` hook.15421543 Async version is `aafter_agent`.15441545 Args:1546 func: The function to be decorated.15471548 Must accept: `state: StateT, runtime: Runtime[ContextT]` - State and runtime1549 context1550 state_schema: Optional custom state schema type.15511552 If not provided, uses the default `AgentState` schema.1553 tools: Optional list of additional tools to register with this middleware.1554 can_jump_to: Optional list of valid jump destinations for conditional edges.15551556 Valid values are: `'tools'`, `'model'`, `'end'`1557 name: Optional name for the generated middleware class.15581559 If not provided, uses the decorated function's name.15601561 Returns:1562 Either an `AgentMiddleware` instance (if func is provided) or a decorator1563 function that can be applied to a function.15641565 The decorated function should return:15661567 - `dict[str, Any]` - State updates to merge into the agent state1568 - `Command` - A command to control flow (e.g., jump to different node)1569 - `None` - No state updates or flow control15701571 Examples:1572 !!! example "Basic usage for logging agent completion"15731574 ```python1575 @after_agent1576 def log_completion(state: AgentState, runtime: Runtime) -> None:1577 print(f"Agent completed with {len(state['messages'])} messages")1578 ```15791580 !!! example "With custom state schema"15811582 Use a custom state schema when your middleware needs to read or write additional1583 state fields that aren't part of the default agent state.15841585 ```python1586 @after_agent(state_schema=MyCustomState, name="MyAfterAgentMiddleware")1587 def custom_after_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:1588 return {"custom_field": "finalized_value"}1589 ```15901591 !!! example "Streaming custom events on completion"15921593 Use `runtime.stream_writer` to emit custom events when agent completes.1594 Events are received when streaming with `stream_mode="custom"`.15951596 ```python1597 @after_agent1598 async def notify_completion(state: AgentState, runtime: Runtime) -> None:1599 '''Notify user that agent has completed.'''1600 runtime.stream_writer(1601 {1602 "type": "status",1603 "message": "Agent execution complete!",1604 "total_messages": len(state["messages"]),1605 }1606 )1607 ```1608 """16091610 def decorator(1611 func: _CallableWithStateAndRuntime[StateT, ContextT],1612 ) -> AgentMiddleware[StateT, ContextT]:1613 is_async = iscoroutinefunction(func)1614 # Extract can_jump_to from decorator parameter or from function metadata1615 func_can_jump_to = (1616 can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])1617 )16181619 if is_async:16201621 async def async_wrapped(1622 _self: AgentMiddleware[StateT, ContextT],1623 state: StateT,1624 runtime: Runtime[ContextT],1625 ) -> dict[str, Any] | Command[Any] | None:1626 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1627 # cannot narrow this sync-or-async callable union.1628 return await cast("_AsyncCallableWithStateAndRuntime[StateT, ContextT]", func)(1629 state, runtime1630 )16311632 # Preserve can_jump_to metadata on the wrapped function1633 if func_can_jump_to:1634 async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]16351636 middleware_name = name or cast("str", getattr(func, "__name__", "AfterAgentMiddleware"))16371638 # `type(...)` builds the correct middleware subclass at runtime, but1639 # type checkers cannot infer its generic `AgentMiddleware` parameters.1640 return cast(1641 "AgentMiddleware[StateT, ContextT]",1642 type(1643 middleware_name,1644 (AgentMiddleware,),1645 {1646 "state_schema": state_schema or AgentState,1647 "tools": tools or [],1648 "aafter_agent": async_wrapped,1649 },1650 )(),1651 )16521653 def wrapped(1654 _self: AgentMiddleware[StateT, ContextT],1655 state: StateT,1656 runtime: Runtime[ContextT],1657 ) -> dict[str, Any] | Command[Any] | None:1658 # `iscoroutinefunction` narrows `func` at runtime, but type checkers1659 # cannot narrow this sync-or-async callable union.1660 return cast("_SyncCallableWithStateAndRuntime[StateT, ContextT]", func)(state, runtime)16611662 # Preserve can_jump_to metadata on the wrapped function1663 if func_can_jump_to:1664 wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]16651666 # Use function name as default if no name provided1667 middleware_name = name or cast("str", getattr(func, "__name__", "AfterAgentMiddleware"))16681669 # `type(...)` builds the correct middleware subclass at runtime, but1670 # type checkers cannot infer its generic `AgentMiddleware` parameters.1671 return cast(1672 "AgentMiddleware[StateT, ContextT]",1673 type(1674 middleware_name,1675 (AgentMiddleware,),1676 {1677 "state_schema": state_schema or AgentState,1678 "tools": tools or [],1679 "after_agent": wrapped,1680 },1681 )(),1682 )16831684 if func is not None:1685 return decorator(func)1686 return decorator168716881689@overload1690def dynamic_prompt(1691 func: _CallableReturningSystemMessage[ContextT],1692) -> AgentMiddleware[StateT, ContextT]: ...169316941695@overload1696def dynamic_prompt(1697 func: None = None,1698) -> Callable[1699 [_CallableReturningSystemMessage[ContextT]],1700 AgentMiddleware[StateT, ContextT],1701]: ...170217031704def dynamic_prompt(1705 func: _CallableReturningSystemMessage[ContextT] | None = None,1706) -> (1707 Callable[1708 [_CallableReturningSystemMessage[ContextT]],1709 AgentMiddleware[StateT, ContextT],1710 ]1711 | AgentMiddleware[StateT, ContextT]1712):1713 """Decorator used to dynamically generate system prompts for the model.17141715 This is a convenience decorator that creates middleware using `wrap_model_call`1716 specifically for dynamic prompt generation. The decorated function should return1717 a string that will be set as the system prompt for the model request.17181719 Args:1720 func: The function to be decorated.17211722 Must accept: `request: ModelRequest` - Model request (contains state and1723 runtime)17241725 Returns:1726 Either an `AgentMiddleware` instance (if func is provided) or a decorator1727 function that can be applied to a function.17281729 The decorated function should return:1730 - `str` – The system prompt string to use for the model request1731 - `SystemMessage` – A complete system message to use for the model request17321733 Examples:1734 Basic usage with dynamic content:17351736 ```python1737 @dynamic_prompt1738 def my_prompt(request: ModelRequest) -> str:1739 user_name = request.runtime.context.get("user_name", "User")1740 return f"You are a helpful assistant helping {user_name}."1741 ```17421743 Using state to customize the prompt:17441745 ```python1746 @dynamic_prompt1747 def context_aware_prompt(request: ModelRequest) -> str:1748 msg_count = len(request.state["messages"])1749 if msg_count > 10:1750 return "You are in a long conversation. Be concise."1751 return "You are a helpful assistant."1752 ```17531754 Using with agent:17551756 ```python1757 agent = create_agent(model, middleware=[my_prompt])1758 ```1759 """17601761 def decorator(1762 func: _CallableReturningSystemMessage[ContextT],1763 ) -> AgentMiddleware[StateT, ContextT]:1764 is_async = iscoroutinefunction(func)17651766 if is_async:17671768 async def async_wrapped(1769 _self: AgentMiddleware[StateT, ContextT],1770 request: ModelRequest[ContextT],1771 handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[Any]]],1772 ) -> ModelResponse[Any] | AIMessage:1773 prompt = await cast("_AsyncCallableReturningSystemMessage[ContextT]", func)(request)1774 if isinstance(prompt, SystemMessage):1775 request = request.override(system_message=prompt)1776 else:1777 request = request.override(system_message=SystemMessage(content=prompt))1778 return await handler(request)17791780 middleware_name = cast("str", getattr(func, "__name__", "DynamicPromptMiddleware"))17811782 # `type(...)` builds the correct middleware subclass at runtime, but1783 # type checkers cannot infer its generic `AgentMiddleware` parameters.1784 return cast(1785 "AgentMiddleware[StateT, ContextT]",1786 type(1787 middleware_name,1788 (AgentMiddleware,),1789 {1790 "state_schema": AgentState,1791 "tools": [],1792 "awrap_model_call": async_wrapped,1793 },1794 )(),1795 )17961797 def wrapped(1798 _self: AgentMiddleware[StateT, ContextT],1799 request: ModelRequest[ContextT],1800 handler: Callable[[ModelRequest[ContextT]], ModelResponse[Any]],1801 ) -> ModelResponse[Any] | AIMessage:1802 prompt = cast("_SyncCallableReturningSystemMessage[ContextT]", func)(request)1803 if isinstance(prompt, SystemMessage):1804 request = request.override(system_message=prompt)1805 else:1806 request = request.override(system_message=SystemMessage(content=prompt))1807 return handler(request)18081809 async def async_wrapped_from_sync(1810 _self: AgentMiddleware[StateT, ContextT],1811 request: ModelRequest[ContextT],1812 handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[Any]]],1813 ) -> ModelResponse[Any] | AIMessage:1814 # Delegate to sync function1815 prompt = cast("_SyncCallableReturningSystemMessage[ContextT]", func)(request)1816 if isinstance(prompt, SystemMessage):1817 request = request.override(system_message=prompt)1818 else:1819 request = request.override(system_message=SystemMessage(content=prompt))1820 return await handler(request)18211822 middleware_name = cast("str", getattr(func, "__name__", "DynamicPromptMiddleware"))18231824 # `type(...)` builds the correct middleware subclass at runtime, but1825 # type checkers cannot infer its generic `AgentMiddleware` parameters.1826 return cast(1827 "AgentMiddleware[StateT, ContextT]",1828 type(1829 middleware_name,1830 (AgentMiddleware,),1831 {1832 "state_schema": AgentState,1833 "tools": [],1834 "wrap_model_call": wrapped,1835 "awrap_model_call": async_wrapped_from_sync,1836 },1837 )(),1838 )18391840 if func is not None:1841 return decorator(func)1842 return decorator184318441845@overload1846def wrap_model_call(1847 func: _CallableReturningModelResponse[ContextT, ResponseT],1848) -> AgentMiddleware[StateT, ContextT]: ...184918501851@overload1852def wrap_model_call(1853 func: None = None,1854 *,1855 state_schema: type[StateT] | None = None,1856 tools: list[BaseTool] | None = None,1857 name: str | None = None,1858) -> Callable[1859 [_CallableReturningModelResponse[ContextT, ResponseT]],1860 AgentMiddleware[StateT, ContextT],1861]: ...186218631864def wrap_model_call(1865 func: _CallableReturningModelResponse[ContextT, ResponseT] | None = None,1866 *,1867 state_schema: type[StateT] | None = None,1868 tools: list[BaseTool] | None = None,1869 name: str | None = None,1870) -> (1871 Callable[1872 [_CallableReturningModelResponse[ContextT, ResponseT]],1873 AgentMiddleware[StateT, ContextT],1874 ]1875 | AgentMiddleware[StateT, ContextT]1876):1877 """Create middleware with `wrap_model_call` hook from a function.18781879 Converts a function with handler callback into middleware that can intercept model1880 calls, implement retry logic, handle errors, and rewrite responses.18811882 Args:1883 func: Function accepting (request, handler) that calls handler(request)1884 to execute the model and returns `ModelResponse` or `AIMessage`.18851886 Request contains state and runtime.1887 state_schema: Custom state schema.18881889 Defaults to `AgentState`.1890 tools: Additional tools to register with this middleware.1891 name: Middleware class name.18921893 Defaults to function name.18941895 Returns:1896 `AgentMiddleware` instance if func provided, otherwise a decorator.18971898 Examples:1899 !!! example "Basic retry logic"19001901 ```python1902 @wrap_model_call1903 def retry_on_error(request, handler):1904 max_retries = 31905 for attempt in range(max_retries):1906 try:1907 return handler(request)1908 except Exception:1909 if attempt == max_retries - 1:1910 raise1911 ```19121913 !!! example "Model fallback"19141915 ```python1916 @wrap_model_call1917 def fallback_model(request, handler):1918 # Try primary model1919 try:1920 return handler(request)1921 except Exception:1922 pass19231924 # Try fallback model1925 request = request.override(model=fallback_model_instance)1926 return handler(request)1927 ```19281929 !!! example "Rewrite response content (full `ModelResponse`)"19301931 ```python1932 @wrap_model_call1933 def uppercase_responses(request, handler):1934 response = handler(request)1935 ai_msg = response.result[0]1936 return ModelResponse(1937 result=[AIMessage(content=ai_msg.content.upper())],1938 structured_response=response.structured_response,1939 )1940 ```19411942 !!! example "Simple `AIMessage` return (converted automatically)"19431944 ```python1945 @wrap_model_call1946 def simple_response(request, handler):1947 # AIMessage is automatically converted to ModelResponse1948 return AIMessage(content="Simple response")1949 ```1950 """19511952 def decorator(1953 func: _CallableReturningModelResponse[ContextT, ResponseT],1954 ) -> AgentMiddleware[StateT, ContextT]:1955 is_async = iscoroutinefunction(func)19561957 if is_async:19581959 async def async_wrapped(1960 _self: AgentMiddleware[StateT, ContextT],1961 request: ModelRequest[ContextT],1962 handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],1963 ) -> ModelCallResult[ResponseT]:1964 return await cast(1965 "_AsyncCallableReturningModelResponse[ContextT, ResponseT]", func1966 )(request, handler)19671968 middleware_name = name or cast(1969 "str", getattr(func, "__name__", "WrapModelCallMiddleware")1970 )19711972 # `type(...)` builds the correct middleware subclass at runtime, but1973 # type checkers cannot infer its generic `AgentMiddleware` parameters.1974 return cast(1975 "AgentMiddleware[StateT, ContextT]",1976 type(1977 middleware_name,1978 (AgentMiddleware,),1979 {1980 "state_schema": state_schema or AgentState,1981 "tools": tools or [],1982 "awrap_model_call": async_wrapped,1983 },1984 )(),1985 )19861987 def wrapped(1988 _self: AgentMiddleware[StateT, ContextT],1989 request: ModelRequest[ContextT],1990 handler: Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]],1991 ) -> ModelCallResult[ResponseT]:1992 return cast("_SyncCallableReturningModelResponse[ContextT, ResponseT]", func)(1993 request, handler1994 )19951996 middleware_name = name or cast("str", getattr(func, "__name__", "WrapModelCallMiddleware"))19971998 # `type(...)` builds the correct middleware subclass at runtime, but1999 # type checkers cannot infer its generic `AgentMiddleware` parameters.2000 return cast(
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