Creates a middleware instance with automatic schema inference.
Middleware configuration
Optional
afterModel?: (The function to run after the model call. This function is called after the model is invoked and before any tools are called. It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.
Optional
afterModelJumpTo?: ("tools" | "model" | "end")[]Explitictly defines which targets are allowed to be jumped to from the afterModel
hook.
Optional
beforeModel?: (The function to run before the model call. This function is called before the model is invoked and before the modifyModelRequest
hook.
It allows to modify the state of the agent.
Optional
beforeModelJumpTo?: ("tools" | "model" | "end")[]Explitictly defines which targets are allowed to be jumped to from the beforeModel
hook.
Optional
contextSchema?: TContextSchemaThe schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:
Optional
modifyModelRequest?: (The function to modify the model request. This function is called after the beforeModel
hook of this middleware and before the model is invoked.
It allows to modify the model request before it is passed to the model.
The name of the middleware
Optional
stateSchema?: TSchemaThe schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:
Optional
tools?: any[]Additional tools registered by the middleware.
A middleware instance
const authMiddleware = createMiddleware({
name: "AuthMiddleware",
stateSchema: z.object({
isAuthenticated: z.boolean().default(false),
}),
contextSchema: z.object({
userId: z.string(),
}),
beforeModel: async (state, runtime, controls) => {
if (!state.isAuthenticated) {
return controls.terminate(new Error("Not authenticated"));
}
},
});
LangChain Agents