跳到正文
DEV Community· Aqib·· 1 小時前AI 評分65

LangGraph 規劃器/執行器智能體如何判斷何時停止

How a LangGraph Planner/Executor Agent Knows When to Stop

AI 導讀

作者以 LangGraph JavaScript 套件示範,透過狀態中的步數與重規劃計數,以及明確的路由規則,控制規劃器/執行器智能體何時停止。範例將最多執行步數設為 6、最多重規劃 2 次,達到上限或無法繼續時,由 finish 節點根據部分結果作答;recursion limit 則作為程式錯誤的後備保護。

正文

B0Bot, the cybersecurity news bot I'm working on for Google Summer of Code 2026 with C2SI, uses a planner/executor design in LangGraph. A planner turns a request into a short list of steps, an executor runs them one at a time, and the graph loops until the work is done. That loop is the useful part of the design, and it's also the part that can quietly go wrong. If nothing in the graph decides when to stop, the agent keeps calling tools until something outside it gives up.

This post is about that one question: how a planner/executor graph knows it's finished, and what it does when it can't finish. The examples use LangGraph's JavaScript package (@langchain/langgraph), and I ran the code below against version 1.7.5 before writing about it.

The shape of the graph

The graph has four nodes:

START -> planner -> executor --(route)--> executor
                                 |------> replanner -> executor
                                 |------> finish -> END

The planner writes the plan. The executor takes the first step off the plan, runs it, and records the result. After every executor run, a routing function looks at the state and picks one of three paths: run the next step, ask the replanner for a new plan because something failed, or go to finish and write an answer.

The important thing is that the routing function is plain code. The LLM decides what the steps are, but code decides whether the loop keeps going. You can read that function and know exactly when the agent stops, which is hard to say about a prompt that tells the model "stop when you're done".

Why the recursion limit isn't enough

LangGraph already has a safety net. Every run has a recursion limit, which caps the number of super-steps one run can execute. A super-step is one round of node execution. In a graph like this one, where only one node runs at a time, each node run is one super-step, and conditional edges don't add any extra steps. The default limit is 25, and when a run goes past it, LangGraph throws a GraphRecursionError.

That protects your bill, but it's a bad way to end a conversation. When the error is thrown, invoke() doesn't return your state, so the user gets an exception instead of an answer. If the agent had already found three useful articles before it got stuck retrying a fourth, that work doesn't reach the user unless you dig it out yourself.

So I treat the recursion limit as a backstop for bugs, and I give the graph its own budget that it can see and react to. When the budget runs out, the graph goes to a normal finish node and answers with what it has.

Putting the budget in state

Here's the state. Besides the goal and the plan, it keeps a list of step results, a count of executed steps, and a count of replans:

import { Annotation, StateGraph, START, END } from "@langchain/langgraph";

type StepResult = { step: string; ok: boolean; output: string };

const AgentState = Annotation.Root({
  goal: Annotation<string>,
  plan: Annotation<string[]>({ reducer: (_old, next) => next, default: () => [] }),
  pastSteps: Annotation<StepResult[]>({
    reducer: (old, next) => old.concat(next),
    default: () => [],
  }),
  stepsUsed: Annotation<number>({ reducer: (_old, next) => next, default: () => 0 }),
  replans: Annotation<number>({ reducer: (_old, next) => next, default: () => 0 }),
  answer: Annotation<string>,
});

type State = typeof AgentState.State;

The reducers matter. plan uses a replace reducer, so when the executor returns the remaining steps, they overwrite the old list. pastSteps appends, so each node only returns its new result and the history builds up on its own. The counters replace, and each node that changes one returns the new value.

Newer LangGraph docs also show a StateSchema class built on Zod. Annotation.Root still works in the current version, so use whichever one your codebase already has.

The nodes

In the real graph the planner and replanner call an LLM with structured output, and the executor calls tools. For this post they're stubs, because the stopping logic doesn't depend on what's inside them:

async function executor(state: State) {
  const [step, ...rest] = state.plan;
  const result = await runStep(step, state); // tool call, returns { step, ok, output }
  return {
    plan: rest,
    pastSteps: [result],
    stepsUsed: state.stepsUsed + 1,
  };
}

async function replanner(state: State) {
  const plan = await makeNewPlan(state.goal, state.pastSteps); // LLM call
  return { plan, replans: state.replans + 1 };
}

async function finish(state: State) {
  const answer = await writeAnswer(state.goal, state.pastSteps); // LLM call
  return { answer };
}

Notice that finish reads pastSteps, not just the last result. When the agent stops early, this is the node that turns partial work into a useful reply, like "I found two reports about this CVE, but the vendor advisory page refused my request".

The routing function

This is where the stopping rules live:

const MAX_STEPS = 6;
const MAX_REPLANS = 2;

function route(state: State) {
  const last = state.pastSteps[state.pastSteps.length - 1];

  if (state.stepsUsed >= MAX_STEPS) return "finish";
  if (last && !last.ok) return state.replans < MAX_REPLANS ? "replanner" : "finish";
  if (state.plan.length === 0) return "finish";
  return "executor";
}

const graph = new StateGraph(AgentState)
  .addNode("planner", planner)
  .addNode("executor", executor)
  .addNode("replanner", replanner)
  .addNode("finish", finish)
  .addEdge(START, "planner")
  .addEdge("planner", "executor")
  .addConditionalEdges("executor", route, ["executor", "replanner", "finish"])
  .addEdge("replanner", "executor")
  .addEdge("finish", END)
  .compile();

The order of the checks is deliberate. The step budget comes first, so no other rule can keep the loop running past it. A failure comes next, because a failed step usually means the rest of the plan was built on something that isn't true anymore. Running out of plan comes last, which is the normal happy ending.

The third argument to addConditionalEdges lists the nodes route can return. LangGraph uses it to know the possible edges when it builds and draws the graph, so it's worth passing even though routing would work without it.

Replans only happen after a failure. Some examples, including LangGraph's own plan-and-execute tutorial, replan after every step. That gives the model a chance to rethink, but it also doubles the LLM calls and gives the model many more chances to wander off the goal. If your steps are fairly predictable, replanning on failure is a calmer default.

Setting the recursion limit from the budget

Once the budget is in state, you can work out the largest number of super-steps a healthy run can take, and set the recursion limit just above it:

// planner + executor runs + replanner runs + finish, plus a little slack
const recursionLimit = 1 + MAX_STEPS + MAX_REPLANS + 1 + 2;

const result = await graph.invoke({ goal: "Summarize news about this CVE" }, { recursionLimit });

recursionLimit goes at the top level of the config object, not inside configurable. Now, if you ever see GraphRecursionError, it means the routing logic has a bug, because a correct run can't get there. That's a much more useful signal than an error that might just mean "this request needed a few more steps".

Testing that it actually stops

I tested this with stubs where one step always fails, which is the case that loops forever in a naive design. The trace looked like this:

  1. The planner makes three steps: search feeds, fetch article, summarize.
  2. Search works. Fetch fails with a 403.
  3. The replanner tries again with fetch and summarize. Fetch fails again.
  4. That happens once more, and now replans is 2, so route sends the run to finish.

That's 8 super-steps in total, and the run ended with an answer built from the one successful step. Running the same graph with a recursion limit of 3 threw GraphRecursionError, as expected.

The trace also shows a weakness. The replanner kept proposing the same failing fetch. The replan cap stopped it, but it would be better to give the replanner the failed steps and their errors and tell it not to repeat a step that already failed with the same input. You can also enforce that in code: before the executor runs a step, check whether pastSteps already has the same step marked as failed, and if it does, skip straight to finish or to the replanner.

A short checklist

When I look at a planner/executor graph now, I check four things. The counters live in state, so every node and the routing function can see them. The routing function checks the budget before any other rule. There's a finish node that can write an answer from partial results. And the recursion limit is set from the budget, so hitting GraphRecursionError points to a bug in the graph instead of a request that simply needed more steps.

來源:DEV Community · dev.to