<?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 Gautham Gondi on Medium]]></title>
        <description><![CDATA[Stories by Gautham Gondi on Medium]]></description>
        <link>https://medium.com/@gauthamnagendra?source=rss-c750cf5dd6f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5NoFlXnzVu_gBb5o</url>
            <title>Stories by Gautham Gondi on Medium</title>
            <link>https://medium.com/@gauthamnagendra?source=rss-c750cf5dd6f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:12:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauthamnagendra/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[A UI Glitch Cost Me $256. So I Built an AI-Powered Bill Tracker to Fight Back.]]></title>
            <link>https://medium.com/@gauthamnagendra/a-ui-glitch-cost-me-256-so-i-built-an-ai-powered-bill-tracker-to-fight-back-63e8459430d9?source=rss-c750cf5dd6f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/63e8459430d9</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Gautham Gondi]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 04:25:45 GMT</pubDate>
            <atom:updated>2026-01-12T04:25:45.498Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I used Python, iOS Shortcuts, and OpenAI to solve the “Silent Failure” problem in my personal finances.</h4><p>I manage data pipelines that process billions of events daily. I design architectures that can’t afford a single dropped message. I obsess over retries, dead-letter queues, and 99.99% availability.</p><p>And yet, last month, I missed my rent payment.</p><p>Not because I didn’t have the money. Not because I forgot. I missed it because of a “silent failure.”</p><p>My landlord’s payment portal showed AutoPay as “Active.” I checked it; the UI gave me a green light. But behind the scenes, the backend had deactivated it without sending a single notification or email.</p><p>The result? A missed payment and an instant <strong>$256 late fee</strong> (10% of my rent).</p><p>That was the moment I realized: <strong>I can’t afford to trust these black-box systems with my financial peace of mind.</strong> If the UI says one thing and the backend does another, I’m the one paying the price.</p><p>We often build tailored observability solutions for our companies, but we rarely apply that same engineering mindset to our personal lives.</p><p>So, I spent the weekend building my own solution.</p><h3>Why I Didn’t Just Build an App (The “Walled Garden” Problem)</h3><p>As a developer, my first instinct was standard: <em>I’ll just build a quick iOS app.</em></p><p>I don’t know Swift or React Native, but in 2026, that hardly matters. With AI coding assistants like <strong>AntiGravity</strong> or <strong>Cline</strong>, I could generate a functional iOS app in an afternoon. The code isn’t the hard part anymore.</p><p><strong>Deploying it to my own phone is the nightmare.</strong></p><p>Because I use an iPhone, I live in Apple’s “Walled Garden.” If you want to run your own code on your own device, you face two bad options:</p><ol><li><strong>Pay the “Apple Tax”:</strong> Shell out $99/year for a Developer Program membership just to install my own software.</li><li><strong>The “Sideload” Dance:</strong> This is a hardware risk. I didn’t want to rely on sideloading methods that might complicate things if I ever need a hardware repair at the Genius Bar.</li></ol><p>That’s when my <strong>years of data engineering experience</strong> kicked in.</p><p>I realized I was trying to solve a data problem with a UI solution. I was thinking about “screens” and “buttons” when I should have been thinking about <strong>events</strong> and <strong>pipelines</strong>.</p><p>In my day job, when we need to ingest data, we don’t build a custom GUI for every source. We build an ingestion pipeline. I realized my iPhone isn’t a place to host an app; it’s simply an edge node emitting a stream of high-value events (SMS notifications).</p><p>I didn’t need an App. I needed a <strong>Data Pipeline</strong>.</p><h3>The Architecture: Trust, But Verify</h3><p>I didn’t want a complex SaaS product with a fancy dashboard. I wanted <strong>certainty</strong>.</p><p>I needed a system that would:</p><ol><li><strong>Capture</strong> every transaction (without me typing anything).</li><li><strong>Analyze</strong> the spending (distinguishing “Rent” from “Coffee”).</li><li><strong>Alert</strong> me immediately if a critical bill didn’t clear by a specific date.</li></ol><p>Here is the event-driven architecture I built using <strong>iOS Shortcuts, Python, SQLite, OpenAI, and Discord</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPLCdeg5jxKkTjrqlV1Xyg.png" /><figcaption>A visual breakdown of the ‘Bill Tracker’ project. On the left, the <strong>“Silent Failure”</strong> of a payment portal UI glitch that led to a $256 late fee. The center shows the <strong>event-driven architecture</strong>: bank SMS notifications are captured by iOS Shortcuts and sent to Discord, where a Python bot uses a SQLite database for idempotency and OpenAI for intelligent categorization. On the right, <strong>“Total Control”</strong> is achieved with a Discord bot providing a daily, verified report, ensuring financial peace of mind.</figcaption></figure><p>Let’s break down the stack.</p><h3>1. The Trigger: iOS Shortcuts (The Bridge)</h3><p>This was the missing link. Most banks have terrible APIs, but they all send SMS or App notifications.</p><p>I realized my phone is effectively an edge device receiving a stream of financial events. I just needed to forward that stream to a place where I could process it.</p><p>I set up an Apple Shortcut automation:</p><ul><li><strong>Trigger:</strong> When I receive a message from [Bank Name]…</li><li><strong>Action:</strong> POST the message content to a private Discord Webhook.</li></ul><p>Cost: <strong>$0</strong>. Effort: <strong>&lt; 5 minutes</strong>.</p><h3>2. The Message Queue: Discord</h3><p>Now, every transaction lands in a private Discord channel. This acts as my persistent message bus. It’s searchable, timestamped, and accessible from anywhere.</p><h3>3. The Memory: SQLite</h3><p>Before doing any AI magic, I needed a state store. I spun up a lightweight SQLite database on a Railway server.</p><p>Why database?</p><ul><li><strong>Idempotency:</strong> I store the unique Discord message_id. This ensures that even if my script runs 50 times, I never double-count a transaction.</li><li><strong>Context Window Management:</strong> I only want to send <em>new</em> messages to OpenAI. SQLite remembers what we’ve already processed, keeping my API costs to pennies.</li></ul><p><strong>SQL</strong></p><pre>CREATE TABLE IF NOT EXISTS payments (<br>    id INTEGER PRIMARY KEY AUTOINCREMENT,<br>    message_id TEXT UNIQUE,<br>    date TEXT NOT NULL,<br>    category TEXT NOT NULL,<br>    amount REAL,<br>    description TEXT,<br>    raw_message TEXT<br>);  </pre><h3>4. The Brain: OpenAI (GPT-5-mini)</h3><p>Bank transaction messages are a mess of unstructured text.</p><ul><li><em>“AutoPay of $1,500.00 processed for “</em>BELL-<em>XXX”</em></li><li><em>“Purchase authorized on 01/12 AMEX EPAYMENT”</em></li></ul><p>Writing Regex for this is a nightmare. It’s brittle and breaks whenever the bank changes their template. Instead, I use an LLM.</p><p>The Python script batches the new messages from Discord and sends them to OpenAI with a prompt like this:</p><pre>prompt = f&#39;&#39;&#39;Analyze these financial transaction messages and identify bill payments.<br><br>Known bill categories:<br>{categories_hint}<br><br>Messages:<br>{messages_text}<br><br>For each bill payment found, extract:<br>1. category - The bill type (use names from the list above or create new ones if needed)<br>2. amount - The dollar amount (number only, no $)<br>3. description - Brief description of the transaction<br>4. message_index - The message number specified above (e.g. 0 for &quot;Message 0&quot;)<br>5. payment_date - The date the payment was made/processed as found in the text (e.g. &quot;12/18/25&quot;, &quot;12/15/2025&quot;). Format as MM/DD/YYYY if possible. If not found in text, leave null.<br><br>Look for these patterns:<br>- &quot;AutoPay of $X was processed&quot;<br>- &quot;pre-authorized payment to X was deducted&quot;<br>- &quot;payment to X was deducted&quot;<br>- &quot;payment was credited to your account&quot; (payment made to credit card)<br>- &quot;Bill Payment&quot;<br><br>Return a JSON object with a single key &quot;payments&quot; containing an array of payment objects.<br>Only include actual bill payments (money leaving account or credit card payments), not transfers or income.<br>Note: &quot;payment was credited to your account&quot; typically indicates a credit card payment.<br>For refunds/deposits, look for context clues to distinguish from actual bill payments.<br><br>Example JSON Object:<br>{{<br>  &quot;payments&quot;: [<br>    {{&quot;category&quot;: &quot;Rent&quot;, &quot;amount&quot;: 1500.00, &quot;description&quot;: &quot;Monthly rent payment to landlord&quot;, &quot;message_index&quot;: 0}}<br>  ]<br>}}<br><br>If no bill payments found, return empty array: {{ &quot;payments&quot;: [] }}&#39;&#39;&#39;</pre><p>The AI handles the fuzzy matching. It knows that “BELL-XXX” is likely my apartment complex based on the context and configuration I provide, and it ignores my Starbucks runs.</p><h3>5. The Safety Net: The Daily Report</h3><p>This is the piece that prevents the $256 fee.</p><p>Every morning, a cron job runs a check. It compares the processed payments in SQLite against a master list of “Required Monthly Bills.”</p><p>It posts a summary back to Discord:</p><p><strong><em>📊 Bill Tracker Report</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KgjAHDYgARDflkTP5_tHg.png" /><figcaption>A daily snapshot from the ‘Bill Tracker’ Discord bot, showing paid bills (green checks) and pending ones (red crosses) for the current and upcoming month. This automated summary ensures critical payments like Rent are never missed.</figcaption></figure><h3>Why This Matters</h3><p>It’s not just about saving money (though the ROI on this project was immediate). It’s about <strong>Control</strong>.</p><p>When you rely on a landlord’s portal or a generic finance app, you are relying on their uptime, their UI logic, and their database integrity. When you build your own event stream, you own the data.</p><h3>Key Engineering Takeaways:</h3><ol><li><strong>LLMs are the new Regex:</strong> For personal projects, trading a few cents in API credits is worth hours of saved time writing parsing logic.</li><li><strong>Idempotency is non-negotiable:</strong> Whether it’s a Kafka pipeline at work or a discord bot at home, never process the same event twice.</li><li><strong>Simple architectures win:</strong> I didn’t need a React frontend or a Postgres cluster. A Python script and a flat file DB running on a server solved the problem perfectly.</li></ol><p>Sometimes the best engineering projects aren’t just the ones you build to change the world — they’re also the ones you build to save yourself $256.</p><h3>Try it yourself</h3><p>I’ve open-sourced the code. It includes the Python logic, the SQLite schema, and the Discord webhook setup.</p><p><a href="https://github.com/gautham-gn/os-bill-tracker"><strong>[Link to GitHub Repository]</strong></a></p><p><em>If you’ve ever been burned by a “technical glitch,” let me know in the comments. I’d love to hear how other engineers are automating their personal lives.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63e8459430d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Grocery Store Hack: How I Built an AI Assistant to Master Kroger’s Aisles]]></title>
            <link>https://medium.com/@gauthamnagendra/the-ultimate-grocery-store-hack-how-i-built-an-ai-assistant-to-master-krogers-aisles-bba132ec017c?source=rss-c750cf5dd6f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba132ec017c</guid>
            <category><![CDATA[grocery-shopping]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Gautham Gondi]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 04:18:49 GMT</pubDate>
            <atom:updated>2025-03-24T14:53:09.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A futuristic, bird’s-eye view of a modern grocery store with glowing blue navigation lines on the floor, guiding paths between aisles. A hovering smartphone displays a chat interface showing a shopping list and aisle numbers. Shopping carts are scattered throughout the store. The scene has a high-tech ambiance with soft blue lighting and a color scheme subtly inspired by Kroger with shades of blue and white." src="https://cdn-images-1.medium.com/max/1024/1*HkfV9MTSE278hrcozGmHSA.jpeg" /></figure><p>Have you ever found yourself wandering aimlessly through the endless aisles of a grocery store, desperately searching for that one ingredient you need? What should be a quick 30-minute grocery run turns into a 3-hour expedition as you navigate from produce to dairy to the international foods section, all while being strategically tempted by products you never intended to buy.</p><p>This weekly ritual of inefficient grocery shopping is by design. Grocery chains deliberately organize their stores to maximize your time inside, exposing you to as many products as possible. The longer you wander, the more likely you are to make impulse purchases.</p><p>But what if technology could help you outsmart this system? That’s exactly what I set out to build: an LLM-powered shopping assistant that tells you precisely where to find each item on your list at your nearest Kroger store.</p><h3>The Problem: Grocery Shopping Inefficiency</h3><p>As someone who spends upwards of two to three hours each weekend grocery shopping for my family, I’ve experienced first hand how frustrating it can be to locate specific items in huge supermarkets. The typical grocery shopping experience involves:</p><ol><li>Creating a shopping list</li><li>Driving to the store</li><li>Wandering aimlessly through aisles</li><li>Backtracking multiple times when you forget items</li><li>Eventually finding what you need (or giving up and substituting)</li></ol><p>This inefficiency is particularly painful for <a href="https://www.instacart.com/">Instacart</a> shoppers and other delivery service providers who shop on behalf of customers. Their income depends on speed and efficiency — every minute spent searching for products directly impacts their bottom line.</p><h3>The Solution: An LLM-Powered Shopping Assistant</h3><p>To tackle this problem, I built a Kroger Shopping Assistant that leverages Large Language Models (LLMs) like GPT-4 combined with Kroger’s API to create a conversational interface for efficient shopping. Here’s what it does:</p><ol><li>Automatically detects your location</li><li>Identifies the nearest Kroger store</li><li>Allows you to ask about any product in natural language</li><li>Returns precise information about:<br>- Product availability<br>- Regular and promotional prices<br>- Exact aisle and section locations<br>- Store details</li></ol><p>The magic happens when you can simply ask: “I’d like to get details about all these items at the nearest Kroger location please: Fage Yogurt and Roma Tomatoes!” and receive structured information about where each item is located in your specific Kroger store.</p><h3>How It Works: The Technical Architecture</h3><p>Let’s dig into how this shopping assistant works under the hood:</p><h3>1. Importing Necessary Libraries and Env Setup</h3><pre>import requests<br>import geocoder<br>from dotenv import load_dotenv<br>from openai import OpenAI<br>import gradio as gr<br><br>load_dotenv(override=True)<br>openai_api_key = os.getenv(&#39;OPENAI_API_KEY&#39;)<br>openai = OpenAI()<br>MODEL = &quot;gpt-4o-mini&quot;</pre><h3>2. Location Detection and Store Identification</h3><p>The system first needs to know which store to search. It uses the geocoder library to determine your approximate location based on IP address:</p><pre>def get_user_lat_lon():<br>    g = geocoder.ip(&#39;me&#39;)<br>    latlng = g.latlng<br>    latitude = latlng[0]<br>    longitude = latlng[1]<br>    return latitude, longitude </pre><p>With your coordinates, it queries the Kroger API to find the closest store:</p><pre>def get_location_id(lat, long, access_key=KROGER_ACCESS_KEY):<br>    &quot;&quot;&quot;<br>    Fetch the nearest Kroger location ID based on latitude and longitude.<br>    <br>    Args:<br>        lat (float): Latitude of the desired location.<br>        long (float): Longitude of the desired location.<br>        access_key (str): Authorization token for the API.<br>    <br>    Returns:<br>        str: The location ID if found, else None.<br>    &quot;&quot;&quot;<br>    url = &quot;https://api-ce.kroger.com/v1/locations&quot;<br>    params = {<br>        &quot;filter.latLong.near&quot;: f&quot;{lat},{long}&quot;,<br>        &quot;filter.radiusInMiles&quot;: 5,<br>        &quot;filter.chain&quot;: &quot;Kroger&quot;,<br>        &quot;filter.limit&quot;: 1<br>    }<br>    headers = {<br>        &quot;Accept&quot;: &quot;application/json&quot;,<br>        &quot;Authorization&quot;: f&quot;Bearer {access_key}&quot;<br>    }<br><br>    try:<br>        response = requests.get(url, params=params, headers=headers)<br>        response.raise_for_status()  # Raises an error for non-200 status codes<br>        data = response.json()<br>        <br>        # Check if data is in the expected format<br>        if &#39;data&#39; in data and len(data[&#39;data&#39;]) &gt; 0:<br>            return {<br>                &#39;name&#39;: data[&#39;data&#39;][0].get(&#39;name&#39;),<br>                &#39;address&#39;: data[&#39;data&#39;][0].get(&#39;address&#39;),<br>                &#39;location_id&#39;: data[&#39;data&#39;][0].get(&#39;locationId&#39;)<br>            }<br>        else:<br>            print(&quot;No valid location ID found in the response.&quot;)<br>            return None<br><br>    except requests.RequestException as e:<br>        print(f&quot;Request failed: {e}&quot;)<br>        return None</pre><h3>2. Product Search and Information Retrieval</h3><p>Once it identifies your store, it can search for specific products at that location:</p><pre>def get_value(data, keys, default=None):<br>    &quot;&quot;&quot;Retrieve nested keys/indices from a dictionary or list safely.&quot;&quot;&quot;<br>    for key in keys:<br>        try:<br>            if isinstance(data, dict):<br>                data = data.get(key, default)<br>            elif isinstance(data, list) and isinstance(key, int):<br>                data = data[key] if 0 &lt;= key &lt; len(data) else default<br>            else:<br>                return default<br>        except (TypeError, IndexError):<br>            return default<br>    return data<br><br>def get_products(search_term, location_id, access_key=KROGER_ACCESS_KEY):<br>    &quot;&quot;&quot;<br>    Fetches product details for a given search term at a specific Kroger location.<br>    <br>    Args:<br>        search_term (str): The product name to search for.<br>        location_id (str): The Kroger location ID.<br>        access_key (str): The API access token.<br>    <br>    Returns:<br>        list: A list of product details found for the search term.<br>    &quot;&quot;&quot;<br>    url = &quot;https://api-ce.kroger.com/v1/products/&quot;<br>    params = {<br>        &quot;filter.locationId&quot;: location_id,<br>        &quot;filter.term&quot;: search_term<br>    }<br>    headers = {<br>        &quot;Accept&quot;: &quot;application/json&quot;,<br>        &quot;Authorization&quot;: f&quot;Bearer {access_key}&quot;<br>    }<br>    <br>    try:<br>        response = requests.get(url, params=params, headers=headers)<br>        response.raise_for_status()<br>        search = response.json()<br>        <br>        products = []<br>        <br>        for idx, product in enumerate(search.get(&#39;data&#39;, [])):<br>            product_key = f&quot;{search_term}-{idx}&quot;<br>            products.append({<br>                product_key: {<br>                    &#39;regular_price&#39;: get_value(product, [&#39;items&#39;, 0, &#39;price&#39;, &#39;regular&#39;]),<br>                    &#39;promo_price&#39;: get_value(product, [&#39;items&#39;, 0, &#39;price&#39;, &#39;promo&#39;]),<br>                    &#39;description&#39;: get_value(product, [&#39;description&#39;]),<br>                    &#39;aisle&#39;: get_value(product, [&#39;aisleLocations&#39;]),<br>                    &#39;stock_level&#39;: get_value(product, [&#39;items&#39;, 0, &#39;inventory&#39;, &#39;stockLevel&#39;]),<br>                }<br>            })<br>            <br>        return products<br><br>    except requests.RequestException as e:<br>        print(f&quot;Request failed: {e}&quot;)<br>        return None</pre><p>The system extracts crucial details for each product:</p><ul><li>Regular and promotional prices</li><li>Full product description</li><li>Aisle location information</li><li>Current stock availability</li></ul><h3>3. Defining Function Tools for the Language Model</h3><p>In this step, we are defining the function tool to be understood by the LLM.</p><pre># Tool definitions for the LLM<br>tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;get_products&quot;,<br>            &quot;description&quot;: &quot;Search for products at a specific Kroger store&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;search_term&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;Product name or description to search for&quot;<br>                    },<br>                    &quot;location_id&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;Kroger store location ID obtained from get_location_id function&quot;<br>                    },<br>                    &quot;access_key&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;Kroger API access token&quot;<br>                    }<br>                },<br>                &quot;required&quot;: [&quot;search_term&quot;]<br>            }<br>        }<br>    }<br>]</pre><h3>4. The LLM Assistant: Tying It All Together</h3><p>The heart of the system is an LLM agent that can understand natural language queries and determine which tools to use. Here we are using One Shot prompting that means providing an example within the system prompt to help LLM understand how it should respond for similar questions based on the tool output.</p><pre>system_message = &quot;&quot;&quot;<br>You are a helpful shopping assistant for Kroger stores. You can help users find products at their nearest Kroger location by:<br>1. Searching for products at that store<br>2. Providing details about product prices, aisle locations, and availability within that particluar store. mention the store address as well in your response.<br><br>When a user asks about shopping or finding products, use the available tools to assist them:<br>- Search for the products they&#39;re interested in using the get_products tool<br><br>Always provide clear, concise information about where to find products in the store, including aisle numbers, product availability, <br>regular price, and a promo price specially for kroger members in the below format. Include the location address in the top of your response.<br><br>Like when the user asks &quot;Please find the details about Fage Yogurt&quot;. Respond in the format:<br><br>Fage Yogurt - Available in Stock - Reg Price $6.99 - Promo Price $5.99 - Located in Aisle 13, Dairy Section, Bay and Shelt Details<br><br>If the user asks for multiple products, search for each one separately and organize the results clearly.<br><br>If you encounter any errors or can&#39;t find certain products, explain the issue and suggest alternatives or next steps.<br>&quot;&quot;&quot;</pre><pre>def handle_tool_call(message, idx):<br>    &quot;&quot;&quot;<br>    Handle a tool call from the LLM.<br>    <br>    Args:<br>        message: The assistant message containing tool calls<br>        idx: Index of the tool call<br>    <br>    Returns:<br>        dict: The tool response in the expected format<br>    &quot;&quot;&quot;<br>    tool_call = message.tool_calls[idx]<br>    function_name = tool_call.function.name<br>    arguments = json.loads(tool_call.function.arguments)<br>    <br>    if function_name == &quot;get_products&quot;:<br>        # Extract arguments<br>        latitude, longitude = get_user_lat_lon()<br>        access_key = arguments.get(&#39;access_key&#39;, KROGER_ACCESS_KEY)<br>        location_data = get_location_id(lat, long, access_key)<br>        search_term = arguments.get(&#39;search_term&#39;)<br>        location_id = arguments.get(&#39;location_id&#39;, location_data[&#39;location_id&#39;]) <br>        <br>        # Call the function with extracted arguments<br>        products = get_products(search_term, location_id, access_key)<br>        <br>        return {<br>            &quot;role&quot;: &quot;tool&quot;,<br>            &quot;content&quot;: json.dumps({&quot;products&quot;: products, &quot;search_term&quot;: search_term, &quot;location_details&quot;: location_data}),<br>            &quot;tool_call_id&quot;: tool_call.id<br>        }</pre><pre>def chat(message, history):<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_message}] + history + [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]<br>    response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)<br>    <br>    if response.choices[0].finish_reason == &quot;tool_calls&quot;:<br>        assistant_message = response.choices[0].message<br>        messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: assistant_message.content, &quot;tool_calls&quot;: assistant_message.tool_calls})<br>        <br>        # Process each tool call<br>        for idx, tool_call in enumerate(assistant_message.tool_calls):<br>            # Use the handle_tool_call function<br>            tool_response = handle_tool_call(assistant_message, idx)<br>            messages.append(tool_response)<br>        <br>        # Get final response after tool calls<br>        response = openai.chat.completions.create(model=MODEL, messages=messages)<br>    <br>    return response.choices[0].message.content</pre><h3>5. User Interface with Gradio</h3><p>Finally, I created a simple chat interface using Gradio that allows users to interact with the assistant:</p><pre>&quot;&quot;&quot;Create and launch the Gradio interface for the grocery shopping assistant.&quot;&quot;&quot;<br><br>gr.ChatInterface(fn=chat, type=&quot;messages&quot;).launch()</pre><h3>6. Results</h3><p>Below is the screenshot taken with the above assistant, and check the results to see how it clearly responds to each product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*al-PfwOC0o6YaELRiQRYRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v043UHfaTauwKkFlmVjbUw.png" /></figure><h3>Real-World Benefits and Applications</h3><p>This shopping assistant provides several key benefits:</p><h3>For Regular Shoppers:</h3><ul><li><strong>Time Savings</strong>: Cut your shopping time by up to 60% by knowing exactly where to go</li><li><strong>Budget Control</strong>: Reduce impulse purchases by following a targeted shopping path</li><li><strong>Comparison Shopping</strong>: Easily check prices across different brands without walking around</li></ul><h3>For Instacart and Delivery Shoppers:</h3><ul><li><strong>Increased Efficiency</strong>: Complete more orders per hour by minimizing search time</li><li><strong>Higher Earnings</strong>: Turn efficiency into higher hourly wages</li><li><strong>Reduced Stress</strong>: Eliminate the frustration of hunting for obscure items</li><li><strong>Better Customer Service</strong>: Provide faster delivery times and more accurate order fulfillment</li></ul><h3>Beyond Kroger: Expanding to Other Retailers</h3><p>Although this implementation specifically targets Kroger stores, the architecture can be adapted to work with any retailer that offers similar API access to their inventory and store data. Potential expansions could include: Walmart Grocery, Target, Whole Foods etc.,</p><p>The key requirements are:</p><ol><li>An API that provides product search capabilities</li><li>Store location data</li><li>In-store location information for products</li></ol><h3>Before Running the Code Yourself</h3><p>To use this shopping assistant, you’ll need to:</p><ol><li>Install the required dependencies using pip install</li><li>You’ll need to register for API access through the <a href="https://developer.kroger.com/">Kroger Developer Portal</a> to obtain your access key. A test API was utilized for this purpose, but it can be readily extended to the production API for real-world production scenarios.</li><li>Create a .env file with your API keys:</li></ol><pre>OPENAI_API_KEY=your_openai_key<br>KROGER_ACCESS_KEY=your_kroger_api_key</pre><h3>Future Enhancements</h3><p>This is just the beginning. Future versions could include:</p><ol><li><strong>Shopping List Management</strong>: Save and reuse common shopping lists</li><li><strong>Optimal Path Generation</strong>: Calculate the most efficient route through the store</li><li><strong>Price Alerts</strong>: Notify when favorite items go on sale</li><li><strong>Substitution Suggestions</strong>: Recommend alternatives when items are out of stock</li><li><strong>Image Recognition</strong>: Scan photos of products to search for them</li><li><strong>Voice Interface</strong>: Hands-free operation while shopping</li></ol><h3>Conclusion: The Future of Smart Shopping</h3><p>The grocery store GPS represents a small but significant step toward using AI to make everyday tasks more efficient. By combining the natural language capabilities of LLMs with specific retail data, we can create tools that save time, reduce stress, and potentially even help us make healthier and more budget-conscious shopping decisions.</p><p>The code provided here is a starting point that demonstrates the concept. With further development and integration with more retail APIs, this approach could transform how we shop for groceries and other products.</p><p>If you found this article helpful, please follow me for more practical AI applications and don’t forget to clap (up to 50 times!) to help others discover this solution. Have you built similar tools or have ideas for improvements? Share your thoughts in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba132ec017c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Saved Millions by Restructuring Iceberg Metadata]]></title>
            <link>https://medium.com/@gauthamnagendra/how-i-saved-millions-by-restructuring-iceberg-metadata-c4f5c1de69c2?source=rss-c750cf5dd6f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f5c1de69c2</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <dc:creator><![CDATA[Gautham Gondi]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 21:11:34 GMT</pubDate>
            <atom:updated>2025-03-19T21:11:34.661Z</atom:updated>
            <content:encoded><![CDATA[<p>When faced with a massive 90-petabyte data lake that was getting slower by the day while costing more and more to operate, I discovered that sometimes the most impactful optimizations aren’t about processing data itself but about how we access it. This is the story of how a deep dive into Apache Iceberg’s metadata architecture led to a solution that saved my team within Advertising millions of dollars in compute costs.</p><figure><img alt="A digital illustration showing data optimization in a modern tech style. A large iceberg floating in dark blue water with visible layers beneath the surface. The underwater portion contains glowing blue file structures and organized data patterns, with some paths highlighted in bright yellow light representing optimized query paths." src="https://cdn-images-1.medium.com/max/1024/1*Xo3ZBitQmz_HxhDj9WxzZg.jpeg" /></figure><h3>The Challenge: Scale, Performance, and Cost</h3><p>As a lead data engineer on a major advertising platform, I was tasked with solving a critical problem. Our data lake had grown to an astounding 90 petabytes, supporting countless advertisers who ran SQL queries (converted to Spark jobs) to analyze their ad performance. These queries were:</p><ul><li>Getting progressively slower as data volumes increased</li><li>Entirely free for advertisers to run (with our company bearing all compute costs)</li><li>Struggling to maintain performance despite existing optimization efforts</li></ul><p>Our performance team had already implemented standard solutions: data compaction, materialization, separating hot and cold data layers, and optimizing partitioning strategies. The data was partitioned by (batch date, batch priority, batch region, and event day) with advertiser IDs distributed across buckets to prevent partition explosion.</p><h3>The Hidden Bottleneck in Iceberg</h3><p>Apache Iceberg was our table format of choice — renowned for its metadata management through manifests that allow queries to touch only the relevant files. We’d even implemented Iceberg’s column sorting and metrics features, but the performance gains were underwhelming.</p><p>When I dove deeper into Iceberg’s architecture, I discovered something critical about how the metadata was structured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oPEcI3GI1ZHIaQb0.png" /></figure><p><strong>Ref:</strong> <a href="https://iceberg.apache.org/spec/#overview">https://iceberg.apache.org/spec/#overview</a></p><ol><li>A high-level JSON metadata file tracking snapshots</li><li>Manifest lists (in Avro format) for each snapshot/batch by grouped metrics across all the partition columns.</li><li>Multiple manifest files(in Avro format) within each list</li><li>Data file references within each manifest file, containing partition data and column metrics</li></ol><p>Here was the insight: <strong>Our queries always filtered on advertiser_id and event_timestamp, but the metadata structure was organized by batch.</strong> This meant that to find data for a specific advertiser, the system had to scan the entire metadata layer — an enormous 300–500 GB of metadata for each table!</p><h3>The Breakthrough: Advertiser-Centric Manifests</h3><p>I realized we could dramatically improve query performance by restructuring the metadata layer without touching the actual data. The solution was elegantly simple:</p><p><strong>Re-organize manifest files by advertiser_bucket and event_timestamp instead of by batch.</strong></p><p>This approach would group all data files for a specific advertiser into dedicated manifest files, allowing the query engine to:</p><ol><li>Immediately identify which manifest files contained an advertiser’s data</li><li>Skip scanning the entire 500 GB metadata structure</li><li>Access only the relevant data files directly</li></ol><h3>Implementation Without Disruption</h3><p>The beauty of this solution was that it didn’t require reprocessing the entire 90 PB dataset — only the 5 TB metadata layer needed restructuring. I developed a process to:</p><ol><li>Load existing manifest files</li><li>Group data file references by advertiser bucket</li><li>Rewrite manifest files and manifest lists to create an advertiser-centric organization</li><li>Store this as a secondary metadata layer optimized for read queries</li></ol><p>This transformation changed our algorithm’s complexity from O(n) to O(1) for locating advertisers’ data files.</p><h3>Results: $3 Million a year in Savings</h3><p>By focusing on the “Read Many” part of the “Write Once, Read Many” paradigm, we maintained fast write performance while dramatically improving read speeds. Writes continued to use batch-based partitioning, while reads leveraged the new advertiser-centric metadata structure.</p><p>The business impact was tremendous:</p><ul><li>Queries that once took hours now being completed in minutes with an increase of performance by 74%</li><li>Compute resource utilization dropped dramatically</li><li>Annual savings of approximately $3 million</li><li>Improved advertiser experience with faster insights</li><li>All achieved without reprocessing 90 PB of data</li></ul><h3>Key Takeaways</h3><p>This experience taught me several valuable lessons about data engineering at extreme scale:</p><ol><li><strong>Look beyond the data itself</strong>: Sometimes the biggest wins come from optimizing how we access data, not changing the data itself.</li><li><strong>Understand your access patterns</strong>: The mismatch between our storage organization (by batch) and our access pattern (by advertiser and time) was the core issue.</li><li><strong>Leverage metadata intelligently</strong>: Modern table formats like Iceberg provide powerful metadata capabilities that can be further optimized for specific use cases.</li><li><strong>Think asymmetrically</strong>: Optimizing differently for reads vs. writes can provide the best of both worlds.</li><li><strong>Measure impact in business terms</strong>: A technical improvement is good, but a $3 million cost saving makes executives take notice.</li></ol><p>The next time you face a seemingly intractable data performance problem, remember to examine not just how your data is stored, but how your metadata is organized and accessed. The answers might be hiding in those often-overlooked manifest files.</p><p><strong>Did you find this article helpful?</strong></p><p>If so, please <strong>clap</strong> and <strong>follow</strong> me for more content on data engineering optimizations, big data architecture and how to leverage AI in your every day life. I’d love to hear about your experiences for similar challenges you’ve faced — share your thoughts in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f5c1de69c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Event Finder with Python, OpenAI, and Ticketmaster API]]></title>
            <link>https://medium.com/@gauthamnagendra/building-a-real-time-event-finder-with-python-openai-and-ticketmaster-api-a4cccb825f7b?source=rss-c750cf5dd6f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4cccb825f7b</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Gautham Gondi]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 17:39:52 GMT</pubDate>
            <atom:updated>2025-03-18T15:06:54.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V74qzzR64mGDuS-4lC0J0A.jpeg" /></figure><p>Have you ever wished for an AI assistant that could tell you about upcoming concerts, sports games, and other events in your area? In this tutorial, I’ll show you how I built exactly that: a simple yet powerful chatbot that can detect your location and provide real-time information about nearby events.</p><h3>What We’re Building</h3><p>This application combines several powerful technologies:</p><ol><li><strong>Location Detection</strong>: Automatically identifies the user’s city and state</li><li><strong>Event Search</strong>: Queries the Ticketmaster API for upcoming events</li><li><strong>AI Assistant</strong>: Uses OpenAI’s GPT models to provide natural language responses</li><li><strong>Web Interface</strong>: Presents a simple chat interface using Gradio</li></ol><p>The result is a conversational AI that can answer queries like “What concerts are happening near me this weekend?” or “Are there any sports events in Boston next month?”</p><h3>The Tech Stack</h3><p>Here’s what we’ll be using:</p><ul><li><strong>Python</strong>: Our primary programming language</li><li><strong>geocoder</strong>: For IP-based location detection</li><li><strong>python-dotenv</strong>: For managing environment variables</li><li><strong>Ticketmaster API</strong>: To fetch event data</li><li><strong>OpenAI API</strong>: For natural language processing</li><li><strong>Gradio</strong>: To create a web interface</li></ul><h3>Step 1: Setting Up the Environment</h3><p>First, let’s install the necessary libraries:</p><pre>pip install geocoder requests python-dotenv openai gradio</pre><p>Create a .env file in your project directory to store your OpenAI API key:</p><pre>OPENAI_API_KEY=your_open_ai_api_key_here<br>TICKET_MASTER_API_KEY=your_ticket_master_api</pre><h3>Step 2: Location Detection</h3><p>We’ll use the geocoder library to determine the user’s location based on their IP address:</p><pre>def get_user_location():<br>    g = geocoder.ip(&#39;me&#39;)<br>    return g.city, states.get(g.state, &#39;&#39;)</pre><p>The states dictionary provides a mapping between state names and their two-letter codes, which we&#39;ll need for the Ticketmaster API.</p><h3>Step 3: Event Search with Ticketmaster API</h3><p>The Ticketmaster API allows us to search for events based on location, date range, and event type:</p><p><strong>Note:</strong> get_dates() used in this function is just to get default dates. I have used two week window to identify events within that window.</p><pre>def get_dates():<br>    tomorrow = datetime.now().date() + timedelta(days=1)<br>    week_after_tomorrow = tomorrow + timedelta(days=14)<br>    return tomorrow, week_after_tomorrow</pre><pre>def get_nearby_events(city=None, state=None, radius=50, segments=&quot;[Music, Sports]&quot;, start_date=None, end_date=None):<br>    if not city or not state:<br>        city, state = get_user_location()<br><br>    if not start_date or not end_date:<br>            start_date, end_date = get_dates()<br>            <br>    url = (<br>        f&quot;https://app.ticketmaster.com/discovery/v2/events.json?&quot;<br>        f&quot;city={city}&amp;&quot;<br>        f&quot;stateCode={state}&amp;&quot;<br>        f&quot;radius={radius}&amp;&quot;<br>        f&quot;segmentName={segments}&amp;&quot;<br>        f&quot;startDateTime={str(start_date)}T00:00:00Z&amp;&quot;<br>        f&quot;endDateTime={str(end_date)}T00:00:00Z&amp;&quot;<br>        f&quot;apikey={TICKET_MASTER_API_KEY}&quot;<br>    )<br>    response_data = requests.get(url).json()<br>    events = []<br>    if response_data.get(&#39;_embedded&#39;) and response_data[&#39;_embedded&#39;].get(&#39;events&#39;):<br>        for event in response_data[&#39;_embedded&#39;][&#39;events&#39;]:<br>            event_info = {<br>                &quot;Event Name&quot;: event[&#39;name&#39;],<br>                &quot;Event Link&quot;: event[&#39;url&#39;]<br>            }<br>            # Add price ranges if available<br>            if &#39;priceRanges&#39; in event and event[&#39;priceRanges&#39;]:<br>                event_info[&quot;Price Ranges&quot;] = f&quot;${event[&#39;priceRanges&#39;][0][&#39;min&#39;]} - ${event[&#39;priceRanges&#39;][0][&#39;max&#39;]}&quot;<br>            events.append(event_info)<br>    return events</pre><h3>Step 4: The AI Brain — OpenAI Function Calling</h3><p>This is where the magic happens. OpenAI’s function calling capability allows our chatbot to understand when to call external functions based on the user’s intent:</p><pre>location_function = {<br>    &quot;name&quot;: &quot;get_user_location&quot;,<br>    &quot;description&quot;: &quot;Gets the user location by returning the user&#39;s city name and user&#39;s state name&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>        },<br>        &quot;required&quot;: [],<br>        &quot;additionalProperties&quot;: False<br>    }<br>}</pre><pre>events_function = {<br>    &quot;name&quot;: &quot;get_nearby_events&quot;,<br>    &quot;description&quot;: &quot;Get the events near to user location or a specific city and state happening within a given radius and date range.&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;city&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The city to search events in.&quot;},<br>            &quot;state&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The state to search events in.&quot;},<br>            &quot;radius&quot;: {&quot;type&quot;: &quot;integer&quot;, &quot;description&quot;: &quot;The radius around the location for events.&quot;},<br>            &quot;segments&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The type of events to filter like Music, Sports.&quot;},<br>            &quot;start_date&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The start date of events (e.g., 2025-03-16).&quot;},<br>            &quot;end_date&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The end date of events (e.g., 2025-03-31).&quot;}<br>        },<br>        &quot;required&quot;: [],<br>        &quot;additionalProperties&quot;: False<br>    }<br>}</pre><pre>tools = [{&quot;type&quot;: &quot;function&quot;, &quot;function&quot;: events_function}, {&quot;type&quot;: &quot;function&quot;, &quot;function&quot;: location_function}]</pre><p>These function definitions act as a bridge between natural language and code execution. When the user asks about events, the AI model:</p><ol><li>Recognizes the intent (looking for events)</li><li>Extracts relevant parameters (location, date range, event type)</li><li>Decides which function to call</li><li>Formats the parameters and makes the call</li><li>Processes the results into a natural language response</li></ol><p>The system message guides the AI’s behavior:</p><pre>system_message = &quot;You are a helpful assistant with also the ability to look for events happening in real time. &quot;<br>system_message += &quot;If the user asks any questions related to the events happening in real time, use the embedded tools to answer. &quot;<br>system_message += &quot;Always be accurate. If you don&#39;t know the answer, say so.&quot;</pre><h3>Step 5: Bringing It All Together — The Chat Interface</h3><p>The chat function ties everything together:</p><pre>def chat(message, history):<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_message}] + history + [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]<br>    response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)<br>    <br>    if response.choices[0].finish_reason == &quot;tool_calls&quot;:<br>        assistant_message = response.choices[0].message<br>        messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: assistant_message.content, &quot;tool_calls&quot;: assistant_message.tool_calls})<br>        <br>        # Handle each tool call<br>        for tool_call in assistant_message.tool_calls:<br>            function_name = tool_call.function.name<br>            <br>            if function_name == &quot;get_nearby_events&quot;:<br>                arguments = json.loads(tool_call.function.arguments)<br>                city = arguments.get(&#39;city&#39;)<br>                state = arguments.get(&#39;state&#39;)<br>                radius = arguments.get(&#39;radius&#39;, 50)<br>                segments = arguments.get(&#39;segments&#39;, &quot;[Music, Sports]&quot;)<br>                start_date = arguments.get(&#39;start_date&#39;)<br>                end_date = arguments.get(&#39;end_date&#39;)<br>                events = get_nearby_events(city, state, radius, segments, start_date, end_date)<br>                tool_response = {<br>                    &quot;role&quot;: &quot;tool&quot;,<br>                    &quot;content&quot;: json.dumps({&#39;events&#39;: events}),<br>                    &quot;tool_call_id&quot;: tool_call.id<br>                }<br>            elif function_name == &quot;get_user_location&quot;:<br>                city, state = get_user_location()<br>                tool_response = {<br>                    &quot;role&quot;: &quot;tool&quot;,<br>                    &quot;content&quot;: json.dumps({&#39;city&#39;: city, &#39;state&#39;: state}),<br>                    &quot;tool_call_id&quot;: tool_call.id<br>                }<br>                <br>            messages.append(tool_response)<br>            <br>        # Get final response after tool calls<br>        response = openai.chat.completions.create(model=MODEL, messages=messages)<br>    return response.choices[0].message.content</pre><h3>Before and After: The Power of AI Tool Integration</h3><h4>Before: AI Without Real-Time Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oD56u2JVXJ8WZlga9qeMxA.png" /></figure><p>Without access to real-time data, AI models can only provide generic responses based on their training data. When asked about local events, they might say something like:</p><p>“I’m sorry, but I don’t have access to real-time event information or your location.”</p><p>This limitation makes the AI less helpful for time-sensitive, location-specific queries.</p><h4>After: AI With Function Calling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEqw-1OdUbcXDUbII-bWeg.png" /></figure><p>With our function calling implementation, the AI can now:</p><ol><li>Recognize that the user is asking about events</li><li>Determine the user’s location (or use a specified location)</li><li>Call the Ticketmaster API with the appropriate parameters</li><li>Process the results</li><li>Respond with specific, actionable information</li></ol><p>The result is a much more capable assistant that can provide value beyond what’s in its training data.</p><h3>The AI Decision Process</h3><p>Let’s explore how the AI makes decisions in our application:</p><ol><li><strong>Understanding Intent</strong>: The model first determines if the user is asking about events. It does this by analyzing the semantic meaning of the query.</li><li><strong>Parameter Extraction</strong>: If the query is about events, the model extracts parameters like: <br>- Location (city, state)<br>- Time frame (this weekend, next month)<br>- Event type (music, sports)</li><li><strong>Function Selection</strong>: Based on the extracted parameters, the model decides which function to call. If it needs location information, it calls get_user_location(). If it needs event information, it calls get_nearby_events().</li><li><strong>Parameter Formatting</strong>: The model formats the parameters according to the function’s requirements. For example, it might convert “this weekend” to specific start and end dates.</li><li><strong>Result Processing</strong>: After receiving the function results, the model generates a natural language response that answers the user’s question directly.</li></ol><p>This process happens seamlessly, giving the user the impression of talking to a knowledgeable assistant rather than a collection of APIs.</p><h3>Key Takeaways</h3><p>Building this system taught me several valuable lessons:</p><ol><li><strong>AI Function Calling</strong>: OpenAI’s function calling capability is the bridge between natural language and code execution. It allows the AI to act as an intelligent router, deciding when and how to call external functions.</li><li><strong>Parameter Handling</strong>: The AI is remarkably good at extracting parameters from natural language, but it needs clear function definitions to know what to look for.</li><li><strong>Conversation Flow</strong>: Maintaining context across multiple messages requires careful management of the conversation history.</li><li><strong>Response Generation</strong>: The AI needs to balance providing enough information with keeping responses concise and natural.</li></ol><h3>Future Improvements</h3><p>Here are some ways this application could be enhanced:</p><ol><li><strong>Memory and Preferences</strong>: Implement user profiles to remember preferences and past interactions.</li><li><strong>Multi-turn Conversations</strong>: Enhance the dialogue capabilities to allow follow-up questions like “Which of those events is cheapest?”</li><li><strong>Proactive Suggestions</strong>: Have the AI suggest events based on user preferences and past interactions.</li><li><strong>Multimodal Responses</strong>: Integrate images of venues or performers to enhance the conversation.</li><li><strong>Calendar Integration</strong>: Allow users to add events directly to their calendar.</li></ol><h3>Conclusion</h3><p>By combining OpenAI’s language models with external APIs, we’ve created a chatbot that can access real-time data and provide specific, actionable information. This approach demonstrates how AI can be more than just a knowledge base — it can be a gateway to dynamic, real-time information.</p><p>The true power of modern AI assistants comes not just from what they know, but from what they can do. By giving our AI the ability to call functions, we’ve expanded its capabilities far beyond what’s possible with a static model.</p><p>Feel free to use this codebase and add your own features or improvements. Happy coding!</p><p><em>Note: Remember to handle your API keys securely and never expose them in your code or version control.</em></p><p>If you gained some value from this, don’t forget to clap as many times as Medium allows you to clap as many as up to 50 times.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4cccb825f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>