LangGraph: Building an Agent Workflow That Knows When to Stop
The reviewer rejects the third draft. What should the agent do next?

The reviewer rejects the third draft. What should the agent do next?
Another attempt is easy to request. A useful workflow needs a harder decision: revise, ask a person, or stop. We'll build that decision into a small research-and-writing graph, then follow the draft through review, a real approval pause, and resumption.
Define a bounded graph
Graph topology constrains control flow; it does not make model output deterministic or correct. This example separates research, drafting, review, and human approval. Workers are injected functions: actual retrieval, model calls, credentials, and timeouts must be implemented separately.
Examples are illustrative, not claims of deployed production behavior.
Use compatible @langchain/langgraph 1.7 and Zod 4 releases in a separate server project. Current documentation uses StateSchema; Annotation belongs to LangGraph, not @langchain/core/messages. Each write increments the attempt counter. Review sees the latest draft, and three rejected drafts end as exhausted, never as approved.
// workflow.ts
import {
StateGraph, StateSchema, START, END, interrupt,
type BaseCheckpointSaver,
} from "@langchain/langgraph";
import * as z from "zod/v4";
const State = new StateSchema({
task: z.string().min(1),
research: z.string().default(""),
draft: z.string().default(""),
feedback: z.string().default(""),
attempts: z.number().int().nonnegative().default(0),
accepted: z.boolean().default(false),
outcome: z.enum(["pending", "approved", "rejected", "exhausted"]).default("pending"),
});
const Review = z.object({
accepted: z.boolean(),
feedback: z.string(),
});
export interface Workers {
research(task: string): Promise<string>;
write(input: {
task: string;
research: string;
previousDraft: string;
feedback: string;
attempt: number;
}): Promise<string>;
review(draft: string): Promise<z.infer<typeof Review>>;
}
export function buildWorkflow(workers: Workers, checkpointer: BaseCheckpointSaver) {
return new StateGraph(State)
.addNode("gather", async ({ task }) => ({
research: z.string().min(1).parse(await workers.research(task)),
}))
.addNode("write", async (state) => ({
draft: z.string().min(1).parse(await workers.write({
task: state.task,
research: state.research,
previousDraft: state.draft,
feedback: state.feedback,
attempt: state.attempts + 1,
})),
attempts: state.attempts + 1,
}))
.addNode("review", async ({ draft }) => Review.parse(await workers.review(draft)))
.addNode("approval", (state) => {
const approved = z.boolean().parse(interrupt({
question: "Approve this exact draft?",
draft: state.draft,
}));
return { outcome: approved ? "approved" as const : "rejected" as const };
})
.addNode("exhausted", () => ({ outcome: "exhausted" as const }))
.addEdge(START, "gather")
.addEdge("gather", "write")
.addEdge("write", "review")
.addConditionalEdges("review", (state) => {
if (state.accepted) return "approval";
return state.attempts >= 3 ? "exhausted" : "write";
})
.addEdge("approval", END)
.addEdge("exhausted", END)
.compile({ checkpointer });
}Follow a rejected draft around the loop: the writer gets both the previous text and the feedback, rather than starting blind. Acceptance takes a different edge into human approval. That distinction keeps a model review from quietly becoming permission to publish.
Pause and resume an authorized thread
The following deterministic fixtures demonstrate wiring only. interrupt() actually pauses execution; setting an approval boolean alone does not. Resume with Command and the same thread_id and checkpointer. The example's hardcoded approval is not an authorization mechanism.
// demo.ts: deterministic fixtures, not LLM or research results
import { Command, MemorySaver } from "@langchain/langgraph";
import { buildWorkflow } from "./workflow";
const graph = buildWorkflow({
research: async (task) => "Fixture notes for: " + task,
write: async ({ task, attempt }) => "Draft " + attempt + ": " + task,
review: async (draft) => ({
accepted: draft.startsWith("Draft 2:"),
feedback: "Fixture reviewer accepts the second draft.",
}),
}, new MemorySaver());
const config = {
configurable: { thread_id: "demo-task-1" },
recursionLimit: 20,
};
const paused = await graph.invoke({ task: "Document an API migration" }, config);
if (!("__interrupt__" in paused)) {
throw new Error("Expected the workflow to pause for approval.");
}
console.log(paused.__interrupt__);
// In a real app, obtain this decision from the authorized reviewer.
const finished = await graph.invoke(new Command({ resume: true }), config);
console.log(finished.outcome);Persistence across requests
MemorySaver survives calls only within its process. Keep a shared graph/checkpointer outside a request handler for local tests; use a durable supported checkpointer for restarts, replicas, and serverless deployments. Authenticate the caller and authorize thread ownership on both start and resume. A client-supplied thread ID is not a permission check.
Next.js streaming boundaries
Keep orchestration and credentials on the server. Validate HTTP inputs, propagate disconnect cancellation to workers, and stream deliberately selected events rather than raw internal state. A paused graph must produce an explicit approval-needed event, not success. POST-based streams require a streaming fetch client; native EventSource does not send POST bodies. Handle framing, proxy buffering, error events, and cancellation separately.
Verify failure paths
Test acceptance, rejection, exactly three failed drafts, malformed reviews, unauthorized resume, and recovery after restart. An interrupted node restarts from its beginning: avoid side effects before interrupt(), or make them idempotent. Put irreversible actions behind a separately authorized step after approval. A recursion limit is an additional graph guard, not a deadline or token budget.
The stopping rule is part of the design, not an error to hide. Keep approved, rejected, and exhausted outcomes distinct, and the person using the workflow can understand what happened without reading its internal state.