Middleware that throws ModelRefusalError when the model refuses.
Providers report a refusal, such as a safety-policy refusal, as a successful
response, so without this middleware the agent run ends as if it succeeded.
The middleware checks each model response for a refusal content block,
including refusals that fail to parse under a structured responseFormat.
It does not detect refusals the model writes as ordinary text.
List it after modelFallbackMiddleware so the fallback catches the
error and retries the request on the next model. modelRetryMiddleware does
not retry refusals.
modelRefusalMiddleware(
): AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[], readonly []>import {
createAgent,
modelFallbackMiddleware,
modelRefusalMiddleware,
} from "langchain";
const agent = createAgent({
model: "anthropic:claude-sonnet-5-5",
tools: [],
middleware: [
modelFallbackMiddleware("openai:gpt-6.1-sol"),
modelRefusalMiddleware(),
],
});