Creates a middleware instance with automatic schema inference.
createMiddleware<
TSchema extends StateDefinitionInit | undefined = undefined,
TContextSchema extends InteropZodObject | undefined = undefined,
TTools extends readonly ClientTool | ServerTool[] = readonly ClientTool | ServerTool[]
>(
config: __type
): AgentMiddleware<TSchema, TContextSchema, NormalizeContextSchema<TContextSchema>, TTools>| Name | Type | Description |
|---|---|---|
config* | __type | Middleware configuration |
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"));
}
},
});import { StateSchema, ReducedValue } from "@langchain/langgraph";
const historyMiddleware = createMiddleware({
name: "HistoryMiddleware",
stateSchema: new StateSchema({
count: z.number().default(0),
history: new ReducedValue(
z.array(z.string()).default(() => []),
{ inputSchema: z.string(), reducer: (current, next) => [...current, next] }
),
}),
beforeModel: async (state, runtime) => {
return { count: state.count + 1 };
},
});