LangGraph Agents

Course Content

LangGraph Agents

7 sections · 49 lessons

How do you design stopping criteria for iterative agent loops (budget, confidence, time)?


Why research runs stopped, per 100 runs6127930123qualityreached4-attempt cap90 s deadlineno progressThe rubric penalised revenue figures private companies never publish.
Recording the stop reason turned a vague cost problem into one fixable rubric bug.

What you need to know

RuleCatchesStored in state
Quality thresholdThe normal, good finishscore, approved
Iteration capSlow convergenceattempts
Cost budgetExpensive loopstokens_used or cost_inr
DeadlineUsers waitingdeadline (a timestamp)
No progressStuck loopslast_outputs
recursion_limitBugs in the aboveRun config
Python
import timedef stop_or_continue(state) -> str:    if state["score"] >= 0.9:        return "finalise"                         # good enough    if state["attempts"] >= 4:        return "finalise"                         # iteration cap    if state["cost_inr"] >= 20:        return "finalise"                         # budget    if time.time() > state["deadline"]:        return "finalise"                         # user waiting    if state["last_outputs"][-2:].count(state["last_outputs"][-1]) == 2:        return "finalise"                         # no progress    return "improve"

Details that matter

  • Set deadline in state at the start of the run, so a resumed run keeps the original deadline.
  • Record why the loop stopped (stop_reason) for dashboards: if 30% of runs stop on the cap, the cap or the prompt needs work.
  • For create_agent, ModelCallLimitMiddleware and ToolCallLimitMiddleware give run-level and thread-level caps without writing edges.
  • Keep the best candidate so far; the finalise node returns it with a note about what was not verified.

A real-life example

A research agent drafts a company profile and improves it until a grader scores 0.9. In production, logs showed: 61% of runs stopped on quality, 27% on the four-attempt cap, 9% on the 90-second deadline and 3% on no-progress. The 27% was high, so the team looked closer and found the grader penalised missing revenue figures for private companies, which can never be found. They changed the rubric; cap-stops fell to 8% and average cost per report fell from Rs 14 to Rs 9.

Follow-up questions to expect

  • "Which rule matters most?" — The quality exit, because it defines success. The others are guards so that failure is cheap and visible.
  • "How do you count cost inside the graph?" — Read token usage from each model response's usage_metadata and add it to a state key with an operator.add reducer.
  • "What should the user see when a budget stops the run?" — The best result, clearly marked with what is uncertain, and an option to continue.