AI AgentsAI Agent Execution & Lifecycle
What is a validated agent loop?
Question 267 of 280 · Updated
On this page
- How this differs from a basic agent loop
- The five stages of a validated loop
- Beginner-friendly numerical production example
- A practical control-flow pattern
- Example validation pseudocode
- A final response is only a proposal until checked.
- What should be validated?
- Production guardrails and failure scenarios
- Metrics and testing
- Engineering trade-offs and common mistakes
A validated agent loop is an agent execution cycle in which every important action, observation, and claimed completion is checked against explicit rules before the system proceeds. The agent does not treat a plausible model response, a successful HTTP status, or the absence of another tool call as proof that the user's goal is complete. It maintains a testable task state, validates tool inputs and outputs, measures progress against acceptance criteria, and stops only when the required postconditions pass—or reports a clear blocked or incomplete state.
How this differs from a basic agent loop#
Question 5 introduced the general cycle: observe, decide, act, and observe again. A validated loop adds independent checks around that cycle:
- Is the proposed action allowed, correctly scoped, and based on valid inputs?
- Did the tool actually perform the intended operation?
- Is the returned observation well-formed, fresh, and relevant?
- Did the task state move closer to the goal?
- Are all required acceptance criteria satisfied before declaring completion?
A model saying “done” is a *candidate conclusion*. The orchestrator or validator must establish whether it is true.
The five stages of a validated loop#
- Define the goal contract. Convert the request into explicit, observable acceptance criteria, constraints, and forbidden side effects. Separate hard requirements from quality preferences. Identify which checks can be deterministic and which need human judgment.
- Validate the next action. Check tool name, argument schema, authorization, tenant/resource scope, preconditions, approval requirements, idempotency key, and remaining budgets before execution. Reject or request clarification for malformed or unsafe actions.
- Execute and validate the observation. Run the tool, capture its operation ID and status, parse the result against a schema, check freshness/provenance, and distinguish “accepted” from “completed.” A 202/queued response, for example, is not proof that an asynchronous job finished.
- Evaluate progress and route. Update a durable task state and run the relevant postcondition checks. If checks fail but can be repaired, feed the specific failures back into the next iteration. If evidence is missing, pause or mark the result unknown rather than guessing.
- Terminate truthfully. Return COMPLETE only when all mandatory acceptance checks pass and no required action remains pending. Otherwise return NEEDS_INPUT, BLOCKED, FAILED, or INCOMPLETE_BUDGET with the remaining work clearly stated.
Beginner-friendly numerical production example#
A coding agent receives this request: “Change the API retry timeout from 3 seconds to 5 seconds and add a regression test.” The team defines four acceptance checks:
- Configuration resolves to exactly 5 seconds.
- A regression test asserts the new timeout behavior.
- The complete relevant test suite passes.
- The final diff contains only the intended configuration and test changes.
The agent runs a maximum of 8 iterations:
- Iteration 1 — inspect: reads the configuration and finds 3 seconds; identifies the relevant test file.
- Iteration 2 — act: applies the configuration change and adds the regression test. The patch tool reports success, but this is not completion.
- Iteration 3 — validate: runs tests; 45 of 46 pass. One old assertion still expects 3 seconds. The validator marks the test criterion FAILED.
- Iteration 4 — repair: updates the obsolete assertion and records the changed test.
- Iteration 5 — verify: reruns the suite; 46 of 46 pass. A separate config check reads back 5 seconds, and a diff check confirms exactly two intended files changed.
All four acceptance checks now pass, with no pending operation. The loop returns COMPLETE after 5 of 8 iterations. If the test runner had merely accepted a job but not finished, or if the diff contained an unrelated production change, the loop would not be allowed to report success.
A practical control-flow pattern#
The key design choice is to route a candidate final answer through a validator before the graph reaches END:
START -> load durable task state and acceptance criteria -> model decides next action -> tool action: validate permissions/schema -> execute tool -> validate result and update state -> evaluate progress -> model (next iteration) -> candidate final answer -> independent goal validator -> PASS: END / COMPLETE -> repairable failure: model with failed checks -> missing approval or evidence: PAUSE -> unrecoverable failure: END / FAILED
In LangGraph, nodes perform work and conditional edges decide whether to continue, branch, or end. The should_continue decision can route tool calls to a tool node, but a production agent should add a goal-validation node between a candidate final response and END. Persist task state and checkpointer data so a resumed run uses the same acceptance contract and completed-action ledger. See the LangGraph workflows-and-agents guide: https://docs.langchain.com/oss/python/langgraph/workflows-agents
Example validation pseudocode#
def validated_agent_loop(state, max_iterations=8): while state.iteration < max_iterations: decision = model_decide(state)
if decision.kind == "needs_input": return {"status": "NEEDS_INPUT", "state": state}
if decision.kind == "tool_call": validate_schema_and_policy(decision.tool, decision.args, state) result = execute_idempotently(decision, state) observation = validate_tool_result(result) state = apply_observation(state, observation) continue
A final response is only a proposal until checked.#
report = validate_acceptance_criteria(state) if report.all_required_checks_pass and not state.pending_effects: return {"status": "COMPLETE", "state": state}
if report.repairable: state = attach_validation_feedback(state, report) continue
return {"status": "BLOCKED", "validation": report}
return {"status": "INCOMPLETE_BUDGET", "state": state}
This is illustrative orchestration logic, not a drop-in framework implementation. Production code must also handle cancellation, timeouts, exceptions, persistence, concurrency, and tool-specific idempotency.
What should be validated?#
- Action contract: JSON/schema validity, required fields, allowed tool, authorization, tenant scope, resource ownership, policy and approval.
- Tool result: expected type, operation ID, status, provenance, freshness, and whether the intended state change actually occurred.
- Progress: meaningful change in the task state, not merely another model turn or repeated tool call.
- Completion: each hard acceptance criterion, no unresolved asynchronous effects, no pending approvals, and no known partial failure.
- Safety: action limits, sensitive-data boundaries, side-effect policy, and stop conditions.
Structured output validation checks shape, not truth. A response can be valid JSON and still contain an incorrect answer; a tool can return HTTP 200 while the business operation failed. Use deterministic checks wherever possible and independent review for subjective criteria.
Production guardrails and failure scenarios#
- False completion: the model stops calling tools before the goal is met. Route final candidates through acceptance checks; do not use “no tool calls” as the only success condition.
- False tool success: an API acknowledges a request but the downstream job later fails. Track operation IDs and poll/subscribe until terminal status.
- Repeated no-progress loop: the agent repeats the same failing action. Detect duplicate action fingerprints, unchanged state, and repeated identical errors; stop or escalate after bounded retries.
- Untrusted tool output: retrieved pages or tool results contain misleading instructions. Treat observations as data, validate them, and never let them silently override system policy.
- Duplicate side effects: a timeout causes a retry after a payment or write may already have succeeded. Use idempotency keys and reconcile the operation before retrying.
- Budget exhaustion: iteration, wall-clock, token, tool-call, and monetary limits are reached. Return INCOMPLETE_BUDGET; do not relabel a partial result as complete.
- Human approval: pause before irreversible or high-impact actions, persist the pending action and resume only after a valid approval decision. LangGraph documents interrupt/resume patterns for human review: https://docs.langchain.com/oss/python/langgraph/interrupts
Metrics and testing#
Track task completion rate with validator proof, false-completion rate, false-rejection rate, iterations per task, no-progress iterations, tool schema failures, tool-result validation failures, duplicate side effects, pending asynchronous operations, budget-exhaustion rate, human escalation rate, and end-to-end latency/cost. Segment by task type and tool; aggregate success can hide one failing workflow.
Test at least these cases: a tool returns success without changing state; a valid result is stale; a required field is missing; a task is partially completed; a tool is retried after an uncertain timeout; a human approval is pending; the agent emits a premature final answer; and the iteration budget expires. Assert that none of these cases can produce COMPLETE unless all hard acceptance criteria are independently satisfied.
Engineering trade-offs and common mistakes#
- More validation improves reliability but adds latency, tool calls, and implementation complexity. Validate high-risk side effects strictly; use lightweight checks for low-risk read-only actions.
- A deterministic validator is excellent for exact state, schema, and test outcomes, but cannot fully judge subjective quality. Use rubric-based evaluation or human review for those criteria.
- Too many retries increase cost and can amplify external side effects. Use bounded retries, backoff, idempotency, and a clear terminal failure state.
- Persisted state improves resumability, but stale checkpoints must be checked against the current task version and authorization before resuming.
- A single “success” boolean hides partial completion. Store per-criterion status, evidence, timestamp, and validator version.
Takeaway: A basic agent loop repeats actions; a validated agent loop proves that each step is admissible and that the final result satisfies the goal. The model proposes; the system verifies.
References
- 1.LangGraph: Workflows and agentsdocs.langchain.com
- 2.LangGraph: Interruptsdocs.langchain.com
- 3.LangGraph: Graph API overviewlangchain-ai.github.io
- 4.OpenAI: Assistants migration guideplatform.openai.com
Related questions
Explore other topics:Large Language ModelsRetrieval-Augmented GenerationMLOps