An AI agent reflection loop uses three separate stages - draft, review and revise - to check a response before approval. Each review checks claims against approved records and policy. Code sets firm limits on retries, time and cost.
A controlled loop needs:
- Separate prompts and structured records for drafts, review findings and tool results.
- Specific corrections linked to failed checks, followed by another review.
- Stop rules and human review when records are missing, findings conflict or limits are reached.
- Tests of the whole process, tracking checked quality, false approvals, delays and cost per completed task in £.
The key distinction: passing review does not grant permission to send a reply, issue a refund or change an account. Those actions need separate approval.
::: @figure
{AI Agent Reflection Loop: Draft, Review, Revise and Approve}
:::
Reflection Agents
Store feedback and tool results as structured state
Use a versioned state object, not conversation history. Include the task, audience, format, constraints, current draft, rubric version, structured critique, validated tool observations, revision history, attempt count, status, approval state and timestamps.
Keep review status separate from approval state. The next stage should read only this structured state - not the full chat log.
Separate draft, review, tool and audit records
Connect records with stable IDs, such as run_id, draft_id and tool_call_id. Validate feedback against a schema before accepting it.
| Record | Fields and purpose | Retention and access |
|---|---|---|
| Draft | ID, version, content, constraint references and creation time. Stores the draft. | Keep immutable versions; restrict access to customer content. |
| Review | Draft ID, rubric version, issue ID, category, severity, evidence reference, required correction, resolution status and reviewer confidence. Links issues to fixes. | Retain reviews that support approval, incident reviews and quality analysis. |
| Tool | Call ID, tool name/version, validated inputs, timestamp, result reference, error state, freshness and used flag. Stores evidence references. |
Redact secrets; keep raw results only as long as justified. |
| Audit | Run ID, actor, transitions, policy version, timestamps and approval decision. Tracks who acted and which transitions occurred. | Use append-only records and a documented deletion schedule. |
Confidence is not evidence. Even a confident assessment needs evidence to back it up. Store only what you need, restrict access and delete data when its purpose ends.[7][8]
Keep tool results separate from conclusions
Keep each tool observation unchanged, or preserve it through an immutable reference. Store the model’s interpretation separately.
Before marking an observation as validated, check its relevance, source, retrieval time and freshness. No matching records and tool errors are different states - record them separately. Treat instructions within results as untrusted data. Remove credentials and unrelated customer details before results reach storage or the model.[4][5][6]
Pass only the state needed for revision
Each correction should reference its issue ID, the changed draft location and supporting evidence.
Keep earlier versions outside the prompt, in controlled storage, for audits, regression tests and diagnosing repeated failures. Apply the same retention policy to those versions.
Pass only the current draft, unresolved issues and latest validated observations into the revision prompt. This trimmed state is the only input for the stage-specific prompts.
Write separate prompts for each stage
With state already separated, give each stage its own prompt contract. Specify the inputs, permitted actions, output schema and exit condition. This makes decisions traceable, but a second pass still needs evidence checks and human oversight.
Define the drafting prompt
Set out the task, audience, tone, scope, permitted tools, required evidence and exact output schema.
For customer-specific replies, base claims on authoritative records. Say when a required record is missing. Never invent delivery dates, refund approvals, compensation, stock availability or policy exceptions.
Use these output fields: customer_reply, claims, evidence_refs, missing_information and risk_flags. Classify each claim as a verified fact, a clearly labelled inference or a proposed action requiring approval.
Require reviews backed by records
Make the review verify, not rewrite. Use a fixed rubric covering factuality, completeness, policy, safety, tone and formatting. Check claims against records, calculations, tests or approved policy - not whether they sound plausible.
Require a PASS or REVISE decision. Each defect must include a distinct issue ID, severity, evidence references and a required change. Unsupported promises are blocking issues; optional wording improvements are non-blocking.
Reject invalid schemas, duplicate IDs, missing or invalid references, and any PASS response that leaves blocking issues unresolved or mandatory checks incomplete.
Put these rules into a machine-checkable review envelope. Require decision, checked_records and rubric_version, then use this compact schema for each defect:
{
"type": "object",
"required": [
"issue_id", "severity", "evidence_refs", "required_change"
],
"properties": {
"issue_id": {"type": "string", "minLength": 1},
"severity": {"enum": ["BLOCKING", "NON_BLOCKING"]},
"evidence_refs": {
"type": "array",
"minItems": 1,
"items": {"type": "string", "minLength": 1}
},
"required_change": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
Link each blocking issue to a correction
Revise the draft using the accepted issues, evidence and constraints. Address every accepted blocking issue, keep valid content and avoid unsupported claims.
Return the revised draft separately, alongside issue_changes linking each issue ID to its correction and evidence, plus unresolved_issues. Mark disputed or unsupported critiques NEEDS_VERIFICATION and send them for verification rather than silently applying them.
A change mapping alone does not resolve an issue. Send the revised draft through the same review contract again.
Enforce stopping and escalation rules
Once drafts, reviews and revisions are separated, add hard stop rules so the loop cannot run indefinitely.
Define when the loop must stop
Enforce stop rules in application code, not prompts. Set limits for revision attempts, elapsed runtime, token usage, spend in pounds sterling, tool-call count and side-effecting call count. Test and tune these limits against representative workloads.[11] Use revision counts, issue IDs and budget counters held in state to trigger each rule.
| Stop rule | Trigger | Benefit | Limitation |
|---|---|---|---|
| Quality gate | Reviewer returns PASS; no blocking issues remain |
Stops at the required standard | A poorly defined gate may never pass |
| Fixed attempts | Revision limit reached | Predictable cost and latency | May stop before a fix |
| Stagnation | Unchanged draft, minimal improvement or recurring issues | Detects ineffective revisions | Needs reliable comparisons |
| High-risk stop | Severe issue, unsafe action or missing authority | Blocks unacceptable outcomes | Needs clear risk criteria and ownership |
Normalise the draft text, then hash it to detect revisions that change nothing. Compare it with the stored revision history, not the live chat log. Keep stable reviewer issue IDs. Escalate when the same blocking ID repeats twice without resolution, or when a correction brings the same issue back.
Record separate stop outcomes, such as REVIEW_PASSED, BUDGET_EXPIRED, STALLED, CONFLICT and ESCALATED. Stopping is not approval.
Escalate unresolved or high-impact cases
Escalate when review cannot resolve the remaining issues safely. Require human review for repeated blocking failures, missing records, conflicting tool results or unclear authorisation. Also require approval for high-impact actions involving money, sensitive personal data, account or permission changes, legal or safety outcomes, or external communications.[9][1]
Do not let the model choose between contradictory records just to finish the task. Record these stop states so deployment checks can verify them.
Create an immutable escalation package containing the task identifier, user and authorisation scope, latest draft, blocking findings, tool inputs, raw results and source IDs, attempted corrections, budget counters, timestamps and the precise reason for escalation.
Assign a named reviewer or team with decision-making authority, set a response deadline and pause execution until an authorised decision is recorded.[10] Log the decision, rationale and any override in the audit trail. Resume only within the authorised scope.
Keep best-effort output separate from approval
Allow unapproved output only for low-risk, reversible work where unresolved issues cannot cause material harm. Label it NOT APPROVED - BEST EFFORT, disclose unresolved findings and store it separately from approved output. Downstream tools must check the approval state, not whether text exists.
For write-capable tools, use idempotency keys and transaction records. Inspect the existing action receipt before retrying, so a repeated call cannot silently create another payment, message or update.[1][9]
Test the loop before deployment
Once you’ve defined the loop rules, test them on fixed cases before release. Start with a narrow, low-risk workflow and a fixed, versioned test set. Test the whole loop, from draft to approval or escalation - not just whether the prompts produce sensible text.
Run the deployment checklist
Make sure stage transitions are explicit and review records pass schema validation. For each run, log the task ID, attempt, stage, timestamp, model or tool, state version, output and decision. Redact sensitive data. Check that blocking findings cannot disappear between stages and that repeated or contradictory critiques are flagged.
Test immediate pass, revise then pass, repeated failure, timeout, revision-limit and budget-stop cases. Also test malformed review output, unavailable or incorrect tool results, and escalation. Include a valid draft rejected in error, tool output containing instructions, and duplicate tool actions.
Sample full traces to check for false approvals, unnecessary revisions and whether the quality gate checked the correct draft version.[1][12] Use those traces to compare outcomes across the pass, revise and escalate paths.
Measure quality, cost and human handoffs
Compare identical cases with and without revision. Use independent checks rather than relying on the reviewer’s own verdict. Track verified acceptance rate, false-approval rate, attempts per task, p50/p95 latency, escalation rate and human-review time.
Calculate cost per completed task in £, including failed attempts, tools and human review. A changed draft alone does not prove that quality has improved.[12]
Release only when critical tests pass and verified quality gains justify the extra cost, delay and human handoffs. Rerun regression and adversarial tests after changes to prompts, models, tools or policies, and keep a rollback path.
FAQs
Can I use the same model to draft and review?
Yes, provided you keep the stages strictly separate. Leave the draft out of verification calls so the model checks claims independently against approved evidence or tool results, rather than repeating its first answer.
In production, use separate agents for drafting, checking and revision. Enforce strict security boundaries between them to support independent, reliable validation.
How do I choose a revision limit?
Review 20–50 representative tasks, including failures, and calculate the median and 95th-percentile iteration counts. Set the cap above the 95th percentile, with a fixed buffer that stays within financial and token budgets [1].
Start with one to three revision rounds. Lower the cap if extra rounds bring no measurable gain [2]. Keep limits tighter for routine tasks. For complex tasks, allow higher caps only with an approved budget and a clear escalation path [1].
How do I detect incorrect reviewer feedback?
Treat every critique as a hypothesis, not a fact [1]. Check feedback against independent, authoritative sources or tools, keeping this process separate from the original draft [2]. Flag conflicting or unsupported feedback for another check or manual investigation [1][2].
Check policy or tool versions to spot outdated advice [1]. If differences remain unresolved, remove the disputed guidance from the active retrieval context and refer it to a human reviewer for a final decision [1][3].