Skip to main content

Saizul Amin

AI

Building Self-Correcting SQL Agents with LangGraph and Vanna AI in Python (2026 Tutorial)

📅 19 Jul 2026 ⏱ 1 min read
AI
In this article

    Why Naive Text-to-SQL Fails in Enterprise Environments

    Naive text-to-SQL prompts frequently invent non-existent column names, hallucinate incorrect table relationships, or generate SQL queries that time out on large datasets. Building an enterprise-grade natural language database assistant requires a self-correcting agent loop that generates SQL, executes it against an isolated read replica with strict timeouts, inspects compiler or execution errors, and iterates automatically until valid data returns.

    Documented by Saizul Amin for AI engineers and enterprise data platform architects.

    LangGraph Self-Correcting Execution Graph

    
    from langgraph.graph import StateGraph, END
    from typing import TypedDict
    
    class SQLAgentState(TypedDict):
        natural_query: str
        generated_sql: str
        error_message: str
        query_result: list
        retry_count: int
    
    def generate_sql_node(state: SQLAgentState):
        # LLM creates SQL using DDL context and previous error (if any)
        # ...
        return {"generated_sql": "SELECT COUNT(*) FROM orders WHERE status = '\''completed'\''", "retry_count": state["retry_count"] + 1}
    
    def execute_sql_node(state: SQLAgentState):
        # Execute query against PostgreSQL read replica with 3-second statement_timeout
        # If error occurs, catch exception and store in error_message
        return {"query_result": [{"count": 4200}], "error_message": ""}
    
    def check_execution(state: SQLAgentState):
        if not state["error_message"]:
            return END
        if state["retry_count"] >= 3:
            return END
        return "generate_sql"
    
    Share this article
    Md Saizul Amin
    Written by

    Digital Systems Strategist · AI Agent Developer · 9+ years in digital & IT

    Md Saizul Amin is a digital systems strategist and AI automation engineer from Dhaka, Bangladesh. With 9+ years across IT, web development and digital marketing, he writes practical guides on technology, business, education and online growth — and builds the same kinds of systems (AI agents, websites, SEO and ad campaigns) for clients in Bangladesh, the UK and the USA.

    9+Years in digital & IT
    50+Websites developed
    7Live AI agent systems
    $150K+Ad spend managed

    Specialist in

    AI agents & n8n automationLLM integration (Gemini, GPT-4o, Claude)Custom software & web appsWordPress developmentSEO · AEO · GEOMeta & Google AdsEmail deliverabilityCRM & funnelsIT infrastructure & cybersecurity

    Credentials & experience

    • 🎓
      B.Sc. in Computer Science & EngineeringBangladesh University of Business & Technology (BUBT), 2017–2021
    • 🤖
      AI Automation Engineer · Web Developer · SEO SpecialistUnique Mark Limited, Birmingham UK — 2024 to present
    • 🌱
      IT SpecialistGreen Fund Initiative Inc., USA — 2024 to present
    • 🏥
      Junior IT Consultant — Ministry of Health (DGHS)Built the first national Shareable Health Record website; supported 6,000+ facilities
    • 🧭
      Head of ITWEDO Bangladesh — led IT for 50+ staff, 2021–2023

    ✔ Researched and written by the author, informed by hands-on work on real projects. Articles are updated when facts, tools or guidelines change.

    Want results like this for your business?

    AI agents, custom software, websites and growth systems — let’s talk about yours.