<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vijay Vadali on Medium]]></title>
        <description><![CDATA[Stories by Vijay Vadali on Medium]]></description>
        <link>https://medium.com/@vijay-vadali?source=rss-12238e16d142------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QHJeJleKg7m3hItV283Qew.png</url>
            <title>Stories by Vijay Vadali on Medium</title>
            <link>https://medium.com/@vijay-vadali?source=rss-12238e16d142------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:08:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vijay-vadali/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Agentic AI SQL Assistant]]></title>
            <link>https://ai.plainenglish.io/agentic-ai-sql-assistant-4df49b906595?source=rss-12238e16d142------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df49b906595</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Vijay Vadali]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 00:58:33 GMT</pubDate>
            <atom:updated>2025-07-10T17:01:00.751Z</atom:updated>
            <content:encoded><![CDATA[<h4>An agentic LLM-powered system for natural language to SQL translation, schema-aware validation, and autonomous query execution</h4><h3>Table of Contents</h3><ul><li>Getting started</li><li>Why Agentic AI for SQL Assistant?</li><li>Use Case Overview</li><li>Dataset and Schema</li><li>Architecture Overview</li><li>How the Agent Works Internally</li><li>Running Locally or in Docker</li><li>Conclusion</li></ul><h3>🧠 Getting started</h3><p>In today’s data-driven world, accessing insights from structured databases often requires knowledge of SQL — a skill not every team member possesses. What if anyone on your team could simply <em>ask</em> a question like, “Which coin had the highest trading volume in March 2021?” and get an accurate SQL response instantly?</p><p>This project introduces an agentic AI chatbot that bridges the gap between natural language and SQL. Powered by a language model and LangChain’s agent architecture, it acts as a reasoning assistant that interprets user intent, understands the underlying database schema, and generates precise SQL queries on the fly.</p><p>But this goes beyond just converting text to SQL. The agent is context-aware, capable of explaining queries, validating results, auto-correcting errors, and maintaining a conversational memory. Whether you’re a data analyst, product manager, or business stakeholder, this assistant enables you to interact with your database as if you’re talking to a human expert — no SQL expertise required.</p><p>The agent also supports querying metadata (e.g., “What tables are available?”), guiding users through unknown schemas or datasets. This makes it especially powerful for onboarding new users, enabling self-serve analytics, or embedding in internal tools and dashboards.</p><p>Let’s explore how this conversational AI agent transforms static databases into interactive, intelligent systems.</p><p>If you’d like to explore or run the code yourself:</p><p>- 🔗 [<a href="https://github.com/vijay-vadali/agenticai-sql-assistant">GitHub Repo</a>]</p><p>- 📓 [<a href="https://github.com/vijay-vadali/agenticai-sql-assistant/blob/main/agenticai_sql_assistant.ipynb">View Jupyter Notebook</a>]</p><p>These contain the full code, setup instructions, and sample queries you can try.</p><p>This agent is built specifically for querying structured data in SQL<strong> </strong>databases. Support for NoSQL systems is not included in this version.</p><h3>🤖 Why Agentic AI For SQL Assistant?</h3><p>Traditional chatbots or API wrappers are limited — they respond to direct prompts but don’t reason, plan, or take autonomous action across tools. Agentic AI changes that.</p><h4>What Makes an Agent Different?</h4><p>Agentic AI represents a significant leap beyond traditional chatbots and static APIs. While traditional systems are limited to static question-answering or predefined task execution, agentic AI dynamically interprets input, plans steps, and makes decisions based on reasoning. Unlike basic bots that simply follow instructions with limited memory, agentic systems maintain context across conversations and adapt their responses accordingly. They are goal-oriented — chaining together reasoning steps to reach an outcome — and can autonomously choose and utilize external tools such as SQL toolkits. This flexibility makes agentic AI far more powerful for real-world tasks that require multi-step reasoning, adaptability, and intelligent tool use.</p><h4>Why not standlone LLM’s or RAG?</h4><p>While RAG and standalone LLMs can generate SQL from natural language, they lack the ability to reason, take actions, or handle multi-step tasks. Agentic AI systems go further — combining LLMs with tools, memory, and planning to validate queries, run them, fix errors, and explain results. This makes them far better suited for building a truly helpful and autonomous SQL assistant, especially for non-technical users.</p><h4>Why It Matters in This Use Case</h4><p>This project demonstrates agentic AI in action:</p><ul><li>The agent analyzes user questions, decides the best way to convert them into SQL, and validates schema before execution.</li><li>It can also self-correct errors, explain queries in natural language, and respond through both UI and API interfaces.</li><li>All this happens through reasoning-driven steps — not just one-shot completions.</li></ul><p>🔁 The result is a smart assistant that bridges the gap between natural<strong> </strong>language and structured<strong> </strong>data — especially empowering non<strong>-</strong>technical<strong> </strong>users to interact with databases.</p><h3>🧩 Use Case Overview</h3><p>Structured databases like SQL are powerful — but they remain largely inaccessible to non-technical users. Business analysts, product managers, and domain experts often need insights trapped inside databases, but lack the technical skills to write SQL queries or understand table relationships.</p><p>This is where an agentic SQL assistant becomes transformative.</p><p>Instead of requiring users to learn SQL syntax or memorize table names, our agent allows them to ask natural language questions like:</p><ul><li><em>“What was the highest price of Bitcoin in January 2020?”</em></li><li><em>“List the top 5 coins by market cap in 2021.”</em></li><li><em>“Show the total volume for Ethereum in Q4 2019.”</em></li></ul><p>Behind the scenes, the agent interprets the question, understands the schema, constructs a valid SQL query, explains it if needed, and returns results — all without any code.</p><p>This assistant serves as a bridge between human intuition and structured data, making analytics conversational, self-serve, and context-aware. Whether embedded into internal tools or exposed via an API, it reduces dependency on engineering while expanding access to insights across the organization.</p><h3>🔍Dataset and Schema</h3><p>A quick look at the CoinMarketCap SQLite dataset used in the demo.</p><p>To showcase agentic SQL capabilities, I used a public SQLite version of the CoinMarketCap dataset — a snapshot of historical cryptocurrency data that includes daily metrics for various coins.</p><h4>🧰 Key Details</h4><ul><li><strong>Database</strong>: coinmarketcap.sqlite</li><li><strong>Table Used</strong>: historical</li><li><strong>Number of Rows</strong>: ~10,000+</li><li><strong>Columns</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgSuq5qVkA9ZnKTPyBStVg.png" /><figcaption>Historical Table Columns</figcaption></figure><h4>📊 Why This Dataset?</h4><ul><li>It’s tabular and structured, making it perfect for SQL-based queries.</li><li>It’s familiar to both finance and crypto audiences.</li><li>Questions like <em>“What was the highest price of Ethereum in 2021?”</em> or <em>“Which coin had the lowest volume in March 2019?”</em> are relatable and showcase the agent’s SQL reasoning power.</li></ul><p>The agent uses LangChain’s schema introspection (db.get_table_info()) to understand available fields and table structures—this is key to ensuring valid and grounded SQL generation.</p><p>Here’s a clear breakdown of how each part of the LangChain + OpenAI + Streamlit + SQLite stack works together to create a natural language SQL query interface:</p><h3>🔧 Architecture Overview</h3><h4>Stack Breakdown: LangChain + OpenAI + Streamlit + SQLite</h4><h4>1. User Interaction — Streamlit (Frontend UI)</h4><ul><li>Streamlit provides a clean, web-based interface where users can:</li><li>Type natural language questions (e.g., “Top 5 coins by market cap in 2021”)</li><li>View the generated SQL</li><li>Edit and run the SQL query</li><li>View the results in a table</li><li>See query explanations or download SQL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_lrOdAhUdDTetU2foQ0fw.png" /><figcaption>Streamlit UI for Agentic SQL Assistant</figcaption></figure><h4>2. LLM Backbone — OpenAI (via LangChain)</h4><ul><li>OpenAI’s gpt-3.5-turbo/ gpt-4/gpt-4o model is used</li><li>Convert natural language into SQL</li><li>Explain SQL queries in plain English</li><li>Auto-correct invalid queries (agentic recovery)</li></ul><h4>3. Agentic Orchestration — LangChain</h4><ul><li>LangChain ties everything together with:</li><li>Agents that can make decisions (e.g., generate SQL, explain, correct)</li><li>Tools like SQL query runners, schema explorers, and LLM wrappers</li><li>Schema awareness using SQLDatabaseToolkit</li></ul><h4>4. Database — SQLite (coinmarketcap.sqlite)</h4><ul><li>Local relational database used to:</li><li>Store historical data of coins (market cap, volume, price, etc.)</li><li>Be queried via LangChain’s SQL tools</li><li>Serve real data for SQL results</li></ul><h4>🧠 Agentic Intelligence in Action</h4><p>Together, this stack lets you:</p><ul><li>Understand the schema automatically</li><li>Generate valid SQL dynamically</li><li>Validate &amp; auto-correct queries</li><li>Explain outputs in human language</li><li>Enable non-devs to access data like a pro</li></ul><h3>🛠️ How the Agent Works Internally</h3><p>Building an <strong>agentic AI assistant</strong> for natural language SQL queries requires more than just a large language model. Here’s how LangChain + OpenAI + SQLite work under the hood:</p><h4>1. 🧠 Prompt Design for Schema-Aware SQL Generation</h4><p>Before asking the LLM to generate SQL, we craft a structured prompt:</p><pre>prompt = (<br>    &quot;You are a SQL expert.\n&quot;<br>    &quot;Use only the following database schema to answer the question.\n\n&quot;<br>    f&quot;{schema}\n\n&quot;<br>    &quot;Translate the question into a valid SQL query.\n&quot;<br>    &quot;Do NOT make up tables or columns.\n&quot;<br>    &quot;Return only valid SQL.\n\n&quot;<br>    f&quot;Question: {user_input}\nSQL:&quot;<br>)</pre><p>📌 Why? This ensures the LLM uses only tables and columns from the actual database. This prevents hallucinations and aligns generation with schema reality.</p><h4>2. 🧰 Tool Routing via LangChain Agent</h4><p>The agent is initialized with a list of tools, each with a clear name and function:</p><ul><li>StrictSQLGenerator: Generates SQL-only responses</li><li>QuerySQLDataBaseTool: Executes raw SQL</li><li>Explain SQL: Explains what a query does</li><li>Info/List SQL Tables: Lists available tables and their metadata</li></ul><p>When a user types a question like:</p><p><em>“Top 5 coins by volume in March 2019”</em></p><p>LangChain routes the prompt through the agent → chooses the StrictSQLGenerator tool → formats prompt → sends to OpenAI → gets SQL → (optional) passes to execution or explanation tools.</p><pre>tools = [<br>    QuerySQLDataBaseTool(db=db),   # Executes SQL queries<br>    InfoSQLDatabaseTool(db=db),    # Provides metadata about tables/columns<br>    ListSQLDatabaseTool(db=db),    # Lists available tables<br>    LangchainTool(<br>        name=&quot;Explain SQL&quot;,<br>        func=lambda sql: ChatOpenAI().predict(f&quot;Explain this SQL: {sql}&quot;),<br>        description=&quot;Explains what the SQL query does&quot;<br>    ),<br>    LangchainTool(<br>        name=&quot;StrictSQLGenerator&quot;,<br>        func=strict_sql_generator,<br>        description=&quot;Converts natural language to SQL only&quot;<br>    )<br>]</pre><p>With these tools, the agent doesn’t just respond — it thinks, plans, and chooses the right tool based on your question. Whether you want to understand the schema, generate SQL from a question, or decode what a query means, the agent knows what to do — all without writing a single line of SQL yourself.</p><h4>3. 🧪 SQL Validation &amp; Auto-Correction</h4><p>Once SQL is generated, we validate it before execution:</p><pre>def validate_sql_tables(sql_query, db):<br>    actual_tables = get_actual_tables(db)<br>    sql_tables = extract_tables_from_sql(sql_query)<br>    return sql_tables - actual_tables</pre><p>If invalid tables are detected:</p><ul><li>The agent auto-prompts the LLM again to fix the SQL</li><li>Or shows a warning to the user with a “Fix” button</li></ul><p>🔄 This loop makes the system resilient and trustworthy<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z82Gkg3siopQXHL8KNEOyg.png" /><figcaption>Agentic Workflow for SQL Assistant</figcaption></figure><h3>🚀Running Locally or in Docker</h3><h4>✅ Option 1: Run Locally (Python)</h4><p><strong>Prerequisites:</strong></p><ul><li>Python 3.10 or 3.11</li><li>pip installed</li></ul><p><strong>Steps:</strong></p><pre># 1. Clone the repo<br>git clone https://github.com/vijay-vadali/agenticai-sql-assistant.git<br>cd agenticai-sql-assistant<br><br># 2. Create a virtual environment<br>conda create -n agenticai-sql-assistant -y<br>conda activate agenticai-sql-assistant<br><br># 3. Install dependencies<br>pip3 install -r requirements.txt<br><br># 4. Set your OpenAI key<br>export OPENAI_API_KEY=&quot;key&quot;<br><br># 5. Run the Streamlit app<br>streamlit run main.py</pre><h3>🐳 Option 2: Run via Docker</h3><p><strong>Dockerfile already included?</strong> Great!</p><p><strong>Steps:</strong></p><pre># 1. Clone the project<br>git clone https://github.com/vijay-vadali/agenticai-sql-assistant.git<br>cd agenticai-sql-assistant<br><br># 2. Build the Docker image<br>docker build -t agenticai-sql-assistant .<br><br># 3. Run the container<br>docker run -p 8501:8501 -e OPENAI_API_KEY=sk-... agenticai-sql-assistant</pre><p>Once it starts, open your browser and visit:<br> 👉 <a href="http://localhost:8501/">http://localhost:8501</a></p><h3>🧠 Conclusion</h3><p>In an era where data is abundant but access is often restricted to technical users, agentic AI offers a refreshing shift. This project showcased how a LangChain-powered agent — integrated with OpenAI, Streamlit, and a simple SQLite database — can empower <em>anyone</em> to query structured data using natural language.</p><p>By wrapping traditional tools like SQL in a conversational interface, we unlock value for product managers, analysts, marketers, and stakeholders who otherwise rely on technical teams for insights. More than just a chatbot, this assistant reasons, explains, and adapts — hallmarks of agentic intelligence.</p><p>Whether embedded in internal dashboards or public-facing tools, such agents represent a powerful new paradigm in human-data interaction.</p><p><a href="http://www.linkedin.com/in/vijaykvadali"><strong>LinkedIn</strong></a><strong> |👏 for my story</strong></p><p><strong>If you enjoy my content, Consider </strong><a href="https://ko-fi.com/vijayvadali"><strong>Buying me a Coffee</strong></a><strong>.</strong></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4df49b906595" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/agentic-ai-sql-assistant-4df49b906595">Agentic AI SQL Assistant</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>