Agentic AI Notebook
Agent Foundations
Phase 4Module 14 of 15

Self Correction

First attempts often fail — correction improves reliability without humans.

Spell-check while typing — fix before the message ships.

Visual Workflows

Start here — scroll inside each diagram frame to explore, then use + / to zoom up to 200% if needed.

100%
Loading diagram...

Scroll inside the frame to explore · use + / − to zoom up to 200%

Self-Correction Loop

100%
Loading diagram...

Scroll inside the frame to explore · use + / − to zoom up to 200%

Detect error feed back to LLM retry with fix context.

Key Takeaways

  • 1.Self-correction detects and fixes errors inside the loop.
  • 2.Programmatic checks: empty results bad format.
  • 3.LLM critique: answer complete and grounded?
  • 4.Retry with fix context max 3-5 attempts.

Real Example

Scenario

SQL agent receives `column 'revinue' does not exist` — the error is appended to context, the LLM fixes the typo to `revenue`, and the query succeeds on retry 2.

What you would do

Detection: programmatic DB error in the observation. Fix: re-prompt with the exact error string. Cap retries at 3; escalate if the same error appears twice. Log every correction for the eval suite. Monitor: retry success rate and mean retries per task.

Practice Task

Write three error→fix pairs (schema typo, empty result set, tool timeout). For each, write the exact sentence you would append to the LLM context.

Code Walkthrough

Highlighted lines show where Self Correction happens in the code.

Self Correction
1MAX_RETRIES = 32retries = 03last_error = None4
5while retries < MAX_RETRIES:6    try:7        result = run_sql(llm_generated_query)  # key line for Self Correction8        break9    except DatabaseError as e:10        retries += 111        if str(e) == last_error:12            raise  # same error twice — escalate13        last_error = str(e)14        llm_generated_query = fix_query_with_error(llm_generated_query, str(e))

Cheat Sheet

Quick recap

quick ref
  • Detect → diagnose → retry
  • Cap retries at 3-5
  • Feed error text back to LLM
  • Log every correction attempt
  • Escalate when stuck

Common Mistakes

  • Skipping evaluation for Self Correction before production
  • No logging or tracing around self correction steps
  • Ignoring cost and latency implications