<?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 Angelina Garnica on Medium]]></title>
        <description><![CDATA[Stories by Angelina Garnica on Medium]]></description>
        <link>https://medium.com/@angelinagarnica?source=rss-396f26498034------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qt0yeblsaQio_AYr.</url>
            <title>Stories by Angelina Garnica on Medium</title>
            <link>https://medium.com/@angelinagarnica?source=rss-396f26498034------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:35:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@angelinagarnica/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[From SQL Agent to Reasoning SQL Agent: A Leap in Intelligent Data Interaction]]></title>
            <link>https://medium.com/@angelinagarnica/from-sql-agent-to-reasoning-sql-agent-a-leap-in-intelligent-data-interaction-3aad58878b66?source=rss-396f26498034------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aad58878b66</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Angelina Garnica]]></dc:creator>
            <pubDate>Mon, 19 May 2025 00:45:05 GMT</pubDate>
            <atom:updated>2025-05-19T00:45:05.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmeYrDGp0JUbtmEWSBmPgw.jpeg" /><figcaption>Image by the author</figcaption></figure><p>Hey everyone! I’m excited to share some significant updates to my SQL agent. For those interested in diving into the full implementation, you can find the complete project on my GitHub repository here: <a href="https://github.com/AngelinaGarnica/Alora">https://github.com/AngelinaGarnica/Alora</a>.</p><p>Following up on my previous post (you can find the initial version and the motivation behind its creation <a href="https://medium.com/@angelinagarnica/alora-sql-gemini-agent-21c56d3181ac?source=friends_link&amp;sk=f6ad170c4716940cafd01ea26e79a17c"><em>here</em></a> ), one of the key improvements I envisioned was enabling the agent to utilize its tools more intelligently, discerning when to execute them and when it’s more appropriate to conclude the conversation or offer the user a data visualization.</p><p>In this blog post, I’ll delve into how I achieved these enhancements. My approach involved refining the use of LangGraph by incorporating a dedicated reasoning node, a human validation step, and a more intelligent charting tool. This new charting tool directly leverages the power of the LLM to generate visualization code, resulting in graphs that are more relevant to the data, more flexible in their design, and aesthetically more pleasing.</p><p><strong>Agent Architecture</strong></p><p>The updated architecture of my agent is structured as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*lauuaGAOvpBL6xrj3vB0kQ.png" /><figcaption>Agent Architecture Graph</figcaption></figure><ul><li><strong>Reasoning Node:</strong> Analyzes the query and determines the next best action (e.g., execute a tool, ask for clarification, or respond directly).</li><li><strong>Human Approval Node:</strong> A step to get explicit user confirmation before proceeding with potentially critical actions or using generated data.</li><li><strong>Graph Tool Node:</strong> A step to offer the user an option to visualize the results, typically after data has been retrieved and approved. When the user confirms the plot, this node interacts with the LLM to generate code for creating a relevant and well-designed chart.</li></ul><p><strong>Explanation of Improvements</strong></p><p>Let’s break down the key improvements:</p><ul><li><strong>Enhanced LangGraph Utilization:</strong> By introducing a dedicated reasoning node, the agent can now make more informed decisions about when to engage its tools. This node analyzes the user’s request, considers the available tools and their capabilities, and determines the most effective course of action. This prevents unnecessary tool executions and leads to a more efficient and focused interaction.</li><li><strong>Reasoning Node with Iterative Control:</strong> This crucial addition allows the agent to think step-by-step before acting. Furthermore, I’ve implemented controls to manage the iterative reasoning process. This includes mechanisms to prevent infinite loops in reasoning, set maximum reasoning steps, and introduce criteria for the agent to conclude its internal deliberation and proceed with an action. This ensures a more stable and predictable behavior.</li><li><strong>Human Approval Node:</strong> Implementing an optional human validation step adds a layer of control and transparency. Before executing a potentially complex action or presenting results, the agent can seek the user’s confirmation. This is particularly useful in scenarios where the user might want to review or modify the proposed action.</li><li><strong>Smarter Charting Tool:</strong> The new charting tool represents a significant leap forward. Instead of relying on pre-defined templates or less flexible methods, it directly communicates with the LLM. This enables the generation of visualization code that is:</li><li><strong>Data-Driven:</strong> The LLM understands the underlying data and creates charts that effectively represent its key insights.</li><li><strong>Highly Customizable:</strong> The generated code can be tailored to specific user preferences and data characteristics, allowing for a wider range of chart types and aesthetic options.</li><li><strong>Better Designed:</strong> The LLM can incorporate principles of data visualization best practices, resulting in clearer and more impactful charts.</li><li><strong>Enhanced Logging for Key Stages:</strong> To facilitate debugging, monitoring, and a deeper understanding of the agent’s workflow, I’ve implemented more comprehensive logging at critical stages.</li></ul><p><strong>Agent in Action</strong></p><p>To illustrate the improvements in the SQL agent’s capabilities, let’s look at some example queries and how the updated agent handles them, including when it intelligently decides wat kind of chart is necessary for the type of data:</p><ol><li><strong>“What is the average of the total in the invoices table?”</strong></li></ol><pre>python run.py &quot;What is the average of the total in the invoices table?&quot; </pre><ul><li><strong>Agent’s Reasoning:</strong> The result will be a numerical value.</li></ul><pre>INFO - [src.tools] [Tool: db_query_tool] Executing query: SELECT AVG(Total) FROM Invoice<br>INFO - [src.config] [Node: Reasoning] LLM Response: The average of the total in the invoices table is 5.65.<br>AI: The average of the total in the invoices table is 5.65.<br>Results: The average of the total in the invoices table is 5.65.<br>Is the data correct? (y/n): y<br>Would you like to generate a graph? (y/n): y</pre><pre>import plotly.graph_objects as go<br><br>fig = go.Figure(go.Indicator(<br>    mode = &quot;number+gauge&quot;,<br>    value = 5.65,<br>    title = {&#39;text&#39;: &quot;Average Invoice Total&quot;},<br>    gauge = {&#39;axis&#39;: {&#39;range&#39;: [None, 10]},<br>             &#39;threshold&#39; : {&#39;line&#39;: {&#39;color&#39;: &quot;red&quot;, <br>                            &#39;width&#39;: 4}, <br>                            &#39;thickness&#39;: 0.75, <br>                            &#39;value&#39;: 7}}))<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdN-ezKSSOZ3XQDRSk5hzw.png" /></figure><pre>Execution completed.<br>Final result: The average of the total in the invoices table is 5.65.</pre><p><strong>2. “How many invoices are in the table with a total amount greater than 15?”</strong></p><pre>python run.py &quot;How many invoices are in the table with a total amount greater than 15?&quot; </pre><ul><li><strong>Agent’s Reasoning:</strong></li></ul><pre>Raw query: How many invoices are in the table invoices with a total amount greater than 15?<br>INFO - [src.tools] [Tool: db_query_tool] Executing query: SELECT COUNT(*) FROM Invoice WHERE Total &gt; 15<br>AI: There are 11 invoices with a total amount greater than 15.<br>Results: There are 11 invoices with a total amount greater than 15.<br>Is the data correct? (y/n): y<br>Would you like to generate a graph? (y/n): y</pre><pre>import plotly.graph_objects as go<br><br>fig = go.Figure(go.Indicator(<br>    mode = &quot;number&quot;,<br>    value = 11,<br>    title = {&quot;text&quot;: &quot;Invoices with Total Amount &gt; 15&quot;},<br>))<br><br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*Og0pqRMcRvJBx1ZAncfkTQ.png" /></figure><pre>Execution completed.<br>Final result: There are 11 invoices with a total amount greater than 15.</pre><p><strong>3. “Which are the three billing countries with the highest invoice total?”</strong></p><pre>python run.py &quot;Which are the three billing countries with the highest invoice total?&quot;</pre><pre>INFO - [src.tools] [Tool: db_query_tool] Executing query: SELECT BillingCountry, SUM(Total) AS TotalInvoiceValue FROM Invoice GROUP BY BillingCountry ORDER BY TotalInvoiceValue DESC LIMIT 3;<br>AI: The three billing countries with the highest invoice totals are:<br><br>1. USA: $523.06<br>2. Canada: $303.96<br>3. France: $195.10<br>Is the data correct? (y/n): y<br>Would you like to generate a graph? (y/n): y</pre><pre>import plotly.express as px<br>import pandas as pd<br><br>data = {&#39;Country&#39;: [&#39;USA&#39;, &#39;Canada&#39;, &#39;France&#39;],<br>        &#39;Invoice Total&#39;: [523.06, 303.96, 195.10]}<br>df = pd.DataFrame(data)<br>fig = px.bar(df, x=&#39;Country&#39;, y=&#39;Invoice Total&#39;,<br>             title=&#39;Top 3 Billing Countries by Invoice Total&#39;,<br>             labels={&#39;Invoice Total&#39;: &#39;Invoice Total ($)&#39;},<br>             text_auto=True)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcfPJEkOLbKRpmVLRbTelQ.png" /></figure><p><strong>Conclusion</strong></p><p>I’m pleased with the advancements in this reasoning SQL agent, and I believe there’s significant potential for further development. Your feedback and suggestions for new features are welcome — please feel free to share your thoughts. To stay updated on the progress of this project and future explorations in intelligent data interaction, be sure to follow my upcoming blog posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aad58878b66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alora SQL Gemini Agent]]></title>
            <link>https://medium.com/@angelinagarnica/alora-sql-gemini-agent-21c56d3181ac?source=rss-396f26498034------2</link>
            <guid isPermaLink="false">https://medium.com/p/21c56d3181ac</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Angelina Garnica]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 19:02:29 GMT</pubDate>
            <atom:updated>2025-04-27T19:02:29.158Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>For years, my daily work revolved around databases. Answering questions, from the most basic to the most intricate, involved a constant immersion in the world of SQL, interrupting workflows to extract valuable information. How many active employees are there this month? How are they distributed by sector? What are the salary averages segmented by seniority and gender? Each query, however simple it seemed, could consume hours of my time.</p><p>Last year, the magical integration between natural language models and databases blew my mind. Seeing how an artificial intelligence could autonomously generate SQL queries was a true revelation. A message to my past self: <em>the era of tedious manual queries was about to end!</em></p><p>Although my professional background is mainly focused on traditional machine learning, this fascinating convergence propelled me headfirst into the universe of agents. The result is, quite simply, astonishing: the translation of natural language to SQL by LLMs seems like pure magic. To unlock this potential, all that’s needed is a good prompt and some code tools.</p><p>I must confess that venturing into the world of blogs is a novelty for me. The initial spark came from an interesting Kaggle and Google course that offered extra points for a publication (although I didn’t manage to make the deadline for the competition). This was the motivation I needed to share these ideas with you.</p><p>In this article, I will guide you through the process of creating my first SQL agent using LangChain and Gemini. This notebook was conceived for the aforementioned competition, and to illustrate its operation, I decided to use a well-known and public database: Chinook.</p><p><strong>Understanding Agents (Without Much Theory)</strong></p><p>To keep things agile, let’s briefly define an agent as an application with clear objectives, operating within a specific context and using the tools at its disposal to achieve its goals.</p><p><strong>Initial Setup: Preparing the Ground</strong></p><p>Before we dive into the code, make sure you have your Google API key handy. If you don’t have one yet, you can follow these simple instructions: <a href="https://ai.google.dev/gemini-api/docs/api-key">https://ai.google.dev/gemini-api/docs/api-key</a></p><p><em>Important clarification:</em> While the course focused on Gemini, the schema I will present to you is adaptable to any other large language model (LLM).</p><pre>#Install required packages<br>!pip install -qU &#39;langgraph==0.3.21&#39; &#39;langchain-google-genai==2.1.2&#39; &#39;langgraph-prebuilt==0.1.7&#39; &#39;langchain-community&#39;<br>!apt-get update<br>!apt-get install -y sqlite3</pre><p>Set up API Key:</p><pre>from google.colab import auth<br>auth.authenticate_user()<br><br>import os<br>os.environ[&quot;GOOGLE_API_KEY&quot;] = &quot;your_api_key&quot;</pre><p>Set up database and imports:</p><pre>from langchain_community.utilities import SQLDatabase<br>from langchain_core.tools import tool<br>from langchain_core.runnables import Runnable<br>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br><br>import ast<br>import sqlite3<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>from difflib import get_close_matches<br><br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langchain.agents import create_tool_calling_agent, AgentExecutor</pre><p>Load example data set:</p><pre># Download and create Chinook database<br>!curl -s https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql | sqlite3 Chinook.db<br>db = SQLDatabase.from_uri(&quot;sqlite:///Chinook.db&quot;)</pre><p><strong>Our Agent’s Tools</strong></p><p>For our agent to interact with the database intelligently, we defined the following tools:</p><ul><li><em>db_query_tool</em>: Executes an SQL query and returns the obtained results.</li><li><em>list_tables</em>: Displays all the available tables in the database, helping the agent identify the correct table for its query.</li><li><em>describe_table</em>: Provides the list of columns and their data types for a specific table. This is crucial for the agent to build valid SQL queries.</li><li><em>find_similar_table</em>: Searches for the most similar table name within the database, which helps prevent errors when the agent is unsure of the exact name.</li></ul><pre>@tool<br>def db_query_tool(sql: str) -&gt; list:<br>    &quot;&quot;&quot;Execute an SQL statement and return the results.&quot;&quot;&quot;<br>    print(f&quot;Executing SQL: {sql}&quot;)<br>    try:<br>        result = db.run(sql)<br>        return result<br>    except Exception as e:<br>        print(f&quot;[ERROR] {e}&quot;)<br>        return [[&quot;⚠️ I can&#39;t find information for your question, can you rephrase it?&quot;]]<br><br>@tool<br>def list_tables() -&gt; list:<br>    &quot;&quot;&quot;List all tables in the database.&quot;&quot;&quot;<br>    return db.get_usable_table_names()<br><br>from langchain_core.tools import tool<br><br>@tool<br>def describe_table(table_name: str) -&gt; list[tuple[str, str]]:<br>    &quot;&quot;&quot;Return a list of column names and types from the given table name.&quot;&quot;&quot;<br>    try:<br>        # Get available table names from the DB<br>        available_tables = db.get_usable_table_names()<br>        normalized_table = next(<br>            (t for t in available_tables if t.lower() == table_name.lower()), None<br>        )<br><br>        if not normalized_table:<br>            raise ValueError(f&quot;Table &#39;{table_name}&#39; not found in database.&quot;)<br><br>        # Use PRAGMA to get schema<br>        result = db.run(f&quot;PRAGMA table_info({normalized_table});&quot;)<br><br>        # Handle if result is a string (sometimes happens)<br>        if isinstance(result, str):<br>            import ast<br>            result = ast.literal_eval(result)<br><br>        if not isinstance(result, list) or not result:<br>            raise ValueError(f&quot;No schema found for table &#39;{normalized_table}&#39;.&quot;)<br><br>        # Each row from PRAGMA is: (cid, name, type, notnull, dflt_value, pk)<br>        return [(row[1], row[2]) for row in result]<br><br>    except Exception as e:<br>        print(f&quot;Error describing table &#39;{table_name}&#39;: {e}&quot;)<br>        return []<br><br>@tool<br>def find_similar_table(table_name: str) -&gt; str:<br>    &quot;&quot;&quot;Find the most similar table name in the database (case-insensitive).&quot;&quot;&quot;<br>    print(f&quot; - DB CALL: find_similar_table({table_name})&quot;)<br><br>    all_tables = db.get_usable_table_names()<br>    lower_map = {t.lower(): t for t in all_tables}<br><br>    # Exact case-insensitive match<br>    if table_name.lower() in lower_map:<br>        return lower_map[table_name.lower()]<br><br>    # Try to find a close match<br>    close = get_close_matches(table_name.lower(), lower_map.keys(), n=1, cutoff=0.6)<br>    if close:<br>        return lower_map[close[0]]<br><br>    return &quot;No similar table found.&quot;</pre><p><strong>Bringing the Agent to Life: The Heart of the Interaction</strong></p><p>One of the crucial stages in creating our agent is defining the prompt. After several tests, I discovered that the most effective strategy was to describe in detail each of the tools we provided to the agent, along with a clear list of the steps it must follow to achieve its objective.</p><pre>prefix = &quot;&quot;&quot;You are a helpful SQL assistant that translates natural language questions<br>into optimized SQL queries for a SQLite database. You have access to the following tools:<br><br>- list_tables: Returns the names of all tables.<br>- describe_table: Given a table name, returns its schema.<br>- db_query_tool: Executes SQL queries and returns results.<br>- find_similar_table: Given a column hint (e.g. &quot;country&quot;, &quot;name&quot;), suggests which tables contain that column.<br><br>When generating SQL queries, always:<br><br>1. Use list_tables() if you&#39;re unsure of the table name.<br>2. Use describe_table() to understand the schema of a table.<br>3. Use find_similar_table() if you are not sure where a column (e.g., &quot;country&quot;) is stored.<br>4. Write optimized SQL — avoid SELECT * unless necessary.<br>5. Use GROUP BY and aggregations (COUNT, GROUP BY, AVG, SUM, etc.) when appropriate.<br>6. Format output in a readable way.<br>7. When the output is list-like (e.g., genres, artists), ask: &quot;Would you like to plot this?&quot;<br><br>Your job is to think step-by-step to build correct SQL queries by using these tools to clarify structure before querying.<br>&quot;&quot;&quot;<br><br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.0-flash&quot;)<br><br>tools = [db_query_tool, list_tables, describe_table, find_similar_table]<br><br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, prefix),<br>    (&quot;user&quot;, &quot;{input}&quot;),<br>    #(&quot;placeholder&quot;, &quot;{agent_scratchpad}&quot;),<br>    MessagesPlaceholder(variable_name=&quot;agent_scratchpad&quot;)<br>])<br><br>agent = create_tool_calling_agent(llm, tools, prompt)<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True)</pre><p>Let’s run some tests,</p><pre>query = &quot;How many artist are there?&quot;<br><br>response = agent_executor.invoke({&quot;input&quot;: query})<br>print(response[&quot;output&quot;])</pre><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `list_tables` with `{}`<br><br><br>[&#39;Album&#39;, &#39;Artist&#39;, &#39;Customer&#39;, &#39;Employee&#39;, &#39;Genre&#39;, &#39;Invoice&#39;, &#39;InvoiceLine&#39;, &#39;MediaType&#39;, &#39;Playlist&#39;, &#39;PlaylistTrack&#39;, &#39;Track&#39;]<br>Invoking: `describe_table` with `{&#39;table_name&#39;: &#39;Artist&#39;}`<br><br><br>[(&#39;ArtistId&#39;, &#39;INTEGER&#39;), (&#39;Name&#39;, &#39;NVARCHAR(120)&#39;)]<br>Invoking: `db_query_tool` with `{&#39;sql&#39;: &#39;SELECT COUNT(*) FROM Artist&#39;}`<br><br><br>Executing SQL: SELECT COUNT(*) FROM Artist<br>[(275,)]There are 275 artists.<br><br>&gt; Finished chain.<br>There are 275 artists.</pre><p>Amazing! Let’s try a more complex query</p><pre>query = &quot;How many albums do artists have on average?&quot;<br><br>response = agent_executor.invoke({&quot;input&quot;: query})<br>print(response[&quot;output&quot;])</pre><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `list_tables` with `{}`<br>responded: I need to find the tables containing information about artists and albums. I&#39;ll start by listing the available tables.<br><br>[&#39;Album&#39;, &#39;Artist&#39;, &#39;Customer&#39;, &#39;Employee&#39;, &#39;Genre&#39;, &#39;Invoice&#39;, &#39;InvoiceLine&#39;, &#39;MediaType&#39;, &#39;Playlist&#39;, &#39;PlaylistTrack&#39;, &#39;Track&#39;]<br>Invoking: `describe_table` with `{&#39;table_name&#39;: &#39;Album&#39;}`<br>responded: I need to find out how albums and artists are related. I will describe the `Album` and `Artist` tables.<br><br>[(&#39;AlbumId&#39;, &#39;INTEGER&#39;), (&#39;Title&#39;, &#39;NVARCHAR(160)&#39;), (&#39;ArtistId&#39;, &#39;INTEGER&#39;)]<br>Invoking: `describe_table` with `{&#39;table_name&#39;: &#39;Artist&#39;}`<br>responded: I need to find out how albums and artists are related. I will describe the `Album` and `Artist` tables.<br><br>[(&#39;ArtistId&#39;, &#39;INTEGER&#39;), (&#39;Name&#39;, &#39;NVARCHAR(120)&#39;)]<br>Invoking: `db_query_tool` with `{&#39;sql&#39;: &#39;SELECT AVG(album_count) FROM (SELECT ArtistId, COUNT(*) AS album_count FROM Album GROUP BY ArtistId)&#39;}`<br><br><br>Executing SQL: SELECT AVG(album_count) FROM (SELECT ArtistId, COUNT(*) AS album_count FROM Album GROUP BY ArtistId)<br>[(1.7009803921568627,)]The average number of albums per artist is approximately 1.70.<br><br>&gt; Finished chain.<br>The average number of albums per artist is approximately 1.70.</pre><p>Let’s go again!</p><pre>query = &quot;Who is the artist with the greatest number of albums?&quot;<br><br>response = agent_executor.invoke({&quot;input&quot;: query})<br>print(response[&quot;output&quot;])</pre><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `list_tables` with `{}`<br>responded: Okay, I need to find out which artist has the most albums. Here&#39;s how I&#39;ll do it:<br><br>1.  **List tables:** I&#39;ll start by listing the tables in the database to understand the available data.<br>2.  **Identify relevant tables:** I&#39;ll look for tables that likely contain information about artists and albums.<br>3.  **Describe tables:** I&#39;ll describe the identified tables to understand their schema (column names and types).<br>4.  **Construct SQL query:** I&#39;ll write an SQL query to count the number of albums for each artist and find the artist with the maximum count.<br>5.  **Execute query:** I&#39;ll execute the SQL query using the `db_query_tool`.<br>6.  **Return result:** I&#39;ll return the name of the artist with the most albums.<br><br>Let&#39;s start by listing the tables.<br><br>[&#39;Album&#39;, &#39;Artist&#39;, &#39;Customer&#39;, &#39;Employee&#39;, &#39;Genre&#39;, &#39;Invoice&#39;, &#39;InvoiceLine&#39;, &#39;MediaType&#39;, &#39;Playlist&#39;, &#39;PlaylistTrack&#39;, &#39;Track&#39;]<br>Invoking: `describe_table` with `{&#39;table_name&#39;: &#39;Artist&#39;}`<br>responded: Okay, the tables are Album, Artist, Customer, Employee, Genre, Invoice, InvoiceLine, MediaType, Playlist, PlaylistTrack, and Track.<br><br>I need to find the artist with the greatest number of albums. The relevant tables are likely &quot;Artist&quot; and &quot;Album&quot;. I should examine the schema of these tables to understand how they are related.<br><br>[(&#39;ArtistId&#39;, &#39;INTEGER&#39;), (&#39;Name&#39;, &#39;NVARCHAR(120)&#39;)]<br>Invoking: `describe_table` with `{&#39;table_name&#39;: &#39;Album&#39;}`<br>responded: Okay, the tables are Album, Artist, Customer, Employee, Genre, Invoice, InvoiceLine, MediaType, Playlist, PlaylistTrack, and Track.<br><br>I need to find the artist with the greatest number of albums. The relevant tables are likely &quot;Artist&quot; and &quot;Album&quot;. I should examine the schema of these tables to understand how they are related.<br><br>[(&#39;AlbumId&#39;, &#39;INTEGER&#39;), (&#39;Title&#39;, &#39;NVARCHAR(160)&#39;), (&#39;ArtistId&#39;, &#39;INTEGER&#39;)]<br>Invoking: `db_query_tool` with `{&#39;sql&#39;: &#39;SELECT Artist.Name, COUNT(Album.AlbumId) AS AlbumCount FROM Artist INNER JOIN Album ON Artist.ArtistId = Album.ArtistId GROUP BY Artist.ArtistId ORDER BY AlbumCount DESC LIMIT 1&#39;}`<br><br><br>Executing SQL: SELECT Artist.Name, COUNT(Album.AlbumId) AS AlbumCount FROM Artist INNER JOIN Album ON Artist.ArtistId = Album.ArtistId GROUP BY Artist.ArtistId ORDER BY AlbumCount DESC LIMIT 1<br>[(&#39;Iron Maiden&#39;, 21)]The artist with the greatest number of albums is Iron Maiden, with 21 albums.<br><br>&gt; Finished chain.<br>The artist with the greatest number of albums is Iron Maiden, with 21 albums.</pre><p><strong>Going a Step Further: Generating Charts (When the Data Allows)</strong></p><p>Observing the agent’s ability to accurately translate natural language into SQL queries, I decided to explore an additional challenge: allowing the user to generate charts if the nature of the data permitted.</p><p>This functionality added complexity to the development, as the agent needed to maintain a “memory” of the SQL query output to use it in chart creation.</p><pre>class GeminiPlotSuggestingAgentWithMemory:<br>    def __init__(self, agent_executor):<br>        self.agent_executor = agent_executor<br>        self.last_plot_data = None<br><br>    def invoke(self, input: dict, config=None) -&gt; dict:<br>        user_input = input.get(&quot;input&quot;, &quot;&quot;).strip().lower()<br><br>        if user_input in [&quot;yes&quot;, &quot;sure&quot;, &quot;yeah&quot;, &quot;please do&quot;, &quot;go ahead&quot;, &quot;ok&quot;]:<br>            if self.last_plot_data:<br>                self.plot_last_result()<br>                return {&quot;output&quot;: &quot;&quot;}<br>            else:<br>                return {&quot;output&quot;: &quot;Sorry, I don&#39;t have data to plot. Ask a new question first.&quot;}<br><br>        result = self.agent_executor.invoke(input)<br>        output = result.get(&quot;output&quot;, &quot;&quot;)<br><br>        sql_data = self._extract_sql_data_from_intermediate(result)<br>        if sql_data:<br>            self.last_plot_data = sql_data<br>            return {<br>                &quot;output&quot;: output,<br>                &quot;follow_up&quot;: &quot;Would you like to plot this?&quot;<br>            }<br><br>        # No SQL result found<br>        self.last_plot_data = None<br>        return {&quot;output&quot;: output}<br><br>    def _extract_sql_data_from_intermediate(self, result):<br>        steps = result.get(&quot;intermediate_steps&quot;, [])<br><br>        for step in steps:<br>            if not isinstance(step, tuple):<br>                continue<br>            action, observation = step<br><br>            if hasattr(action, &quot;tool&quot;) and action.tool == &quot;db_query_tool&quot;:<br>              try:<br>                # If observation is already a list of tuples, just return it<br>                  if isinstance(observation, list) and all(isinstance(x, tuple) for x in observation):<br>                    return observation<br><br>                  # If it&#39;s a string representation of a list of tuples, evaluate it safely<br>                  data = ast.literal_eval(observation)<br>                  if isinstance(data, list) and all(isinstance(x, tuple) and len(x) == 2 for x in data):<br>                    return data<br>                  else:<br>                    print(&quot;Parsed result is not a valid list of pairs.&quot;)<br>              except Exception as e:<br>                print(f&quot;Could not parse SQL result for plotting: {e}&quot;)<br><br>        print(&quot;No valid SQL result found in intermediate_steps.&quot;)<br>        return []<br><br><br>    def plot_last_result(self):<br>        if not self.last_plot_data:<br>            print(&quot;No data to plot.&quot;)<br>            return<br><br>        labels, counts = zip(*self.last_plot_data)<br>        plt.figure(figsize=(10, 4))<br>        plt.bar(labels, counts, color=&quot;skyblue&quot;)<br>        plt.xticks(rotation=45)<br>        plt.title(&quot;Distribution&quot;)<br>        plt.ylabel(&quot;Count&quot;)<br>        plt.tight_layout()<br>        plt.show()</pre><p>Let’s try it,</p><pre>query = &quot;How many employees are there per city in the employee table?&quot;<br><br>response = agent_with_followup.invoke({&quot;input&quot;: query})<br>print(response[&quot;output&quot;])</pre><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `list_tables` with `{}`<br>responded: Okay, I need to figure out the table name and schema first.<br><br>[&#39;Album&#39;, &#39;Artist&#39;, &#39;Customer&#39;, &#39;Employee&#39;, &#39;Genre&#39;, &#39;Invoice&#39;, &#39;InvoiceLine&#39;, &#39;MediaType&#39;, &#39;Playlist&#39;, &#39;PlaylistTrack&#39;, &#39;Track&#39;]<br>Invoking: `describe_table` with `{&#39;table_name&#39;: &#39;Employee&#39;}`<br><br><br>[(&#39;EmployeeId&#39;, &#39;INTEGER&#39;), (&#39;LastName&#39;, &#39;NVARCHAR(20)&#39;), (&#39;FirstName&#39;, &#39;NVARCHAR(20)&#39;), (&#39;Title&#39;, &#39;NVARCHAR(30)&#39;), (&#39;ReportsTo&#39;, &#39;INTEGER&#39;), (&#39;BirthDate&#39;, &#39;DATETIME&#39;), (&#39;HireDate&#39;, &#39;DATETIME&#39;), (&#39;Address&#39;, &#39;NVARCHAR(70)&#39;), (&#39;City&#39;, &#39;NVARCHAR(40)&#39;), (&#39;State&#39;, &#39;NVARCHAR(40)&#39;), (&#39;Country&#39;, &#39;NVARCHAR(40)&#39;), (&#39;PostalCode&#39;, &#39;NVARCHAR(10)&#39;), (&#39;Phone&#39;, &#39;NVARCHAR(24)&#39;), (&#39;Fax&#39;, &#39;NVARCHAR(24)&#39;), (&#39;Email&#39;, &#39;NVARCHAR(60)&#39;)]<br>Invoking: `db_query_tool` with `{&#39;sql&#39;: &#39;SELECT City, COUNT(*) FROM Employee GROUP BY City&#39;}`<br><br><br>Executing SQL: SELECT City, COUNT(*) FROM Employee GROUP BY City<br>[(&#39;Calgary&#39;, 5), (&#39;Edmonton&#39;, 1), (&#39;Lethbridge&#39;, 2)]There are 5 employees in Calgary, 1 in Edmonton, and 2 in Lethbridge.<br><br>&gt; Finished chain.<br>There are 5 employees in Calgary, 1 in Edmonton, and 2 in Lethbridge. Would you like to plot this?</pre><p>After verifying that the response is a list and that it can be plotted, the agent asks the user if they want to visualize the result.</p><pre>#Answer &quot;yes&quot;:<br>agent_with_followup.invoke({&quot;input&quot;: &quot;yes&quot;})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5g8xvlKG2i68id4C-CTkXg.png" /></figure><p>Success! The agent has now successfully generated a chart based on the query results.</p><p><strong>Next Steps: The Road Ahead</strong></p><p>While keeping up with the rapid advancements and diverse applications of large language models is a constant challenge, my agent, although basic and with much room for improvement, represents a step forward in solving problems that previously consumed a lot of time.</p><p>Some key areas I plan to focus on for future improvements include:</p><ul><li><strong>Robust error handling:</strong> Implementing mechanisms to identify and manage errors in SQL queries or user interaction.</li><li><strong>Expansion of tools:</strong> Integrating new tools that allow the agent to perform more complex tasks.</li><li><strong>Greater versatility in visualizations:</strong> Offering more chart options and customization to adapt to different data types and visualization needs.</li><li><strong>More fluid user interactions:</strong> Improving the agent’s ability to understand complex questions and provide more conversational responses.</li><li><strong>Incorporation of evaluation metrics:</strong> Implementing tools to measure the agent’s performance and accuracy.</li></ul><p>Thank you for joining me on this exploration! To see all the steps, code, and experiments, I invite you to visit the complete notebook on Kaggle: <a href="https://www.kaggle.com/code/agarnica/alora-sql-agent.">https://www.kaggle.com/code/agarnica/alora-sql-agent.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21c56d3181ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>