LangChain Middleware API


AgentMiddleware base class hook methods

MethodSignatureExecution frequencyReturn value
before_agent(state, runtime) → dict or None1 timeState update or None
abefore_agent(state, runtime) → dict or None1 timeState update or None
before_model(state, runtime) → dict or NonePer iterationState update or None
abefore_model(state, runtime) → dict or NonePer iterationState update or None
wrap_model_call(request, handler) → ModelResponse or AIMessagePer iterationModel call result
awrap_model_call(request, handler) → ModelResponse or AIMessagePer iterationModel call result
after_model(state, runtime) → dict or NonePer iterationState update or None
aafter_model(state, runtime) → dict or NonePer iterationState update or None
wrap_tool_call(request, handler) → ToolMessage or CommandPer tool callTool execution result
awrap_tool_call(request, handler) → ToolMessage or CommandPer tool callTool execution result
after_agent(state, runtime) → dict or None1 timeState update or None
aafter_agent(state, runtime) → dict or None1 timeState update or None

Decorator overview

DecoratorParametersDescription
@before_agentstate_schema, tools, can_jump_to, nameExecuted before the agent starts
@after_agentstate_schema, tools, can_jump_to, nameExecuted after the agent ends
@before_modelstate_schema, tools, can_jump_to, nameExecuted before model invocation
@after_modelstate_schema, tools, can_jump_to, nameExecuted after model invocation
@wrap_model_callstate_schema, tools, nameIntercept model execution
@wrap_tool_calltools, nameIntercept tool execution
@dynamic_promptNoneDynamically generate system prompt

ModelRequest key attributes

AttributeTypeDescription
modelBaseChatModelCurrent model
messageslist[AnyMessage]Message list (excluding system messages)
system_messageSystemMessage or NoneCurrent system message
toolslistAvailable tools list
tool_choiceAnyTool selection strategy
response_formatResponseFormat or NoneStructured output format
statedictAgent current state
runtimeRuntimeRuntime context

ModelRequest's override() method is used to create a new modified request:

Example

new_request = request.override(
    model=different_model,
    system_message=SystemMessage(content="new prompt"),
    tools=[new_tool],
)

ModelResponse structure

AttributeTypeDescription
resultlist[BaseMessage]Message list returned by the model
structured_responseAny or NoneStructured output result

Special return value ExtendedModelResponse

AttributeDescription
model_responseUnderlying ModelResponse
commandOptional Command object for additional state updates
Other extensions