<?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[VannGuard AI - Medium]]></title>
        <description><![CDATA[At VannGuard AI, we build custom AI solutions to help businesses worldwide solve their unique challenges. - Medium]]></description>
        <link>https://medium.com/vannguardai?source=rss----82aa7e5ff444---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>VannGuard AI - Medium</title>
            <link>https://medium.com/vannguardai?source=rss----82aa7e5ff444---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:20:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/vannguardai" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Beyond the Chatbot: Building Generative UI with Vercel AI SDK]]></title>
            <link>https://medium.com/vannguardai/beyond-the-chatbot-building-generative-ui-with-vercel-ai-sdk-f8b73cec6e2b?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/f8b73cec6e2b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Dur-e-Shahwar]]></dc:creator>
            <pubDate>Tue, 19 May 2026 12:47:04 GMT</pubDate>
            <atom:updated>2026-05-19T13:31:19.307Z</atom:updated>
            <content:encoded><![CDATA[<h4>Moving from static data visualization to intent-driven sales intelligence.</h4><figure><img alt="Generative UI dashboard showing KPI metric cards with AI insights and Optimize Strategy buttons built with Vercel AI SDK and Next.js" src="https://cdn-images-1.medium.com/max/1011/1*Li4ZQNaL6EtQYxnOUlIIsQ.png" /><figcaption>Intent-based rendering: Vantage AI fetching specific KPI metrics based on a high-level query</figcaption></figure><p>Most AI integrations stop at text. A user asks a question, the model replies with a paragraph, and the interface stays static. That works for a chatbot. It does not work for a business dashboard, where reading “$54,219, up 12% from last month” is a poor substitute for actually seeing a KPI card with that number in it.</p><p>This article is about a different approach. We built VantageAI, an intent-driven sales dashboard where users type natural language questions and the application renders live React components in response, KPI cards, bar charts, and risk tables, with no navigation, no filters, and no pre-built report to find.</p><h3>The Problem: The Fixed-Payload Constraint</h3><p>Traditional BI dashboards are built on a fundamental limitation: designers must anticipate every possible query and build a static view for it. We call this the Fixed-Payload Constraint. A Sales Director asking “Why is churn spiking in our Enterprise tier after the billing update?” has to cross-reference three reports, apply manual filters, and synthesize the result themselves. If the view was not pre-designed, the system fails.</p><p>We addressed this at the architectural level by replacing the navigation layer with a natural language interface that renders the right component on demand.</p><h3>The core concept: The Router Pattern</h3><p>The key decision in VantageAI is that the LLM acts as a router, not a data source. The model does not generate UI code. It reads tool descriptions, identifies intent, and routes the request to a pre-built React component. The data comes from your backend. The AI only decides which component to render, which means it cannot hallucinate a revenue figure. It can only call showMetrics, which fetches from your actual data layer.</p><h3>Tech stack</h3><p>Performance is the primary constraint for Generative UI. If the interface takes multiple seconds to respond, the experience feels disjointed, regardless of how good the output is. Our stack was chosen to minimize time-to-UI:</p><ol><li><strong>Groq (Llama 3.3 70B):</strong> We utilized Groq’s LPU architecture to achieve the sub-second inference speeds required for multi-step tool calling.</li><li><strong>Vercel AI SDK v6:</strong> This acts as the orchestration layer, managing the stream of “UI parts” and the transition states between user input and component display.</li><li><strong>Next.js 15:</strong> The framework provides the server-side environment needed to execute tools and fetch data.</li><li><strong>Zod: </strong>All tool parameters are strictly typed with Zod, ensuring the AI cannot pass malformed data to our frontend components.</li></ol><h3>Architecture: The Request Lifecycle</h3><p>Before writing any code, here is the full request lifecycle. Every step maps directly to a file in the project.</p><figure><img alt="Architecture diagram showing Generative UI request flow from user input through Next.js API route, Groq Llama 3.3, tool selection, lib/db.ts, streaming, and React component rendering" src="https://cdn-images-1.medium.com/max/1024/1*3oXAVeqUxUPGIJ2GHLgPAA.png" /><figcaption>The 7-step request lifecycle: from natural language input to a rendered React component, with no UI code generated by the LLM</figcaption></figure><h4>Step 1: The Data Layer</h4><p>The data layer is the part most tutorials skip. Create lib/db.ts as the single source of truth for all dashboard data. The query functions at the bottom are the only interface that the rest of the system uses. In production, you replace those functions with real database calls, and nothing else changes.</p><p>Notice the insight field on each metric. This is intentional: contextual intelligence is embedded at the data layer, not generated by the LLM. When churn spikes, the insight explains why, and it comes from a field your team writes and maintains.</p><pre>// lib/db.ts<br>// Replace query functions with real DB calls (Supabase, Prisma, etc.) in production<br><br>export const db = {<br>  metrics: {<br>    monthly_revenue: { title: &quot;Monthly Revenue&quot;, value: &quot;$54,219&quot;, change: &quot;12%&quot;, positive: true, insight: &quot;Revenue is up, but expansion from existing accounts slowed by 3%.&quot; },<br>    active_users: { title: &quot;Active Users&quot;, value: &quot;3,842&quot;, change: &quot;8%&quot;, positive: true, insight: &quot;Highest growth seen in the EMEA region.&quot; },<br>    churn_rate: { title: &quot;Churn Rate&quot;, value: &quot;2.4%&quot;, change: &quot;0.3%&quot;, positive: false, insight: &quot;Churn spiked in &#39;VantageAI Lite&#39; tier users after the last billing update.&quot; },<br>  },<br><br>  sales: [<br>    { month: &quot;January 2026&quot;, sales: 38000 }, { month: &quot;February 2026&quot;, sales: 45000 }, { month: &quot;March 2026&quot;, sales: 46500 }, { month: &quot;April 2026&quot;, sales: 51200 }, { month: &quot;May 2026&quot;, sales: 54219 }, <br>    { month: &quot;Q3 2025&quot;, sales: 41000 }, { month: &quot;Q4 2025&quot;, sales: 49500 },<br>  ],<br><br>  customers: [<br>    { name: &quot;Acme Inc.&quot;, industry: &quot;Tech&quot;, revenue: &quot;$120k&quot;, status: &quot;Active&quot;, risk: &quot;Low&quot; },<br>    { name: &quot;Global Corp&quot;, industry: &quot;Finance&quot;, revenue: &quot;$90k&quot;, status: &quot;At Risk&quot;, risk: &quot;High&quot; },<br>    { name: &quot;SaaS Labs&quot;, industry: &quot;Tech&quot;, revenue: &quot;$45k&quot;, status: &quot;Active&quot;, risk: &quot;Medium&quot; },<br>  ],<br><br>// products...<br>};<br><br>// Replace these with real DB queries in production<br>export function getMetrics(keys: string[]) {<br>  return keys.map(k =&gt; db.metrics[k as keyof typeof db.metrics]).filter(Boolean);<br>}<br>export function getSalesData(months = 6) { return db.sales.slice(0, months); }<br>export function getCustomers() { return db.customers; }</pre><h4>Step 2: The Actionable UI Components</h4><p>The components are stateless at the data level. They receive props and render. None of them knows that the AI layer exists.</p><p>The MetricCard is the most interesting one. When an insight field is present, it surfaces a contextual recommendation rather than just displaying a number. Clicking “Optimize Strategy” reveals pre-defined actions tailored to that specific KPI. The recommendations are computed locally based on the metric title, not generated by the LLM at query time. This keeps the interaction instant and deterministic.</p><pre>// components/MetricCard.tsx (key logic)<br>const getRecommendations = () =&gt; {<br>  if (title.includes(&quot;Revenue&quot;))<br>    return [&quot;Upsell Pro plan to top 10 accounts&quot;, &quot;Launch H2 referral program&quot;];<br>  if (title.includes(&quot;Churn&quot;))<br>    return [&quot;Automate discount for At Risk users&quot;, &quot;Conduct exit surveys&quot;];<br>  return [&quot;Benchmark against competitors&quot;, &quot;Identify growth levers&quot;];<br>};<br><br>const handleOptimize = () =&gt; {<br>  setIsOptimizing(true);<br>  setTimeout(() =&gt; { setIsOptimizing(false); setShowStrategy(true); }, 1500);<br>};</pre><p>Once the metrics render, cards surface an “Optimize Strategy” button. Clicking it reveals recommended actions specific to that KPI, computed locally, not generated by the LLM at runtime.</p><figure><img alt="VantageAI dashboard MetricCard components showing Strategy Active state with recommended actions for churn rate and active users" src="https://cdn-images-1.medium.com/max/1024/1*9CZUY-VHhVK8smqKXAn_rA.png" /><figcaption>The Actionable UI: Strategic recommendations revealed inside the component to bridge the gap between insight and execution.</figcaption></figure><h4>Step 3: The AI Route</h4><p>The API route is where intent maps to components. The two most important decisions are in the tool configuration, not the model selection.</p><pre>// app/api/chat/route.ts<br>export async function POST(req: Request) {<br>  const body = await req.json();<br>  const messages = Array.isArray(body.messages) ? body.messages : [];<br><br>  const result = streamText({<br>    model: groq(&quot;llama-3.3-70b-versatile&quot;),<br>    system: `You are a Sales Strategy Analyst for VantageAI. Always call exactly one tool.<br>    - Revenue, KPIs, business health -&gt; showMetrics<br>    - Charts, trends, sales over time -&gt; showSalesChart<br>    - Customers, accounts, risk -&gt; showCustomers<br>    - Products, plans -&gt; showProducts`,<br>    messages: toModelMessages(messages),<br>    toolChoice: &quot;required&quot;,   // forces a tool call every time, no plain text responses<br>    tools: {<br>      showMetrics: tool({<br>        description: &quot;Show KPI metric cards for revenue, users, and performance.&quot;,<br>        parameters: z.object({}),  // intentionally empty: all logic lives in execute()<br>        execute: async () =&gt; {<br>          const metrics = getMetrics([&quot;monthly_revenue&quot;, &quot;active_users&quot;, &quot;churn_rate&quot;]);<br>          return { component: &quot;metrics&quot;, metrics };<br>        },<br>      }),<br>      showCustomers: tool({<br>        description: &quot;Show customer list with risk analysis.&quot;,<br>        parameters: z.object({}),<br>        execute: async () =&gt; {<br>          const rows = getCustomers();<br>          return {<br>            component: &quot;table&quot;,<br>            title: &quot;Strategic Customer Overview&quot;,<br>            headers: [&quot;Name&quot;, &quot;Industry&quot;, &quot;Revenue&quot;, &quot;Risk Level&quot;, &quot;Recommended Action&quot;],<br>            rows: rows.map((r) =&gt; [<br>              r.name, r.industry, r.revenue, r.risk,<br>              r.risk === &quot;High&quot; ? &quot;Schedule QBR&quot; : &quot;No Action&quot;,<br>            ]),<br>          };<br>        },<br>      }),<br>      // showSalesChart and showProducts follow the same pattern<br>    },<br>    maxSteps: 5,<br>  });<br><br>  return result.toUIMessageStreamResponse();<br>}</pre><p>When a user asks about customer risk, the showCustomers tool fires. The execute function computes the “Recommended Action” column server-side based on the risk field, so the table arrives with business logic already applied.</p><figure><img alt="Strategic customer overview table showing risk levels and recommended actions generated by Generative UI tool calling in Vercel AI SDK" src="https://cdn-images-1.medium.com/max/1024/1*qTEDyhnqf91RE3l2A-mH4A.png" /><figcaption>The Strategic Table: AI highlights risk and suggests “Schedule QBR” actions directly into the data rows.</figcaption></figure><p>The same routing handles product performance without any changes to the layout or navigation.</p><figure><img alt="Product performance table showing VantageAI tiers by revenue, growth, users, and satisfaction score rendered dynamically by AI" src="https://cdn-images-1.medium.com/max/1024/1*IQwH_qShT-PY3iC4MymWHg.png" /><figcaption>Multi-dimensional data: A breakdown of product performance, growth, and satisfaction metrics.</figcaption></figure><h4>Step 4: The Frontend</h4><p>The frontend has two jobs: send messages and render tool results. In Vercel AI SDK v6, completed tool calls appear in message.parts with type: “tool-{toolName}” and state: “output-available”. The output field contains exactly what execute returned.</p><pre>// app/page.tsx (tool rendering logic)<br>const toolParts = message.parts?.filter(<br>  (p: any) =&gt; p.type?.startsWith(&quot;tool-&quot;) &amp;&amp; p.state === &quot;output-available&quot;<br>) ?? [];<br><br>return (<br>  &lt;div className=&quot;space-y-4&quot;&gt;<br>    {toolParts.map((part: any, i: number) =&gt; (<br>      &lt;div key={i}&gt;{renderToolResult(part.output)}&lt;/div&gt;<br>    ))}<br>  &lt;/div&gt;<br>);</pre><p>While the data is fetching, we render a LoadingSkeleton in the same grid layout as the actual components. This prevents layout shift when the real data arrives, which is especially noticeable on the metrics grid.</p><pre>function LoadingSkeleton() {<br>  return (<br>    &lt;div className=&quot;space-y-4 animate-pulse&quot;&gt;<br>      &lt;div className=&quot;grid grid-cols-2 gap-4&quot;&gt;<br>        {[...Array(4)].map((_, i) =&gt; (<br>          &lt;div key={i} className=&quot;bg-gray-800 rounded-2xl p-5 h-28 border border-gray-700&quot; /&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Sales trend queries render an interactive Recharts bar chart. The tooltip is built into the component; no additional configuration is needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCBqyL6d43GlS9grkRWYfg.png" /><figcaption>Dynamic Visualization: Real-time generation of complex, interactive charts using the Recharts library.</figcaption></figure><h3>Future Considerations</h3><p>When moving to a real database, the query functions in lib/db.ts are the only thing that changes. The AI route, the frontend, and the components stay exactly as written. Next steps would include:</p><ol><li>Connecting to a real database like Supabase or Prisma</li><li>Adding an auth layer around the POST handler so users only access data they are authorized to see</li><li>Wiring the “Schedule QBR” button to a CRM like Salesforce or HubSpot</li><li>Adding conversation memory so the AI retains context across follow-up questions in the same session</li></ol><h3>Conclusion</h3><p>The Router Pattern we have described here is a clean separation of concerns: the AI layer makes a routing decision, the data layer runs a query, and the UI layer renders a component. Each can be tested, updated, and replaced independently. The AI part is thin. The data part is standard backend engineering. The UI part is standard React. That separation is what makes this maintainable at scale, and worth building.</p><p>Full source code available on GitHub: <a href="https://github.com/dshahwarrr/generative-ui-dashboard">https://github.com/dshahwarrr/generative-ui-dashboard</a></p><h3>References</h3><ul><li><a href="https://sdk.vercel.ai/docs">Vercel AI SDK Documentation</a> — official SDK reference for streamText, useChat, and tool calling</li><li><a href="https://console.groq.com/docs">Groq API Documentation</a> — model reference and rate limits for Llama 3.3 70B</li><li><a href="https://nextjs.org/docs/app">Next.js 15 App Router Documentation</a> — API routes and server components reference</li><li><a href="https://recharts.org/en-US">Recharts Documentation</a> — component reference for BarChart and ResponsiveContainer</li><li><a href="https://zod.dev/">Zod Documentation</a> — schema validation reference used for tool parameters</li><li><a href="https://sdk.vercel.ai/docs/migration-guides">Vercel AI SDK v6 Migration Guide</a> — covers the UIMessage and ModelMessage format changes discussed in the article</li></ul><h4>About VannGuard AI</h4><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8b73cec6e2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/beyond-the-chatbot-building-generative-ui-with-vercel-ai-sdk-f8b73cec6e2b">Beyond the Chatbot: Building Generative UI with Vercel AI SDK</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MinIO: From Zero to Advanced]]></title>
            <link>https://medium.com/vannguardai/minio-from-zero-to-advanced-86ebbd584347?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/86ebbd584347</guid>
            <dc:creator><![CDATA[Sohaib Ahmed]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 12:09:07 GMT</pubDate>
            <atom:updated>2026-04-14T12:09:05.875Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Building Event-Driven AI Data Pipelines</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U040usmE3KODHS8kJKL_1Q.png" /></figure><p>When building AI applications, managing massive datasets, multi-gigabyte model weights, and raw multimodal files is half the battle.</p><p>Imagine you are building a computer vision model that processes thousands of high-res images daily. If you route all those gigabytes through your Python backend, your servers will crash. If you rely on AWS S3 but you’re operating in a local dev environment or an on-prem edge device, you need a different tool.</p><p>Enter <strong>MinIO</strong>: an ultra-fast, S3-compatible object storage server built for heavy workloads.</p><p>In this tutorial, we will take a lean, code-first approach to go from zero to advanced usage of MinIO using Python. We will cover standing up the server, basic CRUD, how to handle massive direct uploads, and how to trigger event-driven AI pipelines.</p><h3><strong>The Setup (Local Environment)</strong></h3><p>The fastest way to get MinIO running locally is via Docker. We will use a<strong> docker-compose.yml</strong> file to spin up a server with persistent storage.</p><p>We are also adding some environment variables that we’ll need for Step 3.</p><pre>services:<br>  minio:<br>    image: minio/minio:latest<br>    container_name: minio_server<br>    ports:<br>      - &quot;9000:9000&quot;<br>      - &quot;9001:9001&quot;<br>    environment:<br>      MINIO_ROOT_USER: &quot;admin&quot;<br>      MINIO_ROOT_PASSWORD: &quot;password123&quot;<br>      # Configuration for Webhook events (used in Level 3)<br>      MINIO_NOTIFY_WEBHOOK_ENABLE_primary: &quot;on&quot;<br>      MINIO_NOTIFY_WEBHOOK_ENDPOINT_primary: &quot;http://host.docker.internal:8080/ingest&quot;<br>    command: server /data --console-address &quot;:9001&quot;<br>    extra_hosts:<br>      - &quot;host.docker.internal:host-gateway&quot;<br>    volumes:<br>      - minio_data:/data<br><br>volumes:<br>  minio_data:</pre><p>Run it in your terminal:</p><pre>docker-compose up -d</pre><p>Your MinIO API is now available at <strong>http://localhost:9000</strong>, and the graphical Web UI is at <strong>http://localhost:9001</strong>.</p><h3><strong>1. The Basics</strong></h3><p>First, let’s learn how to connect and perform basic CRUD operations.</p><p><strong>Key takeaway:</strong> You don’t need a special MinIO SDK. Because it is completely S3-compatible, just use the standard AWS <strong>boto3</strong> library! And simply point <strong>boto3</strong> to your local endpoint instead of AWS.</p><p>Run the following <strong>01_basic_crud.py</strong> script. It will create a <strong>datasets</strong> bucket and upload a dummy CSV file.</p><pre>import boto3<br>from botocore.client import Config<br><br># Configuration<br>MINIO_ENDPOINT = &quot;http://localhost:9000&quot;<br>MINIO_ACCESS_KEY = &quot;admin&quot;<br>MINIO_SECRET_KEY = &quot;password123&quot;<br>BUCKET_NAME = &quot;datasets&quot;<br><br># Initialize the client exactly as you would for AWS S3<br>s3_client = boto3.client(<br>    &quot;s3&quot;,<br>    endpoint_url=MINIO_ENDPOINT,<br>    aws_access_key_id=MINIO_ACCESS_KEY,<br>    aws_secret_access_key=MINIO_SECRET_KEY,<br>    config=Config(signature_version=&quot;s3v4&quot;),<br>    region_name=&quot;us-east-1&quot;<br>)<br><br>def create_bucket_if_not_exists():<br>    try:<br>        s3_client.head_bucket(Bucket=BUCKET_NAME)<br>        print(f&quot;Bucket &#39;{BUCKET_NAME}&#39; already exists.&quot;)<br>    except Exception:<br>        print(f&quot;Creating bucket &#39;{BUCKET_NAME}&#39;...&quot;)<br>        s3_client.create_bucket(Bucket=BUCKET_NAME)<br>        print(&quot;Bucket created successfully.&quot;)<br><br>def upload_file(file_content: bytes, object_name: str):<br>    print(f&quot;Uploading &#39;{object_name}&#39;...&quot;)<br>    s3_client.put_object(<br>        Bucket=BUCKET_NAME,<br>        Key=object_name,<br>        Body=file_content<br>    )<br>    print(&quot;Upload complete.&quot;)<br><br>def list_files():<br>    print(f&quot;\nFiles in &#39;{BUCKET_NAME}&#39;:&quot;)<br>    response = s3_client.list_objects_v2(Bucket=BUCKET_NAME)<br>    if &quot;Contents&quot; in response:<br>        for obj in response[&quot;Contents&quot;]:<br>            print(f&quot; - {obj[&#39;Key&#39;]} ({obj[&#39;Size&#39;]} bytes)&quot;)<br>    else:<br>         print(&quot; (Empty bucket)&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    create_bucket_if_not_exists()<br>    <br>    # Create a dummy dataset<br>    sample_data = b&quot;id,name,value\n1,test,100\n2,demo,200&quot;<br>    upload_file(sample_data, &quot;raw/batch_001.csv&quot;)<br>    upload_file(sample_data, &quot;raw/batch_002.csv&quot;)<br>    <br>    list_files()</pre><p>Output:</p><pre>Creating bucket &#39;datasets&#39;...<br>Bucket created successfully.<br>Uploading &#39;raw/batch_001.csv&#39;...<br>Upload complete.<br>Uploading &#39;raw/batch_002.csv&#39;...<br>Upload complete.<br><br>Files in &#39;datasets&#39;:<br> - raw/batch_001.csv (35 bytes)<br> - raw/batch_002.csv (35 bytes)</pre><h3><strong>2. Advanced Workflows: Presigned URLs</strong></h3><p>In AI workflows, you frequently deal with large files (gigabytes of training data, images, etc.).</p><p>If you allow users to upload files to your Python backend application, and <em>then</em> your backend uploads them to MinIO, you will quickly run out of memory, max out your network bandwidth, and crash your APIs.</p><p><strong>The Solution: </strong>Presigned URLs.</p><p>Instead of streaming data through your backend, your backend generates a temporary, secure URL. The client (your front-end UI, or an ingestion device) uses that URL to upload the file <em>directly</em> to the bucket.</p><p>Run the following <strong>02_presigned_urls.py </strong>script.</p><pre>import requests<br>import boto3<br>from botocore.client import Config<br><br># Configuration<br>MINIO_ENDPOINT = &quot;http://localhost:9000&quot;<br>MINIO_ACCESS_KEY = &quot;admin&quot;<br>MINIO_SECRET_KEY = &quot;password123&quot;<br>BUCKET_NAME = &quot;datasets&quot;<br><br>s3_client = boto3.client(<br>    &quot;s3&quot;,<br>    endpoint_url=MINIO_ENDPOINT,<br>    aws_access_key_id=MINIO_ACCESS_KEY,<br>    aws_secret_access_key=MINIO_SECRET_KEY,<br>    config=Config(signature_version=&quot;s3v4&quot;),<br>    region_name=&quot;us-east-1&quot;<br>)<br><br>def generate_presigned_upload_url(https://medium.com/object_name:%20str,%20expiration=3600):<br>    &quot;&quot;&quot;<br>    Generate a presigned URL to share with a client so they can upload <br>    a file directly to MinIO without passing through the backend server.<br>    &quot;&quot;&quot;<br>    print(f&quot;Generating presigned URL for {object_name}...&quot;)<br>    response = s3_client.generate_presigned_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20&#39;put_object&#39;,%3Cbr%3E%20%20%20%20%20%20%20%20Params={%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&#39;Bucket&#39;:%20BUCKET_NAME,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&#39;Key&#39;:%20object_name,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&#39;ContentType&#39;:%20&#39;application/octet-stream&#39;%3Cbr%3E%20%20%20%20%20%20%20%20},%3Cbr%3E%20%20%20%20%20%20%20%20ExpiresIn=expiration%3Cbr%3E)<br>    return response<br><br>if __name__ == &quot;__main__&quot;:<br>    object_key = &quot;uploads/client_data_01.bin&quot;<br>    url = generate_presigned_upload_url(https://medium.com/object_key)<br>    <br>    print(f&quot;\n[Backend Generated URL]:\n{url}&quot;)<br>    print(&quot;\n--- Simulating Client Side Upload ---&quot;)<br>    <br>    # Simulate a client uploading a file directly using the presigned URL<br>    dummy_file_content = b&quot;This is a massive payload directly uploaded from the client.&quot;<br>    <br>    # The client just performs a standard HTTP PUT request<br>    headers = {&#39;Content-Type&#39;: &#39;application/octet-stream&#39;}<br>    response = requests.put(url, data=dummy_file_content, headers=headers)<br>    <br>    if response.status_code == 200:<br>        print(&quot;Upload successful!&quot;)<br>    else:<br>        print(f&quot;Upload failed: {response.status_code} - {response.text}&quot;)</pre><p>Output:</p><pre>Generating presigned URL for uploads/client_data_01.bin...<br><br>[Backend Generated URL]:<br>http://localhost:9000/datasets/uploads/client_data_01.bin?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=admin%2F20260311%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20260311T204201Z&amp;X-Amz-Expires=3600&amp;X-Amz-SignedHeaders=content-type%3Bhost&amp;X-Amz-Signature=9425de685ee1e4c6132ebaffb218788235dc5cb79d995d05fd8051e4a056441d<br><br>--- Simulating Client Side Upload ---<br>Upload successful!</pre><p>This is a critical architectural pattern for scalable data pipelines. Your backend API never actually touches the heavy data!</p><h3><strong>3. Event-Driven AI Pipelines</strong></h3><p>True automation in AI data processing happens through event-driven architectures.</p><p>When a new dataset partition is uploaded to a bucket, you don’t want to write a script that polls the bucket every 5 minutes to check for changes. You want MinIO to instantly tell your system: “<em>Hey, a new CSV arrived!”</em> so you can kick off an Apache Airflow DAG or a parsing function.</p><p><strong>The Solution:</strong> Bucket Event Notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*zrZeZ0syMideqfPTz6AnNw.png" /><figcaption>Complete advanced MinIO architecture: using presigned URLs to bypass backend bottlenecks, and webhooks to trigger event-driven AI pipelines.</figcaption></figure><p>Because we already added the <strong>MINIO_NOTIFY_WEBHOOK</strong> variables to our <strong>docker-compose.yml</strong>, MinIO knows that a webhook integration named <strong>primary</strong> exists. Now we just use <strong>boto3</strong> to attach that webhook to specific file events in our bucket.</p><p>First, we need a server to actually receive these events! Save the following code as <strong>04_webhook_server.py</strong>. It listens on port 8080 (which is what <a href="http://host.docker.internal:8080/ingest"><strong>http://host.docker.internal:8080/ingest</strong></a> in the docker-compose.yml points to!).</p><pre>from flask import Flask, request, jsonify<br>import json<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/ingest&#39;, methods=[&#39;POST&#39;])<br>def handle_minio_event():<br>    &quot;&quot;&quot;<br>    This endpoint receives Webhook events from MinIO.<br>    In a real AI pipeline, this is where you would trigger an Airflow DAG,<br>    a Ray job, or a Serverless function to process the new data.<br>    &quot;&quot;&quot;<br>    event_data = request.json<br>    <br>    if not event_data or &#39;EventName&#39; not in event_data:<br>        print(&quot;\n--- Received Webhook Payload ---&quot;)<br>        print(json.dumps(event_data, indent=2))<br>        return jsonify({&quot;status&quot;: &quot;received_unknown_payload&quot;}), 200<br><br>    print(f&quot;\n🚀 Received MinIO Event: {event_data[&#39;EventName&#39;]}&quot;)<br>    <br>    # MinIO events can contain multiple records<br>    for record in event_data.get(&#39;Records&#39;, []):<br>        bucket_name = record[&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>        object_key = record[&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>        object_size = record[&#39;s3&#39;][&#39;object&#39;][&#39;size&#39;]<br>        <br>        print(f&quot;📦 New file detected!&quot;)<br>        print(f&quot;   Bucket: {bucket_name}&quot;)<br>        print(f&quot;   File:   {object_key}&quot;)<br>        print(f&quot;   Size:   {object_size} bytes&quot;)<br>        print(f&quot;   Action: Kicking off data processing pipeline...&quot;)<br>        print(&quot;-&quot; * 30)<br><br>    return jsonify({&quot;status&quot;: &quot;success&quot;}), 200<br><br>if __name__ == &#39;__main__&#39;:<br>    print(&quot;Starting Webhook Receiver on port 8080...&quot;)<br>    print(&quot;Listening for MinIO events at http://localhost:8080/ingest&quot;)<br>    # Run on all interfaces so Docker can reach it via host.docker.internal<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080)</pre><p>Start the server in a new terminal. Then, in another terminal, run the following <strong>03_event_notifications.py</strong> script to configure MinIO to send the events.</p><p>You might notice the target ARN in the code below uses sqs (arn:minio:sqs…). Why SQS for an HTTP webhook? Because MinIO maintains strict AWS S3 API compatibility, it maps all notification targets (Webhooks, Kafka, Postgres, etc.) to the standard S3 QueueConfigurations API structure.</p><pre>import boto3<br>from botocore.client import Config<br>import json<br><br># Configuration<br>MINIO_ENDPOINT = &quot;http://localhost:9000&quot;<br>MINIO_ACCESS_KEY = &quot;admin&quot;<br>MINIO_SECRET_KEY = &quot;password123&quot;<br>BUCKET_NAME = &quot;datasets&quot;<br><br>s3_client = boto3.client(<br>    &quot;s3&quot;,<br>    endpoint_url=MINIO_ENDPOINT,<br>    aws_access_key_id=MINIO_ACCESS_KEY,<br>    aws_secret_access_key=MINIO_SECRET_KEY,<br>    config=Config(signature_version=&quot;s3v4&quot;),<br>    region_name=&quot;us-east-1&quot;<br>)<br><br>def setup_webhook_notification():<br>    &quot;&quot;&quot;<br>    This script attaches an event configuration to a bucket via boto3, <br>    assuming the MinIO server has a webhook target named &#39;primary&#39; configured.<br>    (We configured MINIO_NOTIFY_WEBHOOK env vars in the docker-compose file).<br>    &quot;&quot;&quot;<br>    print(&quot;Setting up bucket notification configuration...&quot;)<br>    <br>    # Target ARN format for MinIO Webhooks is typically:<br>    # arn:minio:sqs::primary:webhook <br>    # where &#39;primary&#39; is the identifier of the webhook configured in MinIO.<br>    target_arn = &quot;arn:minio:sqs::primary:webhook&quot;<br>    <br>    notification_configuration = {<br>        &#39;QueueConfigurations&#39;: [<br>            {<br>                &#39;Id&#39;: &#39;NotifyOnCsvUpload&#39;,<br>                &#39;QueueArn&#39;: target_arn,<br>                &#39;Events&#39;: [&#39;s3:ObjectCreated:*&#39;],<br>                &#39;Filter&#39;: {<br>                    &#39;Key&#39;: {<br>                        &#39;FilterRules&#39;: [<br>                            {&#39;Name&#39;: &#39;prefix&#39;, &#39;Value&#39;: &#39;raw/&#39;},<br>                            {&#39;Name&#39;: &#39;suffix&#39;, &#39;Value&#39;: &#39;.csv&#39;}<br>                        ]<br>                    }<br>                }<br>            }<br>        ]<br>    }<br><br>    try:<br>        s3_client.put_bucket_notification_configuration(<br>            Bucket=BUCKET_NAME,<br>            NotificationConfiguration=notification_configuration<br>        )<br>        print(&quot;Success! MinIO will now send Webhook payloads to the configured endpoint&quot;)<br>        print(&quot;when any new &#39;.csv&#39; file is uploaded specifically to the &#39;raw/&#39; prefix.&quot;)<br>    except Exception as e:<br>        print(f&quot;Warning: Could not set notification configuration.&quot;)<br>        print(f&quot;Make sure the Webhook target &#39;{target_arn}&#39; is configured in the MinIO server.&quot;)<br>        print(f&quot;Error details: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    setup_webhook_notification()</pre><p>Output:</p><pre>Setting up bucket notification configuration...<br>Success! MinIO will now send Webhook payloads to the configured endpoint<br>when any new &#39;.csv&#39; file is uploaded specifically to the &#39;raw/&#39; prefix.</pre><p>With this configuration, every time a <strong>.csv</strong> file is dropped into the <strong>datasets</strong> bucket under the <strong>raw/</strong> folder using the <strong>01_basic_crud.py</strong>, MinIO instantly sends a JSON payload to your webhook, and the server will log the following:</p><pre>🚀 Received MinIO Event: s3:ObjectCreated:Put<br>📦 New file detected!<br>   Bucket: datasets<br>   File:   raw%2Fbatch_004.csv<br>   Size:   35 bytes<br>   Action: Kicking off data processing pipeline...</pre><p>Notice how the filename in the output is raw%2Fbatch_004.csv? The forward slash (/) gets URL-encoded as %2F. In a real production Python pipeline, you must use urllib.parse.unquote(object_key) to decode the string back to <strong>raw/batch_004.csv</strong> before passing it to your downstream AI tasks.</p><h3><strong>Conclusion</strong></h3><p>You have just gone from spinning up a basic local container to architecting a highly scalable, event-driven data pipeline. As AI datasets continue to grow, relying on standard REST APIs for file uploads is no longer viable. By leveraging presigned URLs and Webhooks, you now have a blueprint to move massive amounts of data efficiently without melting servers!</p><p>Source code link:</p><p><a href="https://github.com/Sohaib9920/minio-from-scratch">GitHub - Sohaib9920/minio-from-scratch: Minio from zero to advanced</a></p><h3>About VannGuard AI</h3><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ebbd584347" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/minio-from-zero-to-advanced-86ebbd584347">MinIO: From Zero to Advanced</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Autonomous Lead-Gen Agent with n8n (No Code Required)]]></title>
            <link>https://medium.com/vannguardai/building-an-autonomous-lead-gen-agent-with-n8n-no-code-required-4185b6c605fc?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/4185b6c605fc</guid>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Dur-e-Shahwar]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 12:46:42 GMT</pubDate>
            <atom:updated>2026-04-07T11:20:16.858Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Groq, SerpAPI, Airtable, and Slack wired together into a fully autonomous sales pipeline!</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mk45GZibRp0xZRdhYho79Q.png" /></figure><p>Automation tools like Zapier or Make excel at linear tasks but struggle with complex, dynamic reasoning. For workflows that require actual decision-making, n8n provides a much more robust, agentic alternative.</p><p>n8n is an open-source workflow automation platform that recently introduced a native AI Agent builder, fundamentally shifting how workflow design is approached. Traditional automation is deterministic: if X, do Y. AI agents are different. They reason, they plan, they decide which steps to take on their own, and they handle edge cases without you writing a single condition for them.</p><p>This article builds a fully autonomous lead-gen agent from scratch, one that researches companies, scores them, drafts personalized outreach emails, logs everything to a CRM, and notifies on Slack. All of it for free!</p><h3>What We’re Building</h3><p>Here’s the full pipeline we’ll assemble. Each step is a node on the n8n canvas, connected by arrows, with data flowing left to right:</p><ol><li><strong>Schedule Trigger:</strong> Fires every morning at 8 AM automatically</li><li><strong>Google Sheets:</strong> Reads your prospect list, filtering only “Pending” companies</li><li><strong>AI Agent (Groq + Llama 3.3 70B):</strong> Researches each company, scores them 1–10, and extracts pain points and talking points</li><li><strong>IF Filter:</strong> Passes scores ≥7 to the qualified branch; everything else is marked “Low Quality” and skipped</li><li><strong>Basic LLM Chain:</strong> Drafts a personalized cold email for each qualified lead</li><li><strong>Airtable:</strong> Logs the company, score, pain points, and draft email to your CRM</li><li><strong>Slack:</strong> Sends a real-time notification with all the key details</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFbXroVwYqeR7UCKXS9DiA.jpeg" /><figcaption>The complete n8n autonomous lead-gen architecture; all nodes connected and running successfully</figcaption></figure><h3>Technical Requirements</h3><p>To implement this workflow, you will need active accounts and API access for the following tools:</p><ul><li>n8n Instance: A Cloud, Desktop, or self-hosted version of n8n.</li><li>Groq API Key: Required for the Llama 3.3 70B model (obtainable via the Groq Cloud Console).</li><li>Search Tool API Key: A key from SerpAPI to allow the agent to access the web.</li><li>Google Sheets Access: A Google Sheet URL and a Google Cloud Console project with the Google Sheets API enabled to authenticate the connection.</li><li>Airtable Credentials: An Airtable Personal Access Token (PAT) and your Base ID to allow the workflow to log leads into your CRM.</li></ul><h3><strong>Setting Up Your Prospect List</strong></h3><p>Create a new Google Sheet named “Lead Gen Prospects” with these exact column headers in Row 1:</p><pre>company_name | website_url | industry | company_size | status</pre><p>The status column is what makes this pipeline safe to run on a schedule. Every row starts as “Pending”. Once the agent processes a company, its status is updated to “Processed”, and the Google Sheets node is configured to read only rows where the status equals “Pending”. This means the same company can never be processed twice, no matter how many times the workflow runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*XDOWneBhCNczUC1TC6yY_w.png" /><figcaption>Input source: Prospect list with ‘Pending’ status control</figcaption></figure><h3>Building the Pipeline in n8n</h3><p>Open n8n, click “New Workflow”, and name it “Lead Gen Agent v1”. The canvas is your workspace. Click the + button to add each node in sequence.</p><h4>1. Schedule Trigger</h4><p>Search for “Schedule Trigger” and add it as your first node. Set it to fire every day at 8:00 AM. This is the heartbeat of your agent; it wakes up every morning and kicks off the entire pipeline without any human intervention.</p><h4>2. Google Sheets: Read Your Prospect List</h4><p>Add a Google Sheets node and connect your Google account. Select your “Lead Gen Prospects” sheet, then add a filter so it only returns rows where the status column equals “Pending”. Click Test Step, you should see your prospect rows appear in the output panel on the right.</p><p>n8n doesn’t require a manual ‘Loop’ or ‘Iterator’ node; it treats every row returned from the Google Sheet as an individual item. The workflow will automatically execute the subsequent nodes for each lead in your list.</p><h4>3. The AI Agent: Where the Intelligence Lives</h4><p>This is the most important node. Add an AI Agent node, then attach two sub-nodes to it: a Groq Chat Model (llama-3.3–70b-versatile) and a SerpAPI tool. The Groq model does the reasoning; SerpAPI gives it the ability to search the web for real-time company information when needed.</p><blockquote>Groq’s inference engine was selected because of its ultra-low latency; processing hundreds of tokens per second. It is ideal for agentic workflows. Other options like OpenAI or Anthropic work too, but slower inference risks timing out the n8n pipeline mid-execution, especially once you scale beyond a handful of leads.</blockquote><p>Set the System Message to:</p><pre>You are a B2B sales research assistant. <br><br>Given a company name and website, your job is to:<br><br>1. Identify the company&#39;s top 2–3 pain points<br>2. Score the lead 1–10 based on B2B software product fit<br>3. Extract 2–3 specific talking points for outreach<br>4. Identify the likely decision maker title<br><br>Only use SerpAPI if you cannot answer from your existing knowledge. <br><br>Return ONLY valid JSON:<br>{<br>  &quot;score&quot;: 8, <br>  &quot;pain_points&quot;: &quot;…&quot;, <br>  &quot;decision_maker&quot;: &quot;…&quot;, <br>  &quot;talking_points&quot;: &quot;…&quot;<br>}</pre><p>And the User Message:</p><pre>Research this company:<br>  Company: {{ $json.company_name }}<br>  Website: {{ $json.website_url }}<br>  Industry: {{ $json.industry }}</pre><h4>4. IF Filter: Qualifying Your Leads</h4><p>Add an IF node after the AI Agent. It acts as a quality gate. Set the condition to check whether the lead score meets your threshold:</p><pre>{{ JSON.parse($json.output).score }} &gt;= 7</pre><p>The TRUE branch continues to email drafting and Airtable. The FALSE branch connects to a Google Sheets update node that marks the status as “Low Quality,” ensuring these leads are excluded from future runs.</p><h4>5. Email Drafter: Personalized Outreach at Scale</h4><p>On the TRUE branch, add a “Basic LLM Chain” node with another Groq Chat Model attached. This is a straight LLM call, not an agent, because we want consistent, template-like output rather than autonomous reasoning. Feed it the enrichment data from the AI Agent node:</p><pre>Write a personalized cold email for {{ $(&#39;Get row(s) in sheet&#39;).item.json.company_name }}.<br><br>Pain points: {{ JSON.parse($(&#39;AI Agent&#39;).item.json.output).pain_points }}<br>Talking points: {{ JSON.parse($(&#39;AI Agent&#39;).item.json.output).talking_points }}<br>Decision maker: {{ JSON.parse($(&#39;AI Agent&#39;).item.json.output).decision_maker }}<br><br>Write: subject line + 3 short paragraphs under 150 words. <br><br>End with a soft CTA for a 15-minute call.</pre><p>This configuration ensures the LLM produces consistent outreach based specifically on the pain points identified in Step 3. The result is a high-quality draft saved directly into your CRM, formatted and ready for a final human review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*XP3YHWqe0qM6MBfQrMvV6Q.png" /><figcaption>Detailed outreach draft saved within the Airtable lead record</figcaption></figure><h4>6. Finalizing the Record and Closing the Loop</h4><p>The final stage of the pipeline transitions the agent’s findings into your CRM and notification systems while ensuring the source data is updated to prevent duplicate processing.</p><p><strong>a. Airtable</strong></p><p>Add an Airtable node to create a new record. Map the company name, website, lead score, and the draft email from the previous nodes.</p><p>Airtable’s Lead Score field typically requires a “Number” data type. To avoid a validation error, wrap the expression in the Number() function to cast the string as an integer:</p><pre>{{ Number(JSON.parse($(&#39;AI Agent&#39;).item.json.output).score) }}</pre><p>Once the workflow runs, your Airtable transforms from a blank list into a fully enriched sales CRM. Every lead is now ranked, researched, and ready for outreach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sm2gYGlleedktzyzyuatNA.png" /><figcaption>The CRM output: Enriched, scored, and prioritized leads</figcaption></figure><p><strong>b. Google Sheets (Status Update):</strong></p><p>Add a Google Sheets node and set the action to Update. To ensure the correct lead is updated, map the Row Number variable from the initial Google Sheets node into the lookup field and set the “Status” column to “Processed.”</p><p>This step is critical for maintaining the “state” of your lead list. By updating the status based on the Row Number, you ensure the agent never researches or emails the same lead twice in subsequent runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*HWgN4mZ7PfxwzgqDYtFAhA.png" /><figcaption>Updated source sheet with ‘Processed’ status to prevent duplicates</figcaption></figure><p><strong>c. Slack:</strong></p><p>Add a Slack node to fire a real-time notification to your team’s channel. Configure the message to include a summary of the qualified lead, the AI-assigned score, and identified pain points.</p><p>This notification provides an essential “sanity check,” delivering high-value opportunity data directly to your communication hub so the team can act on fresh leads as they are discovered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCEYim-_nFTvw7KttAj4OA.png" /><figcaption>Automated Slack alert for high-value qualified leads</figcaption></figure><h3>Where to Take This Next</h3><p>Once you are comfortable with this base configuration, you can further enhance the system by:</p><ul><li><strong>Human-in-the-loop approval: </strong>Adding an “Approve/Reject” step via n8n webhooks before emails are sent.</li><li><strong>Automated Sourcing: </strong>Integrating Phantombuster or LinkedIn scrapers to auto-populate your prospect list.</li><li><strong>Vector Memory: </strong>Connecting a database like Pinecone so the agent remembers past interactions across multiple runs.</li><li><strong>Closed-Loop Feedback: </strong>Logging reply rates back into the system to refine the scoring prompt over time.</li></ul><h3>Conclusion</h3><p>This workflow demonstrates how agentic automation moves beyond linear “if/then” logic to handle the complex reasoning required for lead research. By leveraging n8n’s AI Agent and the Llama 3.3 model, we have built a system that is significantly more resilient than traditional automation; one that can interpret inconsistent data and adapt to edge cases autonomously.</p><p>The result is a pipeline that automates the highest-friction phase of prospecting, ensuring sales teams start their day with pre-qualified, researched leads. Key takeaways include:</p><ul><li>AI agents reason through data inconsistencies that would typically break standard deterministic workflows.</li><li>Groq’s Llama 3.3 70B low-latency inference provides the speed and intelligence needed for production-quality outreach drafting at scale.</li><li>A simple status-column logic ensures reliable, duplicate-free execution on a daily schedule.</li><li>The entire stack is accessible on free tiers, making this a low-risk, high-impact implementation for any team.</li></ul><p>If you build this and run into something unexpected, drop it in the comments. We’d love to hear what you’re building on top of it.</p><h3>References</h3><ul><li><a href="https://n8n.io/">n8n.io</a></li><li><a href="https://console.groq.com/home">Groq Cloud Console</a> (Llama 3.3 70B)</li><li><a href="https://serpapi.com/">SerpAPI</a></li><li><a href="https://airtable.com/">Airtable </a>&amp; <a href="https://docs.google.com/spreadsheets/">Google Sheets</a></li><li><a href="https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.agent/">n8n AI Agent Node Documentation</a></li></ul><h3>About VannGuard AI</h3><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4185b6c605fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/building-an-autonomous-lead-gen-agent-with-n8n-no-code-required-4185b6c605fc">Building an Autonomous Lead-Gen Agent with n8n (No Code Required)</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chat Agent with LangGraph (Part 3): Taking Your Agent to Production]]></title>
            <link>https://medium.com/vannguardai/building-a-chat-agent-with-langgraph-part-3-taking-your-agent-to-production-431280431d7f?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/431280431d7f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Zuhair Zaidi]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 15:32:38 GMT</pubDate>
            <atom:updated>2026-03-27T15:32:37.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LkTGas4F7i0nYUDXh_eCg.png" /></figure><p>Building a powerful AI agent is only half the battle; getting it seamlessly into the hands of users is where the real value is created. An intelligent LangGraph agent running in a local Python terminal is a fantastic engineering milestone.</p><p>However, think about our target end-user: the junior doctor on her morning ward round from Part 2. She isn’t going to open a terminal and execute a Python script to ask a clinical question. To scale this into a fully usable product for professionals like her, it needs a stable API, an intuitive user interface, and a reliable deployment architecture.</p><p><em>(Note: This guide builds directly on the previous work. It is highly recommended to review </em><a href="https://medium.com/vannguardai/building-a-rag-ai-agent-with-langgraph-a-complete-guide-0432d0d1344c"><em>Part 1: Building a Hybrid RAG Pipeline</em></a><em> and </em><a href="https://medium.com/vannguardai/building-a-chat-agent-with-langgraph-part-2-your-rag-pipeline-can-retrieve-but-can-it-remember-3c709eac3123"><em>Part 2: Adding Persistent Memory</em></a><em> before diving into this deployment phase.)</em></p><h3>The Blueprint: Three Steps to Production</h3><p>To transform our local script into a deployable application, we will follow a strict sequence of action items. Here is our step-by-step plan:</p><h4>Step 1: Establish a Backend API</h4><p>We need to wrap our agent in a stable, documented interface so external applications can communicate with it.</p><h4>Step 2: Build the User Interface</h4><p>We need to transition from a developer terminal to a familiar chat interface for end-users.</p><h4>Step 3: Containerize the Stack</h4><p>We must bundle the frontend, backend, and databases together so the application runs reliably on any server.</p><p>Let’s execute these steps in order.</p><h3>Step 1: Establish a Backend API (FastAPI)</h3><p>FastAPI turns your Python function into a proper HTTP endpoint. More importantly, it automatically generates documentation, handles request validation, and gives every caller a clean, stable interface that doesn’t require touching your source code.</p><h4>Initialize the App</h4><p>First, initialize the FastAPI app and attach CORS middleware. This is necessary because our Streamlit frontend runs on port 8501 while the API runs on port 8000, and without CORS, the browser will block every request before it even leaves the page.</p><pre>from fastapi import FastAPI, HTTPException<br>from fastapi.middleware.cors import CORSMiddleware<br>from app.rag import ingestion_pipeline<br>from pydantic import BaseModel<br>from app.graph import rag_graph<br>from typing import Optional<br>import uuid<br><br>api = FastAPI(title=&quot;Medical RAG Agent API&quot;)<br><br>@api.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    print(&quot;--- STARTUP: Initializing services ---&quot;)<br>    try:<br>        # Ensure PostgreSQL tables are created<br>        checkpointer.setup()<br>        print(&quot;--- STARTUP: Database setup complete ---&quot;)<br>    except Exception as e:<br>        print(f&quot;--- STARTUP ERROR: {e} ---&quot;)<br>        raise e<br><br>api.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],  # Lock this down to your frontend domain in production<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)</pre><h4>Define Your Contracts</h4><p>Before writing any endpoint logic, it needs to be defined what exactly goes in and what comes out. Notice that session_id is optional on the way in but required on the way out. A client that doesn&#39;t send one gets a fresh session, and a client that sends the same ID picks up exactly where it left off. That&#39;s the entire memory system in the schema design as follows:</p><pre>class QueryRequest(BaseModel):<br>    query: str<br>    session_id: Optional[str] = None  # If None, generate a fresh one<br><br>class QueryResponse(BaseModel):<br>    answer: str<br>    optimized_query: str<br>    is_medical: bool<br>    error_message: str = &quot;&quot;<br>    session_id: str          # Always return this; the client needs it for continuity</pre><h4>Write the Core Endpoint</h4><p>This is where everything from Parts 1 and 2 gets stitched together. The key line to pay attention to is config = {&quot;configurable&quot;: {&quot;thread_id&quot;: session_id}} — this is what tells LangGraph which conversation to resume. Pass the same session_id and the graph loads the saved PostgreSQL checkpoint before any node runs. Pass nothing, and you get a clean slate.</p><pre>@api.post(&quot;/query&quot;, response_model=QueryResponse)<br>async def process_query(request: QueryRequest):<br>    try:<br>        # If the client doesn&#39;t have a session yet, start one<br>        session_id = request.session_id or str(uuid.uuid4())<br>        <br>        # This is how LangGraph knows which PostgreSQL checkpoint to load<br>        config = {&quot;configurable&quot;: {&quot;thread_id&quot;: session_id}}<br>        <br>        initial_state = {<br>            &quot;messages&quot;: [],<br>            &quot;original_query&quot;: request.query,<br>            &quot;optimized_query&quot;: &quot;&quot;,<br>            &quot;retrieved_context&quot;: &quot;&quot;,<br>            &quot;final_answer&quot;: &quot;&quot;,<br>            &quot;is_medical_query&quot;: True,<br>            &quot;error_message&quot;: &quot;&quot;,<br>            &quot;session_id&quot;: session_id<br>        }<br>        <br>        # Run the full four-node pipeline from Part 2<br>        result = rag_graph.invoke(initial_state, config)<br>        <br>        # Handle off-topic queries gracefully<br>        if not result[&quot;is_medical_query&quot;]:<br>            return QueryResponse(<br>                answer=result.get(&quot;error_message&quot;, &quot;Query rejected&quot;),<br>                optimized_query=&quot;&quot;,<br>                is_medical=False,<br>                error_message=result.get(&quot;error_message&quot;, &quot;&quot;),<br>                session_id=session_id<br>            )<br>        <br>        return QueryResponse(<br>            answer=result[&quot;final_answer&quot;],<br>            optimized_query=result[&quot;optimized_query&quot;],<br>            is_medical=result[&quot;is_medical_query&quot;],<br>            session_id=session_id<br>        )<br>        <br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))</pre><h4>Add Two Utility Endpoints</h4><p>Now there is a need to add a /health endpoint so our Docker orchestrator knows when the service is ready, and an /ingest endpoint to refresh the medical knowledge base without SSHing into the server and running a Python script manually.</p><pre>@api.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Confirm the service is up and the checkpointer is connected.&quot;&quot;&quot;<br>    return {&quot;status&quot;: &quot;healthy&quot;, &quot;checkpointer&quot;: &quot;connected&quot;}<br><br>@api.post(&quot;/ingest&quot;)<br>async def run_ingestion():<br>    &quot;&quot;&quot;Re-trigger the Part 1 ingestion pipeline to refresh the knowledge base.&quot;&quot;&quot;<br>    try:<br>        ingestion_pipeline()<br>        return {&quot;status&quot;: &quot;success&quot;, &quot;message&quot;: &quot;Ingestion completed successfully!&quot;}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=f&quot;Ingestion failed: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(api, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>Visit http://localhost:8000/docs after starting the server. FastAPI generates a full interactive Swagger UI automatically, covering every endpoint and every field, with a built-in test interface. You didn&#39;t have to write a single line of documentation for that.</p><h3>Step 2: Build the User Interface (Streamlit)</h3><p>The API solves Problem 1. But a junior doctor on morning rounds isn’t going to open Postman and craft a JSON payload. They need a chat window. Streamlit lets us build one. No JavaScript. No React. Just Python.</p><h4>Initial Setup</h4><p>Load our environment variables, grab the backend URL, and configure the Streamlit page. Nothing complex here, just the foundation everything else sits on.</p><pre>import streamlit as st<br>import requests<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>backend_endpoint = os.environ.get(&quot;BACKEND_URL&quot;, &quot;http://127.0.0.1:8000&quot;).rstrip(&quot;/&quot;)<br>st.set_page_config(<br>    page_title=&quot;Medical RAG Chatbot&quot;,<br>    page_icon=&quot;🏥&quot;,<br>    layout=&quot;wide&quot;<br>)<br>st.title(&quot;Medical RAG Chatbot&quot;)<br>st.markdown(&quot;Ask questions about medical conditions, symptoms, and treatments.&quot;)</pre><h4>Handle the Session Memory Problem</h4><p>Here’s something that trips everyone up with Streamlit: it reruns the entire script from top to bottom on every single user interaction. Click a button, send a message, anything. Full rerun. st.session_state is used to preserve the session_id and message history across those reruns, because without it, every variable resets and the conversation disappears.</p><pre>if &quot;session_id&quot; not in st.session_state:<br>    st.session_state.session_id = None   # None until the first query creates one<br>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []       # Grows with every turn</pre><h4>Display the Conversation History</h4><p>Loop through the saved messages and render them as chat bubbles. For assistant messages, tuck an expandable details section underneath so users can see exactly what query hit the vector database. When the system rewrites “What are its complications?” into “What are the complications of community-acquired pneumonia in elderly patients?”, that rewrite is visible, which builds trust and makes debugging much faster.</p><pre>for message in st.session_state.messages:<br>    with st.chat_message(message[&quot;role&quot;]):<br>        st.markdown(message[&quot;content&quot;])<br>        <br>        if message[&quot;role&quot;] == &quot;assistant&quot; and &quot;metadata&quot; in message:<br>            with st.expander(&quot;Query Details&quot;):<br>                st.json(message[&quot;metadata&quot;])</pre><h4>Handle User Input</h4><p>Wire up the chat input box, send the query to the backend, and handle the response. Pay close attention to st.session_state.session_id = data[&quot;session_id&quot;], on the first turn, the frontend sends None, the backend generates a fresh UUID and returns it, and from that point, every request carries that same ID back to the same PostgreSQL checkpoint.</p><pre>if prompt := st.chat_input(&quot;Ask a medical question...&quot;):<br>    <br>    st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br>    with st.chat_message(&quot;user&quot;):<br>        st.markdown(prompt)<br>    <br>    with st.chat_message(&quot;assistant&quot;):<br>        with st.spinner(&quot;Thinking...&quot;):<br>            try:<br>                response = requests.post(<br>                    f&quot;{backend_endpoint}/query&quot;,<br>                    json={<br>                        &quot;query&quot;: prompt,<br>                        &quot;session_id&quot;: st.session_state.session_id  # None on first turn<br>                    },<br>                    timeout=300<br>                )<br>                <br>                if response.status_code == 200:<br>                    data = response.json()<br>                    <br>                    # Lock in the session ID from the first response<br>                    st.session_state.session_id = data[&quot;session_id&quot;]<br>                    <br>                    if not data[&quot;is_medical&quot;]:<br>                        st.warning(&quot;That doesn&#39;t appear to be a medical question.&quot;)<br>                        st.session_state.messages.append({<br>                            &quot;role&quot;: &quot;assistant&quot;,<br>                            &quot;content&quot;: &quot;That doesn&#39;t appear to be a medical question.&quot;,<br>                            &quot;metadata&quot;: {<br>                                &quot;Session ID&quot;: data[&quot;session_id&quot;],<br>                                &quot;Optimized Query&quot;: &quot;&quot;,<br>                                &quot;Domain Check&quot;: &quot;Failed&quot;<br>                            }<br>                        })<br>                    else:<br>                        st.markdown(data[&quot;answer&quot;])<br>                        <br>                        st.session_state.messages.append({<br>                            &quot;role&quot;: &quot;assistant&quot;,<br>                            &quot;content&quot;: data[&quot;answer&quot;],<br>                            &quot;metadata&quot;: {<br>                                &quot;Session ID&quot;: data[&quot;session_id&quot;],<br>                                &quot;Optimized Query&quot;: data[&quot;optimized_query&quot;],<br>                                &quot;Domain Check&quot;: &quot;Passed&quot; if data[&quot;is_medical&quot;] else &quot;Failed&quot;<br>                            }<br>                        })<br>                else:<br>                    st.error(f&quot;Backend returned {response.status_code}&quot;)<br>                    <br>            except Exception as e:<br>                st.error(f&quot;Connection error: {str(e)}&quot;)</pre><h4>Add the Admin Sidebar</h4><p>Add a sidebar with an ingestion trigger button and some context about the system for anyone using it for the first time.</p><pre>with st.sidebar:<br>    st.header(&quot;Admin Tools&quot;)<br>    <br>    if st.button(&quot;Run Ingestion Pipeline&quot;):<br>        with st.spinner(&quot;Ingesting documents... this may take a few minutes.&quot;):<br>            try:<br>                response = requests.post(f&quot;{backend_endpoint}/ingest&quot;, timeout=300)<br>                if response.status_code == 200:<br>                    st.success(&quot;Knowledge base updated successfully!&quot;)<br>                else:<br>                    st.error(f&quot;Ingestion failed: {response.text}&quot;)<br>            except Exception as e:<br>                st.error(f&quot;Could not reach backend: {e}&quot;)<br>    <br>    st.markdown(&quot;---&quot;)<br>    st.header(&quot;How It Works&quot;)<br>    st.markdown(&quot;&quot;&quot;<br>    - **LangGraph** routes and manages each turn<br>    - **Hybrid RAG** (dense + sparse) retrieves from Qdrant<br>    - **Cross-encoder reranking** improves precision<br>    - **PostgreSQL** persists every session<br>    &quot;&quot;&quot;)<br>    <br>    st.markdown(&quot;---&quot;)<br>    st.header(&quot;Try This Conversation&quot;)<br>    st.markdown(&quot;&quot;&quot;<br>    1. *&quot;What are the symptoms of pneumonia in elderly patients?&quot;*<br>    2. *&quot;What causes it?&quot;*<br>    3. *&quot;What&#39;s the first-line treatment?&quot;*<br>    4. *&quot;What if they&#39;re penicillin-allergic?&quot;*<br>    &quot;&quot;&quot;)</pre><h3>Step 3: Containerize the Stack (Docker)</h3><p>You now have five things that need to start in the right order, on the right ports, with the right environment variables, every single time. That’s manageable on your laptop. It’s a support burden everywhere else.</p><p>Docker solves this by packaging every service into a container that carries its own dependencies. Docker Compose solves the orchestration problem by defining exactly how those containers start, connect, and depend on each other.</p><h4>Backend Dockerfile</h4><p>Write a Dockerfile for the backend that installs the system-level PostgreSQL dependencies our Python driver needs, then copies and runs the FastAPI app.</p><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    libpq-dev \<br>    gcc \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY app/ ./app/<br>CMD [&quot;uvicorn&quot;, &quot;app.main:api&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h4>Frontend Dockerfile</h4><p>The frontend has no system-level dependencies at all, so keep this Dockerfile as simple as possible. It’s pure Python, install packages, and run Streamlit.</p><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY app.py .<br>CMD [&quot;streamlit&quot;, &quot;run&quot;, &quot;app.py&quot;, &quot;--server.port=8501&quot;, &quot;--server.address=0.0.0.0&quot;]</pre><h4>Docker Compose: Where It All Comes Together</h4><p>This is the file that replaces the startup checklist. Define all five services, their dependencies, and their environment variables in one place so the entire stack starts with a single command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IoF8UNEj7x7sYAvTyhosg.png" /></figure><p>Start with PostgreSQL. The healthcheck block is not optional; without it, depends_on only waits for the container to start, not for PostgreSQL to actually be ready to accept connections. The backend would try to connect during those first few seconds, fail, and crash.</p><pre>services:<br>  postgres:<br>      image: postgres:15-alpine<br>      environment:<br>        - POSTGRES_DB=checkpoints<br>        - POSTGRES_USER=postgres<br>        - POSTGRES_PASSWORD=postgres<br>      ports:<br>        - &quot;5432:5432&quot;<br>      volumes:<br>        - postgres_data:/var/lib/postgresql/data<br>      healthcheck:<br>        test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U postgres&quot;]<br>        interval: 5s<br>        timeout: 5s<br>        retries: 5</pre><p>Next, Qdrant and the embedding services. These are straightforward: expose the ports and mount a volume so that data services restart.</p><pre>qdrant:<br>    image: qdrant/qdrant:latest<br>    ports:<br>      - &quot;6333:6333&quot;   # REST API<br>      - &quot;6334:6334&quot;   # gRPC<br>    volumes:<br>      - qdrant_storage:/qdrant/storage<br>tei-embedding:<br>    image: ghcr.io/huggingface/text-embeddings-inference:cpu-1.7<br>    ports:<br>      - &quot;8080:80&quot;<br>    volumes:<br>      - tei_data:/data<br>    command: &gt;<br>      --model-id sentence-transformers/all-MiniLM-L6-v2<br>      --port 80<br>      --payload-limit 10485760</pre><p>Now the backend. Use condition: service_healthy for Postgres specifically, so Docker waits for the health check to pass before our app tries to connect.</p><pre>backend:<br>    build:<br>      context: ./backend<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - GROQ_API_KEY=${GROQ_API_KEY}<br>      - FAST_EMBED_CACHE_DIR=/tmp/fastembed_cache<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>      qdrant:<br>        condition: service_started<br>      tei-embedding:<br>        condition: service_started<br>    volumes:<br>      - ./backend/app:/app/app<br>      - ./model_cache:/tmp/fastembed_cache</pre><p>Finally, the frontend. Notice BACKEND_URL=http://backend:8000, this is the line that breaks everyone the first time. Inside Docker Compose, services talk to each other using their service name as the hostname, not localhost. If you use localhost, the frontend tries to reach port 8000 on itself, and there&#39;s nothing there.</p><pre>frontend:<br>    build:<br>      context: ./frontend<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8501:8501&quot;<br>    depends_on:<br>      - backend<br>    environment:<br>      - BACKEND_URL=http://backend:8000</pre><p>Declare named volumes at the bottom. Container filesystems are ephemeral; without these, every restart wipes your conversation history from PostgreSQL and your embeddings from Qdrant.</p><pre>volumes:<br>  postgres_data:<br>  qdrant_storage:<br>  tei_data:</pre><h3>Requirement.txt</h3><pre>langgraph<br>langchain-core<br>langchain-groq<br>qdrant-client<br>fastembed<br>sentence-transformers<br>tiktoken<br>python-dotenv<br>pyyaml<br>requests<br>langchain-text-splitters<br>psycopg[binary,pool]</pre><h3>Starting Everything</h3><pre># Create a virtual environment<br>python3 -m venv .venv<br># Activate the virtual environment<br>source .venv/bin/activate<br># Install the dependencies<br>pip install -r requirements.txt<br># Build and start all services<br>docker compose up --build<br># Or run in the background<br>docker compose up --build -d<br># Watch what&#39;s happening<br>docker compose logs -f<br># Shut everything down<br>docker compose down</pre><p>Once it’s running:</p><ul><li><strong>Chat Interface:</strong> <a href="http://localhost:8501/">http://localhost:8501</a></li><li><strong>API:</strong> <a href="http://localhost:8000/">http://localhost:8000</a></li><li><strong>API Docs:</strong> <a href="http://localhost:8000/docs">http://localhost:8000/docs</a></li><li><strong>Qdrant Dashboard:</strong> <a href="http://localhost:6333/dashboard">http://localhost:6333/dashboard</a></li></ul><p>Below is a live demonstration of the final system resolving complex medical queries and maintaining session memory across multiple turns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6VNFuln2BWuMDlmzQltbw.gif" /></figure><h3>What We Actually Built Across All Three Parts</h3><p>Let’s be precise about this, because it’s easy to lose the thread.</p><p><strong>Part 1</strong> gave us a retrieval pipeline. Fast, accurate, hybrid. It answered questions in milliseconds. But it had no idea who was asking or what they’d asked before.</p><p><strong>Part 2</strong> gave that pipeline memory. A four-node LangGraph agent that resolves pronouns, persists sessions to PostgreSQL, and handles off-topic queries before they ever touch the vector database. But it only ran inside a Python process.</p><p><strong>Part 3</strong> made it real. A FastAPI layer that gives a stable, documented interface. A Streamlit frontend that any user can open in a browser. Docker makes the entire stack reproducible anywhere in a single command.</p><p>The junior doctor from Part 2 can now open a URL, ask a question, follow up without re-typing context, close her laptop at lunchtime, come back in the afternoon, and pick up exactly where she left off.</p><p>That’s the system. Three parts, one production-ready agent.</p><h3>Get the Code</h3><p>The complete, production-ready source code for this Medical RAG Agent is available on GitHub.</p><p>🔗 <strong>GitHub Repository</strong>: <a href="https://github.com/zuhairzaidi63/medical-rag-agent">zuhairzaidi63/medical-rag-agent</a></p><h4>About VannGuard AI</h4><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=431280431d7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/building-a-chat-agent-with-langgraph-part-3-taking-your-agent-to-production-431280431d7f">Building a Chat Agent with LangGraph (Part 3): Taking Your Agent to Production</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chat Agent with LangGraph (Part 2): Your RAG Pipeline Can Retrieve, But Can It Remember?]]></title>
            <link>https://medium.com/vannguardai/building-a-chat-agent-with-langgraph-part-2-your-rag-pipeline-can-retrieve-but-can-it-remember-3c709eac3123?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/3c709eac3123</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Zuhair Zaidi]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 11:45:33 GMT</pubDate>
            <atom:updated>2026-03-27T10:08:05.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xct-a41hEcKcp7Vsmm7-ow.png" /></figure><p>In <a href="https://medium.com/vannguardai/building-a-rag-ai-agent-with-langgraph-a-complete-guide-0432d0d1344c">Part 1</a>, we built a production-ready medical RAG pipeline using Qdrant and hybrid search. Ask it a clinical question like “What are the typical presentation findings for community-acquired pneumonia in elderly patients?” and it retrieves a highly accurate, reranked answer in milliseconds.</p><p>Then you try this:</p><p><strong>You:</strong> “And what is the first-line treatment?”</p><p><strong>System:</strong> “Could you clarify what condition you are referring to?”</p><p>That’s the moment everything you built in Part 1 stops being useful.</p><h3>Here’s What Just Happened</h3><p>Your retrieval pipeline didn’t break. It did exactly what you built it to do. When you typed “And the first-line treatment?”, it treated that as a completely isolated question with no context. It had no idea you were still talking about pneumonia.</p><p>The problem is simple but critical: your pipeline has amnesia. It takes a query in, returns results out, and forgets everything immediately. That’s fine for one-off searches. The moment someone has a real conversation, it falls apart.</p><p>Imagine this scenario: A junior doctor is on her morning ward round. She asks a question, gets a good answer, and asks a follow-up. The system asks her to clarify. She re-types everything. She asks another follow-up. The system asks again. After the third round of this, she closes the app and goes back to relying on her own memory instead.</p><p>You built a great search engine. But search engines don’t hold conversations. We need to fix that.</p><h3>The Three Problems We Need to Solve</h3><p>There are actually three separate failures happening here, and each one needs its own fix.</p><p><strong>Problem 1: Pronoun Blindness</strong></p><p>Your retriever sees tokens, not intent. When someone says “And what are its symptoms?” or “What about that condition?”, your system has no idea what “its” or “that” refers to. The query is incomplete before it even hits your vector database.</p><p><strong>Problem 2: In-Session Amnesia</strong></p><p>Even if we solve the pronoun problem using in-memory conversation history, that history vanishes the moment your server restarts. The doctor finishes her morning round, your server gets a routine restart at lunch, and her afternoon session starts completely blank.</p><p><strong>Problem 3: Cross-Session Blindness</strong></p><p>She comes back tomorrow, mid-way through a complex case, and types: “What were the distinguishing features we discussed yesterday?” Your system has no record of yesterday. Every session is completely isolated.</p><p>This is what we’re building today: a system that solves all three problems at once.</p><h3>What We’re Building: The Four-Node Pipeline</h3><p>Every query will pass through four decision points. Off-topic queries exit early without touching your vector database. Medical queries run the full pipeline, and the complete conversation state gets saved to PostgreSQL after every single turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3CIS0LMMTNUS-5jEChV-g.png" /></figure><blockquote>The beautiful part? That retrieval node is your exact hybrid_rag_query() function from Part 1. We&#39;re not replacing anything. We&#39;re building a memory layer on top of what you already have.</blockquote><h3>Step 1: Define Your Agent State</h3><p>Think of this as a clipboard that gets passed from hand to hand through each node. Every node can read from it and add to it.</p><pre>from typing import TypedDict, Annotated, List<br>from langchain_core.messages import BaseMessage<br>import operator<br><br>class AgentState(TypedDict):<br>    &quot;&quot;&quot;Shared state passed between every node in the graph.&quot;&quot;&quot;<br>    messages: Annotated[List[BaseMessage], operator.add]  <br>    # Full conversation history (messages accumulate with operator.add)<br>    <br>    original_query: str        # Exactly what the user typed<br>    optimized_query: str       # Resolved, self-contained version for Qdrant<br>    retrieved_context: str     # Chunks from hybrid_rag_query()<br>    final_answer: str          # The response shown to the user<br>    is_medical_query: bool     # Did this pass the medical check?<br>    error_message: str         # Details if something went wrong<br>    session_id: str            # Links to PostgreSQL checkpoint</pre><h4>Why This Design Matters</h4><p><strong>The messages field with operator.add: </strong>Without this reducer, LangGraph would completely overwrite the messages list every time a node returns a new value. A single node adding one message would erase all previous messages. The operator.add reducer tells LangGraph: &quot;Don&#39;t replace—append.&quot; History accumulates automatically, and no node has to manage it manually.</p><p><strong>Separate original_query and optimized_query: </strong>We keep these separate intentionally. original_query is what the user actually typed; it&#39;s what gets shown back to them and what the medical check evaluates. optimized_query is the rewritten version that goes to Qdrant. This way, users never see a rewritten question, while the retriever gets something it can actually use.</p><p><strong>session_id: </strong>This single ID connects everything to PostgreSQL. Same ID means same conversation. Different ID means a fresh start. That’s how we fix Problem 3.</p><h3>Step 2: Build the Medical Query Check Node</h3><p>Every query hits this node first. If someone asks about the weather or pastes random text, this stops it before we even touch Qdrant.</p><pre>from langchain_core.messages import SystemMessage, HumanMessage<br><br>def medical_query_check(state: AgentState) -&gt; AgentState:<br>    query = state[&quot;original_query&quot;]<br>    <br>    prompt = &quot;&quot;&quot;<br>    You are a query classifier for a Medical AI Assistant.<br>    Classify as MEDICAL if the query is about:<br>    - Medical conditions or diseases<br>    - Symptoms, diagnoses, or clinical findings<br>    - Treatments, medications, or procedures<br>    - Healthcare or public health topics<br>    <br>    Otherwise classify as NOT_MEDICAL.<br>    Respond with only: MEDICAL or NOT_MEDICAL<br>    &quot;&quot;&quot;<br>    <br>    response = llm.invoke([<br>        SystemMessage(content=prompt),<br>        HumanMessage(content=query)<br>    ])<br>    <br>    # Double-check to avoid false positives<br>    is_medical = (<br>        &quot;MEDICAL&quot; in response.content.upper() and<br>        &quot;NOT_MEDICAL&quot; not in response.content.upper()<br>    )<br>    <br>    return {<br>        &quot;is_medical_query&quot;: is_medical,<br>        &quot;error_message&quot;: (<br>            &quot;This question doesn&#39;t appear to be medical. &quot;<br>            &quot;Please ask about a symptom, condition, or treatment.&quot;<br>            if not is_medical<br>            else state.get(&quot;error_message&quot;, &quot;&quot;)<br>        )<br>    }</pre><p>This node acts as a gatekeeper. Non-medical queries are rejected immediately, saving compute and avoiding hallucinations. The double-check prevents false positives where the model might accidentally include “MEDICAL” in a “NOT_MEDICAL” response.</p><h3>Step 3: Build the Query Optimization Node</h3><p>This is the node that fixes Problem 1. It takes the last few messages and rewrites the current query into something your vector database can actually use.</p><pre>def query_optimization_node(state: AgentState) -&gt; AgentState:<br>    query = state[&quot;original_query&quot;]<br>    messages = state.get(&quot;messages&quot;, [])<br><br># Last 6 messages = three full back-and-forth exchanges<br>    conversation_context = &quot;\n&quot;.join([<br>        f&quot;{msg.type}: {msg.content}&quot;<br>        for msg in messages[-6:]<br>        if hasattr(msg, &#39;content&#39;)<br>    ])<br>    <br>    optimizer_prompt = f&quot;&quot;&quot;<br>    Rewrite the current query into a fully self-contained search string.<br>    Use the conversation history to add missing context.<br>    <br>    Examples:<br>    - &quot;What are its symptoms?&quot; + pneumonia context <br>      → &quot;What are the symptoms of pneumonia?&quot;<br>    <br>    - &quot;And the first-line treatment?&quot;<br>      → &quot;What is the first-line treatment for pneumonia?&quot;<br>    <br>    Rules:<br>    - Pull the topic from prior turns if the current query is a follow-up<br>    - Resolve pronouns (&quot;it&quot;, &quot;that&quot;, &quot;this&quot;)<br>    - Expand abbreviations and fix spelling<br>    - Do NOT add anything not implied by the conversation<br>    - Return ONLY the rewritten query<br>    <br>    Conversation history:<br>    {conversation_context}<br>    <br>    Current query: {query}<br>    Rewritten query:<br>    &quot;&quot;&quot;<br>    <br>    response = llm.invoke([<br>        SystemMessage(content=optimizer_prompt),<br>        HumanMessage(content=query)<br>    ])<br>    <br>    optimized = response.content.strip()<br>    <br>    return {<br>        &quot;optimized_query&quot;: optimized,<br>        &quot;messages&quot;: [SystemMessage(content=f&quot;Query optimized: {optimized}&quot;)]<br>    }</pre><h3>What Actually Happens Here</h3><p>Most query optimizers stop at simple pronoun replacement. But the real problem is deeper than that. It’s <strong>topic continuation</strong>.</p><p>When someone says “What are its symptoms?”, that’s not just a pronoun issue. The entire subject — pneumonia, elderly patients — needs to be carried forward from the previous turn. That’s exactly what this node does.</p><p><strong>See the transformation:</strong></p><p><strong>Turn 1 — Initial Question</strong></p><ul><li>You type: &quot;Tell me about pneumonia in elderly patients&quot;</li><li>Qdrant receives: &quot;What is pneumonia and how does it present in elderly patients?&quot;</li></ul><p><strong>Turn 2 — Follow-up with Pronoun</strong></p><ul><li>You type: &quot;What are its symptoms?&quot;</li><li>Qdrant receives: &quot;What are the symptoms of pneumonia in elderly patients?&quot;</li><li>What changed: “its” becomes “pneumonia”, and the age group is preserved</li></ul><p><strong>Turn 3 — Short Follow-up</strong></p><ul><li>You type: &quot;And the first-line treatment?&quot;</li><li>Qdrant receives: &quot;What is the first-line treatment for pneumonia in elderly patients?&quot;</li><li>What changed: The system remembers both the condition and the age group</li></ul><p><strong>Turn 4 — Complex Follow-up</strong></p><ul><li>You type: &quot;What if they are penicillin-allergic?&quot;</li><li>Qdrant receives: &quot;What is the first-line treatment for pneumonia in patients who are penicillin-allergic?&quot;</li><li>What changed: “they” becomes “patients”, and the new constraint is integrated with the existing context</li></ul><p>The key insight is that each query becomes fully self-contained and independent. The vector database never has to guess what you’re talking about. It receives complete, unambiguous search terms every single time.</p><h3>Step 4: Build the Retrieval Node</h3><p>This is your bridge back to Part 1. Nothing complex here — we take the optimized query and hand it to your hybrid_rag_query() function.</p><pre>def retrieval_node(state: AgentState) -&gt; AgentState:<br>    query = state[&quot;optimized_query&quot;]<br><br># Your function from Part 1: dense + sparse + reranking<br>    context, ranked_results = hybrid_rag_query(<br>        query,<br>        top_k=16,        # Cast a wide net for recall<br>        rerank_top_k=8   # Then narrow down for precision<br>    )<br>    <br>    return {<br>        &quot;retrieved_context&quot;: context<br>    </pre><p>The 16-to-8 pipeline is unchanged from Part 1. Retrieve broadly for recall, rerank tightly for precision. Nothing changes just because we added memory on top.</p><h3>Step 5: Build the Answer Generation Node</h3><p>The last node pulls everything together. This is where conversation history actually matters.</p><pre>def answer_generation_node(state: AgentState) -&gt; AgentState:<br>    query = state[&quot;optimized_query&quot;]<br>    context = state[&quot;retrieved_context&quot;]<br>    messages = state.get(&quot;messages&quot;, [])<br><br># Last 10 messages for context<br>    conversation_history = &quot;\n&quot;.join([<br>        f&quot;{msg.type}: {msg.content}&quot;<br>        for msg in messages[-10:]<br>        if hasattr(msg, &#39;content&#39;)<br>    ])<br>    <br>    system_prompt = &quot;&quot;&quot;<br>    You are a Medical AI Assistant with access to a curated clinical knowledge base.<br>    <br>    RULES:<br>    1. Answer ONLY using information in the CONTEXT section below.<br>    2. Use CONVERSATION HISTORY to understand follow-ups and maintain continuity.<br>    3. Never use external knowledge or make inferences beyond what context supports.<br>    4. If the context doesn&#39;t contain enough information to answer, say so explicitly.<br>    5. Be precise. Avoid hedging when the context is clear.<br>    <br>    &lt;CONVERSATION_HISTORY&gt;<br>    {history}<br>    &lt;/CONVERSATION_HISTORY&gt;<br>    <br>    &lt;CONTEXT&gt;<br>    {context}<br>    &lt;/CONTEXT&gt;<br>    &quot;&quot;&quot;<br>    <br>    response = llm.invoke([<br>        SystemMessage(content=system_prompt.format(<br>            history=conversation_history,<br>            context=context<br>        )),<br>        HumanMessage(content=query)<br>    ])<br>    <br>    return {<br>        &quot;messages&quot;: [<br>            HumanMessage(content=query),<br>            SystemMessage(content=response.content)<br>        ],<br>        &quot;final_answer&quot;: response.content<br>    }</pre><p><strong>Notice Rule 4:</strong> “If the context doesn’t contain enough information to answer, say so explicitly.” This is non-negotiable. A confident wrong answer is harder to catch than an honest admission of uncertainty. Your credibility depends on it.</p><h3>Step 6: Wire It All Together</h3><p>Now we connect these four nodes into a graph that routes queries correctly and terminates early when something is off-topic.</p><p><strong>Register the nodes:</strong></p><pre>from langgraph.graph import StateGraph, END<br><br>def create_medical_rag_graph():<br>    workflow = StateGraph(AgentState)<br>    <br>    # Add the four nodes<br>    workflow.add_node(&quot;medical_query_check&quot;, medical_query_check)<br>    workflow.add_node(&quot;query_optimization&quot;, query_optimization_node)<br>    workflow.add_node(&quot;retrieval&quot;, retrieval_node)<br>    workflow.add_node(&quot;answer_generation&quot;, answer_generation_node)</pre><p><strong>Define the routing logic:</strong></p><pre>def route_query(state: AgentState) -&gt; str:<br>    &quot;&quot;&quot;Route based on whether the query is medical or not.&quot;&quot;&quot;<br>    return &quot;query_optimization&quot; if state[&quot;is_medical_query&quot;] else &quot;end&quot;</pre><p><strong>Connect the edges:</strong></p><pre># Start at the medical check<br>    workflow.set_entry_point(&quot;medical_query_check&quot;)<br>    <br>    # Conditional edge: medical queries proceed, others exit<br>    workflow.add_conditional_edges(&quot;medical_query_check&quot;, route_query, {<br>        &quot;query_optimization&quot;: &quot;query_optimization&quot;,<br>        &quot;end&quot;: END<br>    })<br>    <br>    # The rest flow in sequence<br>    workflow.add_edge(&quot;query_optimization&quot;, &quot;retrieval&quot;)<br>    workflow.add_edge(&quot;retrieval&quot;, &quot;answer_generation&quot;)<br>    workflow.add_edge(&quot;answer_generation&quot;, END)</pre><p><strong>Add PostgreSQL checkpointing:</strong></p><pre># Compile with checkpointing enabled<br>return workflow.compile(checkpointer=checkpointer)<br># Create your graph<br>rag_graph = create_medical_rag_graph()</pre><p>This is the critical step that fixes Problems 2 and 3. After every turn, the full AgentState, including the messages list, gets saved to PostgreSQL under the current session_id. Next time that session sends a query, LangGraph loads that checkpoint before any node runs.</p><p><strong>Test it yourself: </strong>start a conversation, ask a few follow-ups, restart your Python process completely, then send another follow-up with the same session_id. The system will know exactly where you left off.</p><h3>Key Takeaways</h3><p>You’ve now built a conversational medical AI that actually understands context. Here’s what we accomplished:</p><ul><li><strong>Problem 1 (Pronoun Blindness):</strong> Solved with the Query Optimization node. Incomplete queries become complete.</li><li><strong>Problem 2 (In-Session Amnesia):</strong> Solved with conversation history in AgentState. Server restarts don’t erase context.</li><li><strong>Problem 3 (Cross-Session Blindness):</strong> Solved with PostgreSQL checkpointing. Sessions persist across days.</li></ul><p>Your Part 1 retrieval pipeline stays completely unchanged. The system is modular — you can add or remove nodes as needed. PostgreSQL persists everything — no conversation is lost.</p><p>The journey from a stateless search engine to a stateful conversational agent is complete. Now let’s make it accessible to real users.</p><h3>About VannGuard AI</h3><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c709eac3123" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/building-a-chat-agent-with-langgraph-part-2-your-rag-pipeline-can-retrieve-but-can-it-remember-3c709eac3123">Building a Chat Agent with LangGraph (Part 2): Your RAG Pipeline Can Retrieve, But Can It Remember?</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chat Agent with LangGraph: A Complete Guide (part 1 of 2)]]></title>
            <link>https://medium.com/vannguardai/building-a-rag-ai-agent-with-langgraph-a-complete-guide-0432d0d1344c?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/0432d0d1344c</guid>
            <dc:creator><![CDATA[Zuhair Zaidi]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 11:18:17 GMT</pubDate>
            <atom:updated>2026-03-27T09:00:52.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DokCHOk3r52fquMe9z9v9Q.jpeg" /></figure><h3>Introduction</h3><p>This guide builds a production-ready medical diagnosis assistant that combines hybrid retrieval, conversation memory, and intelligent orchestration. Unlike basic RAG systems that simply retrieve documents, our system maintains context, validates queries, and optimizes searches based on conversation history.</p><p><strong>What you’ll build:</strong></p><ul><li>Medical diagnosis assistant with hybrid search (semantic + keyword matching)</li><li>Smart data pipeline with hierarchical chunking</li><li>Qdrant vector database with dual embeddings</li><li>Foundation for stateful LangGraph agent <strong>(Part 2)</strong></li></ul><p><strong>Part 1</strong> covers configuration, data preparation, and retrieval.</p><p><strong>Part 2</strong> adds the LangGraph agent, API, frontend, and Docker deployment.</p><h3>Why This Architecture?</h3><p><strong>Limitations of Traditional RAG Systems:</strong></p><ul><li>Vector search misses exact keywords</li><li>No conversation memory</li><li>No safety validation</li><li>Opaque decisions</li></ul><p><strong>Our Solution:</strong></p><ul><li><strong>Hybrid search</strong>: Combines semantic (dense) and keyword (sparse) retrieval, then uses cross-encoder reranking for precision</li><li><strong>Multi-stage pipeline</strong>: Validates → optimizes → retrieves → generates with clear decision points</li><li><strong>Stateful conversations</strong>: PostgreSQL checkpointing maintains context</li><li><strong>Transparent workflow</strong>: Each step is visible and debuggable</li></ul><h3>Project Structure</h3><pre>medical-rag-agent/<br>├── backend/<br>|   ├── __init__.py<br>│   ├── app/<br>│   │   ├── __init__.py<br>|   |   ├── prepare_data.py<br>│   |   ├── Diagnosis_flowchart/<br>│   │   ├── main.py<br>│   │   ├── graph.py<br>│   │   ├── nodes.py<br>│   │   ├── rag.py<br>|   |   ├── config.yaml<br>│   │   └── config.py<br>│   ├── requirements.txt<br>│   └── Dockerfile<br>├── frontend/<br>|   ├── __init__.py<br>│   ├── app.py<br>│   ├── requirements.txt<br>│   └── Dockerfile<br>├── docker-compose.yml<br>├── .env<br>└── README.md</pre><h3>Configuration</h3><h4><strong>config.yaml</strong></h4><p>This file holds the main service URLs and the settings for your vector collection.</p><pre>services:<br>  tei_url: http://localhost:8080/embed<br>  qdrant_url: http://localhost:6333<br>  database_url: postgresql://postgres:postgres@postgres:5432/checkpoints<br>collection:<br>  name: medical_db<br>  dense_vector_size: 384</pre><h4><strong>.env</strong></h4><p>This is where you securely store your API keys:</p><pre>GROQ_API_KEY=&lt;YOUR_GROQ_API&gt;</pre><h4>config.py</h4><p>Here we load everything from the config files and initialize the global services our app will use.</p><pre>import os<br>from langgraph.checkpoint.postgres import PostgresSaver<br>from dotenv import load_dotenv<br>from langchain_groq import ChatGroq<br>import yaml <br>from psycopg_pool import ConnectionPool<br><br>load_dotenv()<br><br>try:<br>    with open(&quot;config.yaml&quot;, &quot;r&quot;) as f:<br>        config = yaml.safe_load(f)<br>except FileNotFoundError:<br>    print(&quot;Error: config.yaml not found. Using hardcoded defaults.&quot;)<br>    config = {}<br><br>TEI_URL = config.get(&quot;services&quot;, {}).get(&quot;tei_url&quot;, &quot;http://localhost:8080/embed&quot;)<br>QDRANT_URL = config.get(&quot;services&quot;, {}).get(&quot;qdrant_url&quot;, &quot;http://localhost:6333&quot;)<br>DB_URI = config.get(&quot;services&quot;, {}).get(&quot;database_url&quot;, &quot;postgresql://postgres:postgres@postgres:5432/checkpoints&quot;)<br>COLLECTION_NAME = config.get(&quot;collection&quot;, {}).get(&quot;name&quot;, &quot;medical_rag_db&quot;)<br>DENSE_VECTOR_SIZE = config.get(&quot;collection&quot;, {}).get(&quot;dense_vector_size&quot;, 384)<br><br>pool = ConnectionPool(conninfo=DB_URI, max_size=20, kwargs={&quot;autocommit&quot;: True})<br>checkpointer = PostgresSaver(pool)<br><br>llm = ChatGroq(<br>    model=&quot;llama-3.3-70b-versatile&quot;,  <br>    temperature=0,<br>    max_tokens=None,<br>    timeout=None,<br>    max_retries=2,<br>)</pre><h3>Part 1: Data Preparation &amp; Chunking</h3><p>High-quality data preparation is essential for a RAG system. This guide uses a medical diagnosis flowchart (<a href="https://physionet.org/content/mimic-iv-ext-direct/1.0.0/">mimic-iv-ext-direct-1.0.0</a>), which requires proper credentialing for access.</p><h4>1.1 Sample Medical Data</h4><pre>{<br>  &quot;diagnostic&quot;: {<br>    &quot;Suspected Pneumonia&quot;: {<br>      &quot;Pneumonia&quot;: {<br>        &quot;Bacterial Pneumonia&quot;: {},<br>        &quot;Viral Pneumonia&quot;: {}<br>      }<br>    }<br>  },<br>  &quot;knowledge&quot;: {<br>    &quot;Pneumonia&quot;: {<br>      &quot;description&quot;: &quot;Radiological examination: Chest X-rays...&quot;,<br>      &quot;tests&quot;: [&quot;Microbiological tests...&quot;, &quot;CBC...&quot;]<br>    }<br>  }<br>}</pre><h4>1.2 Smart Chunking Strategy</h4><p>Traditional chunking often breaks semantic meaning. We implement hierarchical markdown chunking that preserves document structure, maintains heading context, respects 240-token limits, and splits at natural boundaries.</p><h4>1.3 Load all JSON files from directory</h4><pre>parent_directory = &quot;Diagnosis_flowchart&quot;  <br><br>def load_json_files(folder_path):<br>    json_data = []<br>    for filename in os.listdir(folder_path):<br>        if filename.endswith(&quot;.json&quot;):<br>            with open(os.path.join(folder_path, filename), &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>                data = json.load(f)<br>                json_data.append(data)<br>    return json_data<br><br>data_list = load_json_files(parent_directory)</pre><h4><strong>1.4 Initial JSON chunking with RecursiveJsonSplitter.</strong></h4><pre>json_splitter = RecursiveJsonSplitter(max_chunk_size=240)<br>docs = json_splitter.create_documents(texts=data_list)</pre><h4>1.5 Convert JSON chunks to markdown</h4><p>The goal of this function is to <strong>convert JSON data into hierarchical Markdown</strong> while preserving the structure.</p><pre>def chunk_to_markdown(json_text, level=1):<br>    &quot;&quot;&quot;<br>    Convert a JSON chunk (string) into hierarchical Markdown.<br>    &quot;&quot;&quot;<br>    try:<br>        data = json.loads(json_text)<br>    except json.JSONDecodeError:<br>        return json_text<br><br>    def recursive_to_md(data, lvl):<br>        md = &quot;&quot;<br>        if isinstance(data, dict):<br>            for key, value in data.items():<br>                md += f&quot;{&#39;#&#39; * lvl} {key}\n\n&quot;<br>                md += recursive_to_md(value, lvl + 1) + &quot;\n&quot;<br>        elif isinstance(data, list):<br>            for i, item in enumerate(data, 1):<br>                md += f&quot;{&#39;#&#39; * lvl} Item {i}\n\n&quot;<br>                md += recursive_to_md(item, lvl + 1) + &quot;\n&quot;<br>        else:<br>            md += f&quot;{data}\n&quot;<br>        return md.strip()<br><br>    return recursive_to_md(data, level)<br><br>markdown_doc = [chunk_to_markdown(doc.page_content) for doc in docs]</pre><h4>1.6 Chunk markdown to limit each chunk to max tokens</h4><p>The main goal of this code is to split large Markdown documents into smaller chunks based on token limits while preserving the semantic structure.</p><p><strong>1.6.1 Token Counting Function</strong></p><p>LLMs have a maximum token limit per input. This function calculates the number of tokens in a text, allowing us to split documents into chunks that fit within the model’s token limit.</p><pre>encoding = tiktoken.encoding_for_model(&quot;gpt-4&quot;)<br><br>def count_tokens(text):<br>    &quot;&quot;&quot;Counts the number of tokens in a given text using the model&#39;s tokenizer.&quot;&quot;&quot;<br>    return len(encoding.encode(text))</pre><p><strong>1.6.2 Parse Markdown into a Tree</strong></p><p>This function converts the markdown into a tree structure based on headings (#, ##, ###), keeping subheadings nested under their parent headings. It preserves the document’s semantic hierarchy, which is crucial for context-aware retrieval in RAG pipelines.</p><pre>def parse_markdown_tree(md_text):<br>    lines = md_text.split(&quot;\n&quot;)<br>    root = {&quot;level&quot;: 0, &quot;heading&quot;: None, &quot;content&quot;: [], &quot;children&quot;: []}<br>    stack = [root]<br><br>    for line in lines:<br>        m = re.match(r&#39;^(#+)\s+(.*)&#39;, line)<br>        if m:<br>            level = len(m.group(1))<br>            heading = m.group(2)<br>            while stack and stack[-1][&#39;level&#39;] &gt;= level:<br>                stack.pop()<br>            node = {&quot;level&quot;: level, &quot;heading&quot;: heading, &quot;content&quot;: [], &quot;children&quot;: []}<br>            stack[-1][&#39;children&#39;].append(node)<br>            stack.append(node)<br>        else:<br>            stack[-1][&#39;content&#39;].append(line)<br>    return root</pre><p><strong>1.6.3 Build Heading Context</strong></p><p>For RAG pipelines, each chunk should include its hierarchical context so the model understands where this text fits in the document. This ensures semantic coherence when retrieving or answering queries.</p><pre>def get_heading_context(node, parent_headings=[]):<br>    &quot;&quot;&quot;Build the heading context that will be prepended to chunks.&quot;&quot;&quot;<br>    headings = [h for h in parent_headings if h]<br>    if node[&#39;heading&#39;]:<br>        headings.append(node[&#39;heading&#39;])<br>    return &quot;\n&quot;.join([&quot;#&quot; * (i+1) + &quot; &quot; + h for i, h in enumerate(headings)])</pre><p><strong>1.6.4 Chunk Node (Bottom-Up Approach)</strong></p><p>This function performs semantic-preserving chunking by splitting at paragraphs first and then at sentences when needed. It keeps each chunk within the max-token limit and includes all relevant hierarchical headings in every chunk. Its bottom-up recursion ensures all child nodes are processed before their parent content, maintaining coherent context for retrieval and LLM input.</p><pre>def chunk_node_bottom_up(node, max_tokens=240, parent_headings=[]):<br>    chunks = []<br><br>    for child in node[&#39;children&#39;]:<br>        child_chunks = chunk_node_bottom_up(<br>            child,<br>            max_tokens=max_tokens,<br>            parent_headings=parent_headings + ([node[&#39;heading&#39;]] if node[&#39;heading&#39;] else [])<br>        )<br>        chunks.extend(child_chunks)<br><br>    content_text = &quot;\n\n&quot;.join(node[&#39;content&#39;]).strip()<br>    if not content_text:<br>        return chunks<br><br>    heading_context = get_heading_context(node, parent_headings)<br>    heading_tokens = count_tokens(heading_context) if heading_context else 0<br><br>    paragraphs = [p for p in content_text.split(&quot;\n\n&quot;) if p.strip()]<br>    current_chunk = []<br>    current_tokens = heading_tokens <br><br>    for para in paragraphs:<br>        para_tokens = count_tokens(para)<br><br>        if current_tokens + para_tokens &gt; max_tokens and current_chunk:<br>            <br>            chunk_content = &quot;\n\n&quot;.join(current_chunk)<br>            full_chunk = f&quot;{heading_context}\n\n{chunk_content}&quot; if heading_context else chunk_content<br>            chunks.append(full_chunk.strip())<br>            current_chunk = []<br>            current_tokens = heading_tokens<br>        <br>        if heading_tokens + para_tokens &gt; max_tokens:<br>            sentences = re.split(r&#39;(?&lt;=[.!?])\s+&#39;, para)<br>            for sent in sentences:<br>                sent_tokens = count_tokens(sent)<br>                if current_tokens + sent_tokens &gt; max_tokens and current_chunk:<br>                    chunk_content = &quot;\n\n&quot;.join(current_chunk)<br>                    full_chunk = f&quot;{heading_context}\n\n{chunk_content}&quot; if heading_context else chunk_content<br>                    chunks.append(full_chunk.strip())<br>                    current_chunk = [sent]<br>                    current_tokens = heading_tokens + sent_tokens<br>                else:<br>                    current_chunk.append(sent)<br>                    current_tokens += sent_tokens<br>        else:<br>            current_chunk.append(para)<br>            current_tokens += para_tokens<br><br>    if current_chunk:<br>        chunk_content = &quot;\n\n&quot;.join(current_chunk)<br>        full_chunk = f&quot;{heading_context}\n\n{chunk_content}&quot; if heading_context else chunk_content<br>        chunks.append(full_chunk.strip())<br><br>    return chunks</pre><p><strong>1.6.5 Chunk Full Markdown Document</strong></p><p>This is the high-level function to convert a markdown string into a list of token-compliant chunks, ready for LLM processing or storage in a vector DB.</p><pre>def chunk_markdown_document(md_text, max_tokens=240):<br>    tree = parse_markdown_tree(md_text)<br>    return chunk_node_bottom_up(tree, max_tokens=max_tokens)</pre><p><strong>1.6.6 Process Multiple Markdown Documents</strong></p><p>This function iterates through all markdown documents, keeping any document under the token limit as a single chunk and otherwise applying the existing chunking logic. All resulting chunks are then flattened into one list for ingestion into the RAG pipeline.</p><pre>markdown_chunks_array = []<br><br>for doc in markdown_doc:<br>    text = str(doc)<br>    tokens = count_tokens(text)<br>    <br>    if tokens &lt;= 240:<br>        markdown_chunks_array.append([text])<br>    else:<br>        chunks = chunk_markdown_document(text, max_tokens=240)<br>        markdown_chunks_array.append(chunks)<br><br>markdown_documents = [chunk for doc_chunks in markdown_chunks_array for chunk in doc_chunks]</pre><h3>Part 2: Hybrid RAG Pipeline</h3><h4>Why Hybrid Search?</h4><p>Dense embeddings capture semantic meaning, while sparse embeddings (SPLADE) capture exact keyword matches. Combining both gives us the best of both worlds.</p><h4>2.1 System Initialization Setup</h4><p>Initializes the Qdrant client along with sparse and dense embedding models and a reranker, preparing the retrieval pipeline for indexing and query processing.</p><pre>from qdrant_client import QdrantClient, models<br>from fastembed import SparseTextEmbedding <br>from sentence_transformers import CrossEncoder<br>from app.config import QDRANT_URL, TEI_URL, COLLECTION_NAME, DENSE_VECTOR_SIZE<br><br>client = QdrantClient(url=QDRANT_URL)<br>sparse_model = SparseTextEmbedding(model_name=&quot;prithivida/Splade_PP_en_v1&quot;, threads=4)<br>reranker = CrossEncoder(&#39;cross-encoder/ms-marco-MiniLM-L-6-v2&#39;)</pre><h4>2.2 Vector Database Setup (Qdrant)</h4><p>Once we have our medical documents chunked and converted into markdown, the next step is to prepare the vector database so we can perform fast, semantically rich searches. For this, we use <strong>Qdrant</strong>, a vector database that can store and query embeddings efficiently.</p><p><strong>2.2.1 Set Up Connection:</strong><br>Initializes a Qdrant collection with dense vectors for semantic search and sparse vectors for exact keyword matches. Enables hybrid retrieval.</p><pre><br>def setup_collection():<br>    &quot;&quot;&quot;Initialize Qdrant with hybrid vectors&quot;&quot;&quot;<br>    client.create_collection(<br>        collection_name=COLLECTION_NAME,<br>        vectors_config={<br>            &quot;dense-vector&quot;: models.VectorParams(<br>                size=DENSE_VECTOR_SIZE,  <br>                distance=models.Distance.COSINE<br>            )<br>        },<br>        sparse_vectors_config={<br>            &quot;sparse-vector&quot;: models.SparseVectorParams(<br>                index=models.SparseIndexParams(on_disk=False)<br>            )<br>        }<br>    )</pre><p><strong>2.2.2 Get Dense Embedding:</strong></p><p>Sends text to the TEI service and returns a normalized dense vector for semantic similarity.</p><pre>def get_dense_embedding(text: str) -&gt; List[float]:<br>    response = requests.post(<br>        TEI_URL, <br>        json={&quot;inputs&quot;: [text], &quot;normalize&quot;: True},<br>        timeout=2<br>    )<br>    response.raise_for_status() <br>    return response.json()[0]</pre><p><strong>2.2.3 Delete Collection:</strong></p><p>If the collection already exists, it will be deleted first to ensure a clean setup with no duplication.</p><pre>def delete_collection():<br><br>    try:<br>        if client.collection_exists(collection_name=COLLECTION_NAME):<br>            client.delete_collection(collection_name=COLLECTION_NAME)<br>            print(f&quot;Collection &#39;{COLLECTION_NAME}&#39; deleted successfully.&quot;)<br>        else:<br>            print(f&quot;Collection &#39;{COLLECTION_NAME}&#39; does not exist. Skipping deletion.&quot;)<br>    except Exception as e:<br>        print(f&quot;An error occurred while trying to delete collection &#39;{COLLECTION_NAME}&#39;: {e}&quot;)</pre><p><strong>2.2.4 Wait for TEI</strong></p><p>Waits until the TEI embedding service is ready, preventing failed embedding requests during ingestion.</p><pre>def wait_for_tei(timeout=102000):<br>    print(&quot;Waiting for TEI model to load...&quot;)<br><br>    start = time.time()<br>    while True:<br>        try:<br>            r = requests.post(<br>                TEI_URL,<br>                json={&quot;inputs&quot;: [&quot;hello&quot;], &quot;normalize&quot;: True},<br>                timeout=2<br>            )<br>            if r.status_code == 200:<br>                print(&quot;✔ TEI model loaded and ready.&quot;)<br>                return<br>        except Exception:<br>            pass<br><br>        if time.time() - start &gt; timeout:<br>            raise TimeoutError(&quot;TEI model did not start within the expected time.&quot;)<br><br>        print(&quot;… still loading model, waiting 3 seconds...&quot;)<br>        time.sleep(3)</pre><h4>2.3 Embedding &amp; Ingestion</h4><p>After setting up Qdrant, the next step is to <strong>populate the database with our processed documents</strong>, so they can later be retrieved efficiently. The key idea here is <strong>dual embeddings, </strong>each document chunk is represented both semantically and with exact keyword mapping:</p><pre>def ingest_documents(markdown_documents: List[str]):<br>    &quot;&quot;&quot;Ingest documents with dual embeddings&quot;&quot;&quot;<br>    points_to_upload = []<br>    <br>    for i, doc in enumerate(markdown_documents):<br>        # Dense embedding via TEI<br>        dense_vector = get_dense_embedding(doc)<br>        <br>        # Sparse embedding via SPLADE<br>        sparse_vector_output = list(sparse_model.query_embed(doc))[0]<br>        sparse_vector = models.SparseVector(<br>            indices=sparse_vector_output.indices.tolist(),<br>            values=sparse_vector_output.values.tolist()<br>        )<br>        <br>        points_to_upload.append(models.PointStruct(<br>            id=str(uuid.uuid4()),<br>            vector={<br>                &quot;dense-vector&quot;: dense_vector,<br>                &quot;sparse-vector&quot;: sparse_vector<br>            },<br>            payload={&quot;text&quot;: doc, &quot;chunk_id&quot;: i}<br>        ))<br>    <br>    client.upsert(collection_name=COLLECTION_NAME, points=points_to_upload)?</pre><h4>2.4 Retrieval with Reranking</h4><p>Once our documents are embedded and ingested into Qdrant, the next critical step is <strong>retrieving the most relevant information</strong> in response to a user query. This is where the hybrid_rag_query function comes into play, combining <strong>semantic understanding</strong> with <strong>keyword precision</strong> and finally applying a <strong>reranking step</strong> for maximum accuracy.</p><pre>def hybrid_rag_query(query_text: str, top_k: int = 16, rerank_top_k: int = 8):<br>    &quot;&quot;&quot;Hybrid retrieval + cross-encoder reranking&quot;&quot;&quot;<br>    <br>    # Get both dense and sparse query vectors<br>    query_dense = get_dense_embedding(query_text)<br>    query_sparse_gen = list(sparse_model.embed(documents=[query_text]))[0]<br>    query_sparse = models.SparseVector(<br>        indices=query_sparse_gen.indices.tolist(),<br>        values=query_sparse_gen.values.tolist()<br>    )<br>    <br>    # Hybrid search with RRF fusion<br>    search_results = client.query_points(<br>        collection_name=COLLECTION_NAME,<br>        prefetch=[<br>            models.Prefetch(query=query_dense, using=&quot;dense-vector&quot;, limit=top_k),<br>            models.Prefetch(query=query_sparse, using=&quot;sparse-vector&quot;, limit=top_k),<br>        ],<br>        query=models.RrfQuery(rrf=models.Rrf(k=60)),<br>        limit=top_k<br>    ).points<br>    <br>    # Rerank with cross-encoder<br>    doc_texts = [hit.payload[&#39;text&#39;] for hit in search_results]<br>    cross_encoder_inputs = [[query_text, doc] for doc in doc_texts]<br>    scores = reranker.predict(cross_encoder_inputs)<br>    <br>    # Sort by cross-encoder scores<br>    ranked_results = sorted(<br>        [{&quot;text&quot;: hit.payload[&#39;text&#39;], &quot;score&quot;: scores[i]} <br>         for i, hit in enumerate(search_results)],<br>        key=lambda x: x[&quot;score&quot;],<br>        reverse=True<br>    )<br>    <br>    final_docs = [res[&quot;text&quot;] for res in ranked_results[:rerank_top_k]]<br>    context_str = &quot;\n\n---\n\n&quot;.join(final_docs)<br>    <br>    return context_str, ranked_results[:rerank_top_k]</pre><h4>2.5 Ingestion Pipeline</h4><p>The ingestion pipeline clears any existing collection, rebuilds a fresh hybrid-search Qdrant collection, waits for the TEI embedding service to be ready, and then embeds and uploads all markdown chunks. This guarantees a clean, consistent, and fully indexed dataset every time it runs. Once completed, all documents are properly embedded and ready for efficient RAG retrieval.</p><pre>def ingestion_pipeline():<br>    try:<br>        print(&quot;Deleting existing collection...&quot;)<br>        delete_collection()<br><br>        print(&quot;Setting up new collection...&quot;)<br>        setup_collection()<br><br>        print(&quot;Waiting for TEI model to be ready...&quot;)<br>        wait_for_tei()<br><br>        print(f&quot;Ingesting {len(markdown_documents)} markdown documents...&quot;)<br>        ingest_documents(markdown_documents)<br><br>        print(&quot;Ingestion pipeline completed successfully!&quot;)<br>    except Exception as e:<br>        print(f&quot;Ingestion pipeline failed: {e}&quot;)<br>        raise</pre><h3>What We’ve Accomplished</h3><p>We have successfully built the foundation of a production-ready medical RAG system, featuring:</p><ul><li>Hierarchical markdown chunking that preserves context</li><li>Hybrid dense-and-sparse embeddings for robust semantic and keyword search</li><li>Cross-encoder reranker for precision retrieval</li><li>A fully configured Qdrant vector database</li></ul><p>The automated ingestion pipeline ensures that all documents are processed and transformed into searchable chunks, ready for RAG queries.</p><h4>What’s Next in Part 2?</h4><p>Part 2 adds the <strong>“brain”</strong> to retrieval engine. The system will gain:</p><ul><li>Memory via PostgreSQL checkpointing</li><li>Safety checks with guardrails</li><li>Contextual query optimization</li><li>Intelligent routing through multi-step LangGraph workflows</li></ul><p>Additionally, Part 2 will include:</p><ul><li>A <strong>user interface</strong> served through FastAPI and Streamlit</li><li><strong>Docker deployment support</strong> for portability</li></ul><blockquote><strong>MEDICAL DISCLAIMER</strong>: This project is for <strong>educational and research purposes only</strong>. It is NOT a substitute for professional medical advice, diagnosis, or treatment. The AI system may produce inaccurate, incomplete, or misleading information. Always seek the advice of qualified healthcare professionals for medical concerns. Never disregard professional medical advice or delay seeking it because of information from this system.</blockquote><p><strong>About VannGuard AI</strong></p><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><p><strong>#AI #MachineLearning #LangChain #LangGraph #RAG #VectorDatabase #Docker #FastAPI #Streamlit #PostgreSQL #NLP #Chatbot #Python</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0432d0d1344c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/building-a-rag-ai-agent-with-langgraph-a-complete-guide-0432d0d1344c">Building a Chat Agent with LangGraph: A Complete Guide (part 1 of 2)</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web AI Agent from Scratch]]></title>
            <link>https://medium.com/vannguardai/building-web-ai-agent-from-scratch-a66d245749a5?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/a66d245749a5</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 10:15:44 GMT</pubDate>
            <atom:updated>2026-01-12T10:15:43.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*h4Y8sfUfjVhtsfgLnPcU6Q.png" /></figure><h3>Introduction</h3><p>Building a web AI agent from scratch is a hot research topic. While there are many open-source implementations like Browser-Use and closed-source tools like OpenAI’s Web Browsing Tool and Claude Web Search, understanding the basic implementation provides a crucial foundation. This knowledge is not just about replicating what’s already out there; it’s about enabling you to customize, debug, and innovate on your own terms.</p><h3>Pipeline</h3><p>The pipeline is composed of the DOM service, the browser service, the controller service, and the agent service. The complete workflow of the agent is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9yM2cTtMRPYloyo5" /><figcaption>Pipeline for Web AI agent</figcaption></figure><p>Let’s start exploring the agent with the most fundamental part: the DOM Service.</p><h3>DOM Service</h3><p>The <strong>DOM Service</strong> handles two key tasks:</p><ol><li><strong>Extracting Elements</strong>: It pulls all the interactive elements — like buttons, text fields, and links — from the <strong>HTML page source</strong>. This is the most critical task, as the HTML page source is very large, and we have to prune it effectively to extract only the relevant interactive elements. We use BeautifulSoup and JavaScript code for this extraction.</li><li><strong>Creating Mappings</strong>: It then creates <strong>XPath mappings</strong> for each of these elements. This mapping acts as a unique address, allowing a <strong>driver </strong>to easily find and interact with the elements later. (XPath is preferred for its precision in locating elements amid dynamic web changes.)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NipU2Tu7B8cNswTRsT3PyQ.png" /></figure><h3>Browser Service</h3><p>Next, we programmatically create a browser instance that we can use to execute different actions, such as Google searches, navigating to a URL, clicking elements, inputting text, and scrolling. It uses the <strong>Selenium </strong>driver to interact with an actual browser. For every new action, simply add the logic inside the <strong><em>BrowserService </em></strong>class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*jNUgPTDfM9DBH1e9Ns9alA.png" /></figure><h3>Controller Service</h3><p>The Controller service provides an execution layer on top of the browser service. It takes actions from the <strong>agent </strong>and executes them on the browser using the browser service.</p><p>Every new action that can be executed on the browser by the agent is defined in the <strong><em>ControllerActions </em></strong>Pydantic class.</p><pre>class ControllerActions(BaseModel):<br>    search_google: Optional[SearchGoogleControllerAction] = None<br>    go_to_url: Optional[GoToUrlControllerAction] = None<br>    nothing: Optional[Literal[True]] = None<br>    go_back: Optional[Literal[True]] = None<br>    done: Optional[DoneControllerAction] = None<br>    click_element: Optional[ClickElementControllerAction] = None<br>    input_text: Optional[InputTextControllerAction] = None<br>    scroll_down: Optional[Literal[True]] = None<br>    scroll_up: Optional[Literal[True]] = None<br><br>    @staticmethod<br>    def description() -&gt; str:<br>     return &quot;&quot;&quot;<br>- Search Google with a query<br>  Example: {&quot;search_google&quot;: {&quot;query&quot;: &quot;weather today&quot;}}<br>- Navigate directly to a URL<br>  Example: {&quot;go_to_url&quot;: {&quot;url&quot;: &quot;https://abc.com&quot;}}<br>- Do nothing/wait<br>  Example: {&quot;nothing&quot;: true}<br>- Go back to previous page<br>  Example: {&quot;go_back&quot;: true}<br>- Mark entire task as complete<br>  Example: {&quot;done&quot;: {&quot;text&quot;: &quot;This is the requested result of the task...&quot;}}<br>- Click an element by its ID<br>  Example: {&quot;click_element&quot;: {&quot;id&quot;: 1}}<br>- Input text into an element by its ID<br>  Example: {&quot;input_text&quot;: {&quot;id&quot;: 1, &quot;text&quot;: &quot;Hello world&quot;}}<br>- Scroll down<br>  Example: {&quot;scroll_down&quot;: true}<br>- Scroll up<br>  Example: {&quot;scroll_up&quot;: true}<br>&quot;&quot;&quot;</pre><h3>Agent Service</h3><p>The Agent service decides which action to take next, given the current browser state. It inputs a <strong>prompt </strong>containing the browser state and returns the appropriate action. This is where the AI’s decision-making shines, adapting based on real-time page data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*qqZxfDAc4-WTQ0Yc" /></figure><h3>Execution Example</h3><p>Let’s see it in action: “<strong>Go to kayak.com and find the cheapest flight from Karachi to Jeddah on 2025–05–25 with return on 2025–06–05 for 2 people.</strong>”</p><p>The agent would use the services to navigate, input search criteria, and extract results step-by-step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*s32LyywDUhtMFWYr7cYwQQ.gif" /></figure><h3>Source Code</h3><p>The complete source code is available at:</p><p><a href="https://github.com/Sohaib9920/auto-scrape/tree/8364ca8af49633e87d07032df3d9dd739f1a9c9f">GitHub - Sohaib9920/auto-scrape at 8364ca8af49633e87d07032df3d9dd739f1a9c9f</a></p><p><strong>About VannGuard AI</strong></p><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at <a href="/service/mailto:info@vannguardai.com">info@vannguardai.com</a> to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a66d245749a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/building-web-ai-agent-from-scratch-a66d245749a5">Building a Web AI Agent from Scratch</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker 101]]></title>
            <link>https://medium.com/vannguardai/docker-101-38e914a746e1?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/38e914a746e1</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <dc:creator><![CDATA[Uzair Gabol]]></dc:creator>
            <pubDate>Thu, 22 May 2025 14:48:58 GMT</pubDate>
            <atom:updated>2025-05-22T14:48:58.605Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>DOCKER 101</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBsq7XQoHvrQ3bsAwSvpKA.jpeg" /></figure><h4><strong>Introduction to Docker</strong></h4><p>Docker is a powerful tool that helps developers create, share, and run applications easily. It ensures that an application runs the same way on any computer, removing the common issue of “it works on my machine but not on yours.” Docker does this by using containers, which are lightweight and fast compared to traditional methods of running software.</p><h4><strong>What is Docker?</strong></h4><p>Docker is a platform that allows you to package an application and its required components together so it can run on any system. Instead of installing software manually on different computers, Docker makes it possible to set up everything once and use it anywhere. It simplifies software development, testing, and deployment.</p><p>Here’s what Docker provides:</p><ul><li>A way to package applications and their dependencies into a single unit (called a container).</li><li>A consistent environment to run applications on different machines.</li><li>Faster setup and deployment of applications.</li></ul><h4><strong>Why Use Docker?</strong></h4><p>Docker brings several benefits that make development and deployment much easier. Some key reasons to use Docker include:</p><ul><li><strong>Consistency Across Environments: </strong>Developers often face issues where an application runs on one computer but not on another. Docker eliminates this problem by creating a uniform environment.</li><li><strong>Lightweight and Fast: </strong>Docker containers use fewer resources compared to traditional virtual machines, making them faster and more efficient.</li><li><strong>Easy to Scale: </strong>Applications running in Docker can be easily expanded to handle more users or workload without major changes.</li><li><strong>Quick Deployment: </strong>With Docker, setting up an application takes only a few seconds, reducing the time needed to configure new systems.</li><li><strong>Better Collaboration: </strong>Since Docker ensures that an application works the same way everywhere, developers and teams can collaborate more effectively.</li></ul><h4><strong>Containers vs. Virtual Machines</strong></h4><p>Many people confuse Docker containers with virtual machines (VMs), but they work differently. Below is a comparison to understand the key differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*NyESYwlzTpcCcpZH0VE6SQ.png" /></figure><h4><strong>Key Differences:</strong></h4><ul><li><strong>Virtual Machines</strong>: Run a full operating system inside another operating system, which requires more resources.</li><li><strong>Containers</strong>: Share the same operating system but keep applications separated, making them more efficient.</li></ul><h4><strong>Architecture Diagram of Docker</strong></h4><figure><img alt="Image4" src="https://cdn-images-1.medium.com/proxy/0*7Jk5_yDx_JWKzMU-" /></figure><h4><strong>Installing Docker</strong></h4><h4><strong>Installing Docker on Ubuntu (Linux)</strong></h4><p>Follow these steps to install Docker on Ubuntu:</p><h4><strong>1. Set up Docker’s apt repository</strong></h4><p>Run the following commands to add Docker’s official GPG key and repository:</p><pre># Update package list and install dependencies<br>sudo apt-get update<br>sudo apt-get install ca-certificates curl<br><br># Create a directory for the key<br>sudo install -m 0755 -d /etc/apt/keyrings<br><br># Download and add Docker&#39;s official GPG key<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc<br>sudo chmod a+r /etc/apt/keyrings/docker.asc<br><br># Add the Docker repository to Apt sources<br>echo \<br> &quot;deb [arch=$(dpkg - print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br> $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \<br> sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br><br># Update package list again<br>sudo apt-get update</pre><h4><strong>2. Install Docker</strong></h4><p>Run the following command to install Docker:</p><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p><strong>3. Verify Installation</strong></p><p>Run the following command to check if Docker was installed correctly:</p><pre>sudo docker run hello-world</pre><h4><strong>Installing Docker on Windows</strong></h4><p>Follow these steps to install Docker on Windows:</p><p><strong>Download Docker Desktop</strong></p><ul><li>Visit the <a href="https://docs.docker.com/desktop/setup/install/windows-install/">Docker official website</a> and download Docker Desktop for Windows.</li></ul><p><strong>Install Docker Desktop</strong></p><ul><li>Run the downloaded installer and follow the setup instructions.</li><li>Ensure that “Use WSL 2 instead of Hyper-V” is selected if using Windows Subsystem for Linux (WSL 2).</li></ul><p><strong>Restart Your Computer</strong></p><ul><li>After installation, restart your system to apply the changes.</li></ul><p><strong>Verify Installation</strong></p><ul><li>Open PowerShell or Command Prompt and run:</li></ul><pre>docker run hello-world</pre><h4><strong>Installing Docker on macOS</strong></h4><p>Follow these steps to install Docker on macOS:</p><p><strong>Download Docker Desktop</strong></p><ul><li>Go to the <a href="https://docs.docker.com/desktop/setup/install/mac-install/">Docker official website</a> and download Docker Desktop for Mac.</li></ul><p><strong>Install Docker Desktop</strong></p><ul><li>Open the downloaded .dmg file and drag Docker to the Applications folder.</li></ul><p><strong>Run Docker</strong></p><ul><li>Open Docker Desktop from the Applications folder and follow the setup process.</li></ul><p><strong>Verify Installation</strong></p><ul><li>Open the Terminal and run:</li></ul><pre>docker run hello-world</pre><h4><strong>For Windows and macOS:</strong></h4><ul><li>No additional configuration is needed, as Docker Desktop runs with the necessary permissions.</li></ul><figure><img alt="Image3" src="https://cdn-images-1.medium.com/proxy/0*l74TdW0xMv_hBC11" /></figure><h4><strong>Understanding Docker Commands</strong></h4><h4><strong>Basic Commands</strong></h4><p>These are the fundamental Docker commands that help you check running containers and interact with them.</p><ul><li><strong>List running containers</strong>:</li></ul><pre>sudo docker ps</pre><ul><li>This command shows all active containers.</li><li><strong>List all containers (including stopped ones)</strong>:</li></ul><pre>sudo docker ps -a</pre><ul><li><strong>Run a container</strong>:</li></ul><pre>sudo docker run &lt;image_name&gt;</pre><ul><li>This starts a new container from the specified image.</li><li><strong>Stop a running container</strong>:</li></ul><pre>sudo docker stop &lt;container_id&gt;</pre><ul><li><strong>Remove a container</strong>:</li></ul><pre>sudo docker rm &lt;container_id&gt;</pre><h4><strong>Managing Images</strong></h4><p>Docker images are the foundation of containers. These commands help in managing images efficiently.</p><ul><li><strong>Download an image from Docker Hub</strong>:</li></ul><pre>docker pull &lt;image_name&gt;</pre><ul><li><strong>List available images</strong>:</li></ul><pre>sudo docker images</pre><ul><li><strong>Remove an image</strong>:</li></ul><pre>sudo docker rmi &lt;image_id&gt;</pre><h4><strong>Running Containers</strong></h4><p>Running a container allows you to interact with applications inside Docker.</p><ul><li><strong>Start an interactive Ubuntu container</strong>:</li></ul><pre>sudo docker run -it ubuntu bash</pre><ul><li>This starts a container with Ubuntu and gives access to the terminal inside it.</li><li><strong>Start a container in detached mode (runs in the background)</strong>:</li></ul><pre>sudo docker run -d &lt;image_name&gt;</pre><h4><strong>Stopping and Removing Containers</strong></h4><p>Managing containers includes stopping and removing them when they are no longer needed.</p><ul><li><strong>Stop a running container</strong>:</li></ul><pre>sudo docker stop &lt;container_id&gt;</pre><ul><li><strong>Remove a stopped container</strong>:</li></ul><pre>sudo docker rm &lt;container_id&gt;</pre><ul><li><strong>Remove all stopped containers</strong>:</li></ul><pre>sudo docker container prune</pre><h4><strong>Summary Table of Basic Docker Commands</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*IK9hUJQR8EVpLs1vfuABJw.png" /></figure><h4><strong>Working with Dockerfiles</strong></h4><h4><strong>Writing a Dockerfile</strong></h4><p>A Dockerfile consists of several key instructions that define the image setup:</p><ul><li><strong>Base Image</strong>: Every Dockerfile starts with a base image, which serves as the foundation.<br>FROM python:3.9</li><li><strong>Setting Environment Variables</strong>:<br>ENV OPEN_AI_API_KEY=”sk-sdfkkqw123&quot;<br>This sets environment variables inside the container.</li><li><strong>Copying Files</strong>:<br>COPY . /app<br>This copies files from the host machine to the container.</li><li><strong>Installing Dependencies</strong>:<br>RUN pip install -r requirements.txt<br>This installs required Python packages.</li><li><strong>Defining Default Command</strong>:<br>CMD [“python”, “app.py”]<br>This sets the default command when the container starts.</li><li><strong>Setting an Entrypoint</strong>:<br>ENTRYPOINT [“python”]<br>This defines the main executable for the container.</li></ul><h4><strong>Building an Image</strong></h4><p>Once the Dockerfile is ready, build the image using the following command:</p><pre>sudo docker build -t myimage .</pre><p>This command creates a new image with the tag myimage.</p><h4><strong>Running a Container from the Image</strong></h4><p>After building the image, run a container using:</p><pre>sudo docker run -d -p 8000:8000 myimage</pre><p>This runs the container in the background and maps port 8000 of the container to port 8000 on the host.</p><h4><strong>Simple Dockerfile for a Python FastAPI App</strong></h4><pre># Use an official Python runtime as a parent image<br>FROM python:3.9<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the current directory contents into the container<br>COPY . /app<br><br># Install any needed dependencies<br>RUN pip install — no-cache-dir -r requirements.txt<br><br># Expose port 8000 for FastAPI<br>EXPOSE 8000<br><br># Command to run FastAPI app<br>CMD [“uvicorn”, “main:app”, “ — host”, “0.0.0.0”, “ — port”, “8000”]</pre><h4><strong>Working with Docker Compose</strong></h4><h4><strong>What is Docker Compose?</strong></h4><p>Docker Compose uses a YAML file to define services, networks, and volumes required for a project. Instead of running multiple docker run commands, you can start all services with a single command.</p><p>Key benefits of Docker Compose:</p><ul><li>Manages multi-container applications efficiently.</li><li>Uses a single YAML file for configuration.</li><li>Allows easy scaling and networking between services.</li></ul><h4><strong>Writing a</strong> <strong>docker-compose.yml</strong> <strong>File</strong></h4><p>A docker-compose.yml file describes the services, networks, and volumes needed for an application. Here’s a breakdown of its key components:</p><ul><li><strong>Version</strong>: Specifies the Compose file format version.</li><li><strong>Services</strong>: Defines individual containers.</li><li><strong>Networks</strong>: Allows containers to communicate with each other.</li><li><strong>Volumes</strong>: Stores persistent data.</li></ul><h4><strong>Running Multi-Container Applications</strong></h4><p>To start the application using Docker Compose:</p><pre>sudo docker compose up -d</pre><p>The -d flag runs containers in the background.</p><p>To stop the application:</p><pre>sudo docker compose down</pre><p>This command stops and removes all containers, networks, and volumes defined in the docker-compose.yml file.</p><p>To rebuild the containers i.e you updated the code:</p><pre>sudo docker compose up — build -d</pre><h4><strong>Simple</strong> <strong>docker-compose.yml</strong> <strong>File</strong></h4><p>Here is a basic example of a Docker Compose file for a FastAPI application with a PostgreSQL database:</p><pre>services:<br> web:<br> image: my-fastapi-app<br> build: .<br> ports:<br> — “8000:8000”<br> depends_on:<br> — db<br><br> db:<br> image: postgres:13<br> environment:<br> POSTGRES_USER: user<br> POSTGRES_PASSWORD: password<br> POSTGRES_DB: mydatabase<br> volumes:<br> — db_data:/var/lib/postgresql/data<br><br>volumes:<br> db_data:</pre><p>This file defines two services:</p><ul><li>web: Runs the FastAPI application and depends on the db service.</li><li>db: Uses a PostgreSQL image with environment variables for configuration.</li></ul><h4><strong>Docker Networking</strong></h4><h4><strong>Default Bridge Network</strong></h4><p>The <strong>Default Bridge Network</strong> is Docker’s default network configuration. When you run a container without specifying a network, it is connected to the bridge network automatically. This network type is isolated from the rest of the system and other containers.</p><p><strong>How it works:</strong></p><ul><li>Every container on this network gets an IP address.</li><li>Containers can communicate with each other using their IP addresses.</li><li>If you want external systems to communicate with containers, you need to publish ports.</li></ul><p><strong>Example:</strong> When you run a container with the following command:</p><pre>docker run -d — name my-container nginx</pre><p>The container will be placed on the default bridge network. You can access it by publishing a port like this:</p><pre>docker run -d -p 8080:80 — name my-container nginx</pre><p>This will allow you to access the Nginx server running inside the container on port 8080 of your host machine.</p><h4><strong>Creating Custom Networks</strong></h4><p>Sometimes, you may need to create a custom network to have more control over how containers communicate with each other. You can create a custom network to define its type, range of IP addresses, and communication rules.</p><p><strong>Steps to create a custom network:</strong></p><ol><li>To create a custom network, use the following command:</li><li>sudo docker network create my-custom-network</li><li>When you run containers, specify the custom network:</li><li>sudo docker run -d — name container1 — network my-custom-network nginx</li><li>sudo docker run -d — name container2 — network my-custom-network httpd</li></ol><p><strong>Advantages of using custom networks:</strong></p><ul><li>Containers on the same custom network can communicate easily with each other.</li><li>Custom networks provide better control over network configurations like IP addresses, DNS, and subnet.</li></ul><h4><strong>Connecting Multiple Containers</strong></h4><p>If you want multiple containers to talk to each other, Docker makes it easy to connect them by placing them on the same network. Containers on the same network can resolve each other by container names.</p><p><strong>Steps to connect multiple containers:</strong></p><ol><li>First, create a custom network (if you haven’t already):</li><li>sudo docker network create my-custom-network</li><li>Run containers on the same network:</li><li>sudo docker run -d — name container1 — network my-custom-network nginx</li><li>sudo docker run -d — name container2 — network my-custom-network httpd</li><li>Inside container2, you can refer to container1 by its name:</li><li>sudo docker exec -it container2 bash</li><li>curl container1</li><li>This will send a request to container1 from container2 using the container’s name.</li></ol><p>This makes inter-container communication seamless, as Docker handles DNS resolution and ensures that containers on the same network can find each other.</p><h4><strong>Sample Docker Compose with Network</strong></h4><p>Docker Compose is a tool that allows you to define and run multi-container Docker applications. You can specify a custom network in the Compose file to ensure containers can communicate easily.</p><p>Here is a simple example:</p><pre>services:<br> web:<br> image: nginx<br> networks:<br> — my-network<br> ports:<br> — “8080:80”<br> app:<br> image: httpd<br> networks:<br> — my-network<br><br>networks:<br> my-network:<br> driver: bridge</pre><p><strong>Explanation:</strong></p><ul><li><strong>services</strong>: Defines two containers: web (nginx) and app (httpd).</li><li>Both containers are connected to the custom network called my-network.</li><li><strong>networks</strong> section defines my-network as a bridge network.</li></ul><p>When you run this Compose file with docker compose up, Docker will:</p><ol><li>Create a custom bridge network named my-network.</li><li>Launch the web and app containers, both connected to my-network.</li><li>Map port 8080 of the host machine to port 80 of the web container.</li></ol><p>Now, both containers can communicate with each other through the my-network, and you can access the nginx web server on localhost:8080.</p><h4><strong>Docker Volumes &amp; Data Persistence</strong></h4><h4><strong>Using Named Volumes</strong></h4><p><strong>Named volumes</strong> are the most common way to store persistent data in Docker. A named volume is managed by Docker and can be shared across multiple containers. When you create a named volume, Docker handles the location and storage for you.</p><p><strong>How to create and use a named volume:</strong></p><ol><li><strong>Create a named volume:</strong> Docker automatically creates a named volume if you specify one. Here’s how you can create a volume and use it in a container:<br>sudo docker volume create my-volume</li><li><strong>Run a container with a named volume:</strong> You can attach the named volume to a container by using the -v or — mount option:<br> sudo docker run -d -v my-volume:/data my-image</li><li>In this case, any data written to /data inside the container will be stored in the my-volume volume. The data will persist even if the container is removed.</li><li><strong>List named volumes:</strong> To see all the named volumes on your system, use:<br> sudo docker volume ls</li></ol><p><strong>Advantages of named volumes:</strong></p><ul><li>They are managed and stored by Docker, so you don’t have to worry about the file system location.</li><li>They can be easily backed up and restored.</li><li>Volumes can be shared across multiple containers.</li></ul><h4><strong>Bind Mounts</strong></h4><p><strong>Bind mounts</strong> are another way to persist data, but they give you more control over where the data is stored. Unlike named volumes, bind mounts allow you to mount a specific file or directory from the host system into the container.</p><p><strong>How to create and use bind mounts:</strong></p><p><strong>Run a container with a bind mount:</strong> You can mount a specific directory from your local machine into the container. For example:</p><p>sudo docker run -d -v /path/on/host:/path/in/container my-image</p><ol><li>Here, /path/on/host is a directory or file on your local machine, and /path/in/container is where it will be mounted inside the container.</li><li><strong>Edit files on the host:</strong> Any changes you make to the files in /path/on/host will automatically be reflected inside the container at /path/in/container and vice versa.</li></ol><p><strong>Advantages of bind mounts:</strong></p><ul><li>You can choose the exact location on your host machine where the data is stored.</li><li>It is useful when you need to edit data directly on the host or share files between containers and the host system.</li></ul><p><strong>Caution:</strong> Be careful with bind mounts, as Docker does not manage them like volumes. If you delete or modify the files on the host, it can affect the container data.</p><h4><strong>Backing Up &amp; Restoring Volumes</strong></h4><p>Backing up Docker volumes is essential to ensure that important data is not lost. Docker provides ways to back up and restore volumes for disaster recovery or to migrate data between different systems.</p><h4><strong>Backing Up a Volume:</strong></h4><p><strong>Create a backup of a volume using docker run:</strong> You can use a temporary container to create a backup of a volume. For example, to back up the my-volume to a tar file:</p><p>docker run — rm -v my-volume:/data -v $(pwd):/backup alpine tar czf /backup/my-volume-backup.tar.gz -C /data .</p><p>This command does the following:</p><ul><li>It mounts the my-volume to /data inside the container.</li><li>It mounts the current directory $(pwd) on your host to /backup in the container.</li><li>It uses the tar command inside an Alpine container to compress and back up the volume to a .tar.gz file.</li></ul><p><strong>Check the backup:</strong> After running the command, you will find the backup file (my-volume-backup.tar.gz) in your current directory.</p><h4><strong>Restoring a Volume:</strong></h4><ol><li><strong>Restore the backup:</strong> To restore the volume from a backup, run a similar command, but this time use tar to extract the contents into the volume:<br>sudo docker run — rm -v my-volume:/data -v $(pwd):/backup alpine tar xzf /backup/my-volume-backup.tar.gz -C /data</li><li><strong>Verify the restored data:</strong> After the restore process, you can run a container to check that the data in the volume has been correctly restored:<br>sudo docker run -it -v my-volume:/data alpine ls /data</li></ol><p><strong>Advantages of backing up and restoring:</strong></p><ul><li>You can easily move data between different Docker hosts.</li><li>It’s crucial for ensuring that important data is not lost if something goes wrong with your containers.</li></ul><h4><strong>Working with NVIDIA and Docker</strong></h4><h4><strong>Installing NVIDIA Container Toolkit</strong></h4><p>To get started with GPU-accelerated containers, you first need to install the NVIDIA Container Toolkit. This toolkit allows Docker to use the GPU on your system.</p><h4><strong>Step-by-Step Installation:</strong></h4><p><strong>Configure the production repository:</strong> Start by adding the necessary GPG key and repository for the NVIDIA Container Toolkit. Open a terminal and run the following commands:</p><pre>curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg — dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \<br> &amp;&amp; curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \<br> sed ‘s#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g&#39; | \<br> sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list</pre><p><strong>Optionally configure the repository to use experimental packages:</strong> If you want to use experimental features, you can enable the experimental packages by running:</p><p>sed -i -e ‘/experimental/ s/^#//g’ /etc/apt/sources.list.d/nvidia-container-toolkit.list</p><p><strong>Update the packages list:</strong> After configuring the repository, update the list of available packages:</p><p>sudo apt-get update</p><p><strong>Install the NVIDIA Container Toolkit:</strong> Install the toolkit using the following command:</p><p>sudo apt-get install -y nvidia-container-toolkit</p><p>Now, the NVIDIA Container Toolkit is installed on your system, and Docker will be able to use the GPU.</p><h4><strong>Configuring Docker to Use NVIDIA Runtime</strong></h4><p>After installing the toolkit, the next step is to configure Docker to use the NVIDIA runtime for containers. This is done by modifying Docker’s configuration files.</p><p><strong>Configure the container runtime:</strong> Run the following command to configure Docker to use the NVIDIA runtime:</p><p>sudo nvidia-ctk runtime configure — runtime=docker</p><p>This command will update Docker’s configuration file (/etc/docker/daemon.json) to use the NVIDIA runtime.</p><p><strong>Restart Docker:</strong> After the configuration is complete, restart Docker to apply the changes:</p><p>sudo systemctl restart docker</p><p>Once Docker has restarted, it is ready to run GPU-accelerated containers.</p><h4><strong>Running GPU-accelerated Containers</strong></h4><p>Now that Docker is configured to use the NVIDIA runtime, you can run containers that require GPU resources. The nvidia-docker runtime ensures that containers can access your GPU.</p><p><strong>Run a container with GPU support:</strong> You can start a container that uses GPU resources by adding the — gpus flag. For example, to run the nvidia/cuda image (which is a sample image that uses CUDA for GPU tasks), use:</p><p>docker run — gpus all nvidia/cuda:11.0-base nvidia-smi</p><ol><li>In this command:</li></ol><ul><li>— gpus all tells Docker to make all available GPUs accessible inside the container.</li><li>nvidia/cuda:11.0-base is a Docker image that includes CUDA, which is required for GPU-accelerated workloads.</li><li>nvidia-smi is a command that shows the status of the NVIDIA GPUs inside the container.</li></ul><ol><li><strong>Check the output:</strong> If everything is set up correctly, the nvidia-smi command will show details about the GPU(s) inside the container, including information like GPU memory usage and processes using the GPU.</li></ol><h4><strong>4. Using nvidia-smi Inside a Container</strong></h4><p>The nvidia-smi tool is used to monitor the status of NVIDIA GPUs. You can run it inside a Docker container to check if the container has access to the GPU and view GPU usage.</p><ol><li><strong>Run the nvidia-smi command inside a container:</strong> To use nvidia-smi inside a running container, follow these steps:</li></ol><ul><li>Start a container with GPU support (as shown in the previous section).</li><li>Once inside the container, run the command:</li></ul><ol><li>nvidia-smi</li><li><strong>Expected output:</strong> The output will provide details about the available GPUs, including memory usage, processes, and driver versions. This is useful for monitoring the GPU usage within your container.</li></ol><figure><img alt="Image2" src="https://cdn-images-1.medium.com/proxy/0*kTkZzHspJ6b1Si33" /></figure><h4><strong>Deploying Applications with Docker</strong></h4><h4><strong>Deploying a Python Flask App</strong></h4><p>Flask is a lightweight web framework for Python, often used to build web applications. Dockerizing a Flask app allows you to deploy it in any environment without worrying about dependencies or configuration issues.</p><h4><strong>Steps to Deploy a Flask App with Docker:</strong></h4><p><strong>Create your Flask app:</strong> First, create a simple Flask app. Here’s a minimal app.py example:</p><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(‘/’)<br>def hello_world():<br> return ‘Hello, Docker World!’<br><br>if __name__ == ‘__main__’:<br> app.run(host=’0.0.0.0&#39;, port=5000)</pre><p><strong>Create a requirements.txt file:</strong> This file lists the dependencies needed to run your Flask app. You can create it with the following content:</p><pre>Flask==2.1.1</pre><p><strong>Create a Dockerfile:</strong> The Dockerfile is used to define how your application is built into a Docker image. Here’s an example Dockerfile for your Flask app:</p><pre># Use an official Python runtime as a parent image<br>FROM python:3.9-slim<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the current directory contents into the container at /app<br>COPY . /app<br><br># Install the necessary dependencies<br>RUN pip install — no-cache-dir -r requirements.txt<br><br># Make port 5000 available to the world outside this container<br>EXPOSE 5000<br><br># Define environment variable<br>ENV FLASK_APP=app.py<br><br># Run Flask app when the container starts<br>CMD [“flask”, “run”, “ — host=0.0.0.0”]</pre><p><strong>Build the Docker image:</strong> In the same directory as your Dockerfile and app.py, run the following command to build the Docker image:</p><pre>sudo docker build -t flask-app .</pre><p><strong>Run the Flask app in a container:</strong> Once the image is built, run it with the following command:</p><pre>sudo docker run -p 5000:5000 flask-app</pre><p>This will start your Flask app inside a Docker container, and you can access it by navigating to <a href="http://localhost:5000/">http://localhost:5000</a> in your web browser.</p><h4><strong>Deploying a Machine Learning Model</strong></h4><p>Deploying machine learning models with Docker allows you to package the model and its dependencies into a container, ensuring it runs smoothly in any environment.</p><h4><strong>Steps to Deploy a Machine Learning Model with Docker:</strong></h4><ol><li><strong>Save your trained model:</strong> Let’s assume you have a machine learning model trained using any Python framework like scikit-learn, TensorFlow, or PyTorch. You will first save the model into a file, for example, model.pkl (for a scikit-learn model).</li></ol><p><strong>Create an API to serve the model:</strong> Use Flask or FastAPI to create a simple API that loads and serves the model. Here’s an example using Flask:</p><pre>import pickle<br>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br># Load the model when the application starts<br>with open(‘model.pkl’, ‘rb’) as model_file:<br> model = pickle.load(model_file)<br><br>@app.route(‘/predict’, methods=[‘POST’])<br>def predict():<br> data = request.get_json()<br> prediction = model.predict([data[‘features’]])<br> return jsonify({‘prediction’: prediction.tolist()})<br><br>if __name__ == ‘__main__’:<br> app.run(host=’0.0.0.0&#39;, port=5001)</pre><p><strong>Create a requirements.txt file for dependencies:</strong> Add the dependencies to the requirements.txt:</p><pre>Flask==2.1.1<br>scikit-learn==1.0.2</pre><p><strong>Create a Dockerfile:</strong> Here’s an example Dockerfile to package your machine learning model API:</p><pre># Use Python as the base image<br>FROM python:3.9-slim<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the application code and model file into the container<br>COPY . /app<br><br># Install dependencies<br>RUN pip install — no-cache-dir -r requirements.txt<br><br># Expose the port the app will run on<br>EXPOSE 5001<br><br># Start the Flask app<br>CMD [“python”, “app.py”]</pre><p><strong>Build and run the Docker image:</strong> To build the image:</p><pre>sudo docker build -t ml-model-api .</pre><p>To run the container:</p><pre>sudo docker run -p 5001:5001 ml-model-api</pre><p>The model is now available through the API at <a href="http://localhost:5001/predict.">http://localhost:5001/predict.</a> You can send a POST request with features to get predictions.</p><h4><strong>Best Practices for Production</strong></h4><p>When deploying applications to production with Docker, there are a few best practices you should follow to ensure your containers are efficient, secure, and maintainable.</p><h4><strong>Best Practices:</strong></h4><p><strong>Use Multi-stage Builds:</strong> Multi-stage builds allow you to create smaller, more secure images. You can separate the build and runtime environments to minimize the final image size.<br>Example:</p><pre># Stage 1: Build stage<br>FROM python:3.9-slim as build<br><br>WORKDIR /app<br>COPY . /app<br>RUN pip install — no-cache-dir -r requirements.txt<br><br># Stage 2: Final image<br>FROM python:3.9-slim<br>WORKDIR /app<br>COPY — from=build /app /app<br>EXPOSE 5000<br>CMD [“python”, “app.py”]</pre><p><strong>Use Environment Variables:</strong> Use environment variables for sensitive information like API keys or database credentials, instead of hardcoding them in the app. You can define them in your Dockerfile or at runtime.<br>Example:</p><pre>sudo docker run -e MY_API_KEY=”your-api-key” my-app</pre><ol><li><strong>Keep Containers Lightweight:</strong> Use lightweight base images (like python:slim or alpine) to reduce the size of your containers. Smaller images are faster to pull and deploy.</li><li><strong>Use Docker Compose for Multi-container Applications:</strong> If your application depends on multiple services (like a web app and a database), use Docker Compose to manage them together. This simplifies configuration and scaling.</li><li><strong>Secure Your Docker Containers:</strong> Always use the latest stable versions of Docker and base images. Also, run containers with the least privileges needed, and avoid running containers as the root user.</li><li><strong>Automate Docker Builds and Deployments:</strong> Automate the process of building, testing, and deploying Docker containers using CI/CD pipelines. This ensures consistent deployments and saves time during releases.</li></ol><h4><strong>About VannGuard AI</strong></h4><p>At VannGuard AI, we specialize in delivering cutting-edge solutions in Machine Learning, AI, Deep Learning, and Natural Language Processing. Our expertise drives innovation and excellence in every project, ensuring your business stays ahead of the curve. Struggling with an AI challenge? Our expert team is ready to help you turn your vision into reality with tailored AI solutions. Contact us at info@vannguardai.com to explore how we can collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38e914a746e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/docker-101-38e914a746e1">Docker 101</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Catastrophic Forgetting and Continual Learning]]></title>
            <link>https://medium.com/vannguardai/catastrophic-forgetting-and-continual-learning-10ec6c9bd7df?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/10ec6c9bd7df</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Taimoor Sardar]]></dc:creator>
            <pubDate>Thu, 08 May 2025 14:25:30 GMT</pubDate>
            <atom:updated>2025-05-08T14:25:29.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*700xtu0rZgk0-g0fKNJRNA.jpeg" /></figure><h4><strong>1. Introduction: The Goldfish Memory Problem in AI</strong></h4><p>Imagine learning to bake bread and instantly forgetting how to ride a bicycle — absurd for humans, but routine for many AI systems. Neural networks suffer from <strong>catastrophic forgetting</strong>, the abrupt loss of old knowledge when new information is learned.</p><p>This happens because a model’s internal “weights” shift to master a new task, overwriting previous skills. For example:</p><ul><li>A robot trained to recognize kitchen objects may forget navigation routines when taught to tidy up.</li><li>A pneumonia‑diagnosis AI might lose tuberculosis‑detection accuracy after retraining.</li></ul><p>These failures matter in high‑stakes domains — from robotics to healthcare to personalized assistants. <strong>Can we build AI that learns continuously — like humans — without this goldfish‑style amnesia?</strong></p><h3>2. Understanding Catastrophic Forgetting and Its Real‑World Impact</h3><h4>2.1 What Is Catastrophic Forgetting?</h4><p>Catastrophic forgetting (also called catastrophic interference) is the tendency of neural networks to <strong>abruptly erase</strong> previously learned information when trained on new tasks. Unlike humans — who integrate new knowledge without losing past skills — AI models often overwrite old “weights,” leading to total loss of earlier abilities.</p><h4><strong>2.2 How Neural Networks Forget</strong></h4><p>Three core factors drive forgetting in sequential learning:</p><ul><li><strong>Weight Overwriting:</strong> New-task updates adjust shared parameters, disrupting representations formed for prior tasks.</li><li><strong>No Memory Replay:</strong> Unlike biological brains, standard networks don’t spontaneously rehearse old data unless explicitly programmed to do so.</li><li><strong>Sequential‑Only Training:</strong> Training on fresh data without revisiting earlier examples treats each task as if it’s the only one, making retention impossible.</li></ul><h4>2.3 Real‑World Implications</h4><p>When AI forgets, the consequences can be severe:</p><ul><li><strong>Healthcare:</strong> An AI fine‑tuned on new radiology images may lose accuracy on earlier diagnoses, risking missed or incorrect medical decisions</li><li><strong>Safety‑Critical Systems:</strong> Autonomous vehicles or disaster‑response drones that forget baseline behaviors can endanger lives and property</li></ul><h3><strong>3. Preventing Catastrophic Forgetting with Replay Buffer and EWC</strong></h3><h4><strong>3.1 Replay Buffer</strong></h4><p><strong>Overview:<br></strong> The replay buffer method involves storing a subset of samples from previous tasks. When training on a new task, these stored samples are interleaved with new data, acting as a “reminder” mechanism that helps the model preserve earlier information.</p><p><strong>Key Experimental Observations:</strong></p><ul><li><strong>Without Replay:</strong> After training on a new task, the model’s performance on Task 1 (e.g., recognizing digits 0 &amp; 1) dropped drastically.</li><li><strong>With Replay Buffer:</strong> Incorporating a replay buffer significantly improved retention on Task 1 while maintaining strong performance on Task 2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atDrRCJ9WO-Vsr8EB3vCgw.png" /></figure><h4><strong>Hand-on</strong></h4><p>Imports and Device Setup</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from torch.utils.data import DataLoader, Subset<br>import numpy as np<br>import random<br>import matplotlib.pyplot as plt</pre><pre>seed = 42<br>random.seed(seed)<br>np.random.seed(seed)<br>torch.manual_seed(seed)</pre><p><strong>Define the Enhanced MLP Model</strong></p><p>This code defines a simple feedforward neural network (EnhancedMLP) using PyTorch for binary image classification. It flattens 28x28 input images and passes them through two hidden layers with ReLU activation and dropout for regularization, followed by an output layer with two neurons representing the class scores.</p><pre>class EnhancedMLP(nn.Module):<br>    def __init__(self):<br>        super(EnhancedMLP, self).__init__()<br>        self.fc1 = nn.Linear(28 * 28, 256)  # Input layer: 28x28 image flattened<br>        self.dropout1 = nn.Dropout(0.5)<br>        self.fc2 = nn.Linear(256, 128)<br>        self.dropout2 = nn.Dropout(0.5)<br>        self.fc3 = nn.Linear(128, 2)  # Two classes per task<br><br>    def forward(self, x):<br>        x = x.view(x.size(0), -1)  # Flatten input<br>        x = F.relu(self.fc1(x))<br>        x = self.dropout1(x)<br>        x = F.relu(self.fc2(x))<br>        x = self.dropout2(x)<br>        x = self.fc3(x)<br>        return x</pre><p><strong>Define the Replay Buffer</strong></p><p>This code defines a ReplayBuffer class used to store and manage a fixed-size buffer of samples (e.g., data and labels) for training purposes. New samples are added with add(), and if the buffer exceeds its capacity, it randomly removes entries to maintain the size. The sample() method returns a random batch of samples for training, useful in scenarios like reinforcement learning or continual learning.</p><pre>class ReplayBuffer:<br>    def __init__(self, capacity):<br>        self.capacity = capacity<br>        self.buffer = []<br><br>    def add(self, samples):<br>        &quot;&quot;&quot;Add new samples (tuple of (data, target)) to the buffer.<br>           If buffer overflows, remove random samples.<br>        &quot;&quot;&quot;<br>        self.buffer.extend(samples)<br>        if len(self.buffer) &gt; self.capacity:<br>            self.buffer = random.sample(self.buffer, self.capacity)<br><br>    def sample(self, batch_size):<br>        if len(self.buffer) &lt; batch_size:<br>            return self.buffer<br>        else:<br>            return random.sample(self.buffer, batch_size)</pre><p>Prepare the MNIST Dataset for Two Tasks</p><p>This function get_task_dataset prepares a binary classification dataset from MNIST based on the specified task_classes. It filters the MNIST dataset to include only the given two digit classes, normalizes the images, and remaps their labels to 0 or 1 using a custom RemappedDataset class, making it suitable for tasks like binary classification or continual learning.</p><pre>def get_task_dataset(task_classes, train=True):<br>    transform = transforms.Compose([transforms.ToTensor(),<br>                                    transforms.Normalize((0.1307,), (0.3081,))])<br>    dataset = datasets.MNIST(&#39;./data&#39;, train=train, download=True, transform=transform)<br>    indices = [i for i, (_, target) in enumerate(dataset) if target in task_classes]<br>    subset = Subset(dataset, indices)<br><br>    # We define a lambda function to adjust the target.<br>    def target_transform(idx):<br>        return 0 if idx == task_classes[0] else 1<br><br>    class RemappedDataset(torch.utils.data.Dataset):<br>        def __init__(self, subset, transform_fn):<br>            self.subset = subset<br>            self.transform_fn = transform_fn<br>        def __getitem__(self, index):<br>            x, y = self.subset[index]<br>            return x, self.transform_fn(y)<br>        def __len__(self):<br>            return len(self.subset)<br><br>    return RemappedDataset(subset, target_transform)</pre><pre># Create datasets for Task1 and Task2<br>task1_train = get_task_dataset([0, 1], train=True)<br>task1_test = get_task_dataset([0, 1], train=False)<br>task2_train = get_task_dataset([2, 3], train=True)<br>task2_test = get_task_dataset([2, 3], train=False)</pre><pre>batch_size = 64<br>task1_train_loader = DataLoader(task1_train, batch_size=batch_size, shuffle=True)<br>task1_test_loader = DataLoader(task1_test, batch_size=batch_size, shuffle=False)<br>task2_train_loader = DataLoader(task2_train, batch_size=batch_size, shuffle=True)<br>task2_test_loader = DataLoader(task2_test, batch_size=batch_size, shuffle=False)</pre><p><strong>Define Training and Evaluation Functions</strong></p><p>These two functions handle the training and evaluation of a PyTorch model. The train function runs one training epoch, optionally using a <strong>replay buffer</strong> for continual learning by mixing past samples with current ones, computing loss, backpropagating, and updating model weights. It also stores current samples in the buffer. The evaluate function switches the model to evaluation mode, disables gradient tracking, and computes the classification accuracy on a given dataset.</p><pre>def train(model, optimizer, criterion, dataloader, epoch, device, replay_buffer=None, replay_batch_size=32):<br>    model.train()<br>    running_loss = 0.0<br>    for batch_idx, (data, target) in enumerate(dataloader):<br>        data, target = data.to(device), target.to(device)<br><br>        # If a replay buffer is provided, sample from it and concatenate with current batch<br>        if replay_buffer is not None:<br>            buffer_samples = replay_buffer.sample(replay_batch_size)<br>            if len(buffer_samples) &gt; 0:<br>                buf_data = torch.stack([sample[0] for sample in buffer_samples]).to(device)<br>                buf_target = torch.tensor([sample[1] for sample in buffer_samples]).to(device)<br>                data = torch.cat([data, buf_data], dim=0)<br>                target = torch.cat([target, buf_target], dim=0)<br><br>        optimizer.zero_grad()<br>        output = model(data)<br>        loss = criterion(output, target)<br>        loss.backward()<br>        optimizer.step()<br><br>        running_loss += loss.item()<br><br>        # For continual learning: add current batch (without replay augmentation) to buffer<br>        if replay_buffer is not None:<br>            samples = [(d.detach().cpu(), t.item()) for d, t in zip(data[:batch_size], target[:batch_size])]<br>            replay_buffer.add(samples)<br><br>    avg_loss = running_loss / len(dataloader)<br>    print(f&quot;Epoch {epoch}, Loss: {avg_loss:.4f}&quot;)</pre><pre>def evaluate(model, dataloader, device):<br>    model.eval()<br>    correct = 0<br>    total = 0<br>    with torch.no_grad():<br>        for data, target in dataloader:<br>            data, target = data.to(device), target.to(device)<br>            output = model(data)<br>            # Use argmax to get predicted class<br>            pred = output.argmax(dim=1, keepdim=True)<br>            correct += pred.eq(target.view_as(pred)).sum().item()<br>            total += data.size(0)<br>    return 100. * correct / total</pre><pre>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>print(&quot;Device:&quot;, device)</pre><pre># Hyperparameters<br>num_epochs = 5<br>lr = 0.001</pre><p><strong>Experiment 1: Continual Learning Without Replay Buffer</strong></p><p>In this experiment, we train on Task1, then train on Task2 without replay. We then evaluate on both tasks.</p><p><strong>Note: </strong>After training on Task2, performance on Task1 is expected to drop (catastrophic forgetting).</p><pre># Train on Task1 (classes 0 and 1)<br>model_no_replay = EnhancedMLP().to(device)<br>optimizer = optim.Adam(model_no_replay.parameters(), lr=lr)<br>criterion = nn.CrossEntropyLoss()</pre><pre>print(&quot;Training on Task1 (no replay)...&quot;)<br>for epoch in range(1, num_epochs+1):<br>    train(model_no_replay, optimizer, criterion, task1_train_loader, epoch, device)<br><br># Evaluate on Task1<br>acc_task1_before = evaluate(model_no_replay, task1_test_loader, device)<br>print(f&quot;Accuracy on Task1 (after Task1 training): {acc_task1_before:.2f}%&quot;)</pre><pre># Now train on Task2 (classes 2 and 3) WITHOUT using a replay buffer.<br>print(&quot;\nTraining on Task2 without replay ...&quot;)<br>for epoch in range(1, num_epochs+1):<br>    train(model_no_replay, optimizer, criterion, task2_train_loader, epoch, device)<br><br># Evaluate on Task1 and Task2 after training Task2<br>acc_task1_after = evaluate(model_no_replay, task1_test_loader, device)<br>acc_task2 = evaluate(model_no_replay, task2_test_loader, device)<br>print(f&quot;Accuracy on Task1 after Task2 training (no replay): {acc_task1_after:.2f}%&quot;)<br>print(f&quot;Accuracy on Task2 (no replay): {acc_task2:.2f}%&quot;)</pre><p><strong>Experiment 2: Continual Learning With Replay Buffer</strong></p><p>In this experiment, we reinitialize the model and train on Task1. Then, when training on Task2, we use a replay buffer to sample and mix Task1 examples into each mini-batch. This should help to alleviate forgetting.</p><pre># Reinitialize model<br>model_with_replay = EnhancedMLP().to(device)<br>optimizer = optim.Adam(model_with_replay.parameters(), lr=lr)<br>criterion = nn.CrossEntropyLoss()</pre><pre># Create an empty replay buffer (capacity can be tuned)<br>replay_capacity = 500<br>replay_buffer = ReplayBuffer(capacity=replay_capacity)</pre><pre>print(&quot;\n[With Replay] Training on Task1...&quot;)<br>for epoch in range(1, num_epochs+1):<br>    train(model_with_replay, optimizer, criterion, task1_train_loader, epoch, device)<br><br># Evaluate on Task1<br>acc_task1_before_replay = evaluate(model_with_replay, task1_test_loader, device)<br>print(f&quot;[With Replay] Accuracy on Task1 (after Task1 training): {acc_task1_before_replay:.2f}%&quot;)</pre><pre># The training function will update the replay buffer and mix samples.<br>print(&quot;\n[With Replay] Training on Task2 with replay...&quot;)<br>for epoch in range(1, num_epochs+1):<br>    train(model_with_replay, optimizer, criterion, task2_train_loader, epoch, device, replay_buffer=replay_buffer, replay_batch_size=32)<br><br># Evaluate on both tasks<br>acc_task1_after_replay = evaluate(model_with_replay, task1_test_loader, device)<br>acc_task2_replay = evaluate(model_with_replay, task2_test_loader, device)<br>print(f&quot;[With Replay] Accuracy on Task1 after Task2 training: {acc_task1_after_replay:.2f}%&quot;)<br>print(f&quot;[With Replay] Accuracy on Task2: {acc_task2_replay:.2f}%&quot;)</pre><pre># Accuracy comparison<br>methods = [&#39;No Replay&#39;, &#39;With Replay&#39;]<br>task1_acc = [acc_task1_after, acc_task1_after_replay]<br>task2_acc = [acc_task2, acc_task2_replay]</pre><pre># plotting graphs<br>x = np.arange(len(methods))  # label locations<br>width = 0.35  # bar width<br><br>fig, ax = plt.subplots()<br>rects1 = ax.bar(x - width/2, task1_acc, width, label=&#39;Task1&#39;)<br>rects2 = ax.bar(x + width/2, task2_acc, width, label=&#39;Task2&#39;)<br><br>ax.set_ylabel(&#39;Accuracy (%)&#39;)<br>ax.set_title(&#39;Continual Learning: No Replay vs. With Replay Buffer&#39;)<br>ax.set_xticks(x)<br>ax.set_xticklabels(methods)<br>ax.legend()<br><br>for rect in rects1 + rects2:<br>    height = rect.get_height()<br>    ax.annotate(f&#39;{height:.1f}&#39;,<br>                xy=(rect.get_x() + rect.get_width() / 2, height),<br>                xytext=(0, 3),  # 3 points vertical offset<br>                textcoords=&quot;offset points&quot;,<br>                ha=&#39;center&#39;, va=&#39;bottom&#39;)<br><br>plt.show()</pre><p><a href="https://colab.research.google.com/drive/1n4NCHZ-uRXHBUiCn7OVn64KSDrCOXjW-?usp=sharing">Google Colab</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*A5WxslZVpMFXoDc_" /><figcaption>Replay Buffer Results</figcaption></figure><h4><strong>4.2 Elastic Weight Consolidation (EWC)</strong></h4><p><strong>Overview:<br></strong> EWC addresses catastrophic forgetting by quantifying the importance of each parameter for previous tasks. It computes the Fisher Information Matrix from Task 1 to estimate parameter importance. When training on Task 2, a regularization term is added to penalize changes in these important weights, thereby preserving prior knowledge without storing actual data.</p><p><strong>Key Experimental Observations:</strong></p><ul><li><strong>Without EWC:</strong> The model lost significant accuracy on Task 1, even though Task 2 performance remained high.</li><li><strong>With EWC (with careful tuning):</strong> Task 1 accuracy was substantially better preserved while maintaining robust Task 2 performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK70Bj3lox8QAUXZWhwO_Q.png" /></figure><h4>Hand-on</h4><p>Imports and Device Setup</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from torch.optim import AdamW<br>from torch.utils.data import DataLoader, Dataset<br>from torchvision import datasets, transforms<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><p><strong>Define the Enhanced MLP Model</strong></p><p>This code defines a simple feedforward neural network (EnhancedMLP) using PyTorch for binary image classification. It flattens 28x28 input images and passes them through two hidden layers with ReLU activation and dropout for regularization, followed by an output layer with two neurons representing the class scores.</p><pre>class EnhancedMLP(nn.Module):<br>    def __init__(self):<br>        super(EnhancedMLP, self).__init__()<br>        self.fc1 = nn.Linear(28*28, 256)<br>        self.dropout1 = nn.Dropout(0.5)<br>        self.fc2 = nn.Linear(256, 128)<br>        self.dropout2 = nn.Dropout(0.5)<br>        self.fc3 = nn.Linear(128, 2)  # Two classes per task<br><br>    def forward(self, x):<br>        x = x.view(x.size(0), -1)<br>        x = torch.relu(self.fc1(x))<br>        x = self.dropout1(x)<br>        x = torch.relu(self.fc2(x))<br>        x = self.dropout2(x)<br>        x = self.fc3(x)<br>        return x</pre><p><strong>Define the EWC Class</strong></p><p>This EWC class implements <strong>Elastic Weight Consolidation</strong>, a technique used in continual learning to prevent catastrophic forgetting. It calculates the <strong>Fisher Information Matrix</strong> and stores a copy of the model&#39;s optimal parameters after training on a task. The penalty method adds a regularization term to the loss during future training, penalizing changes to important parameters (as measured by the Fisher matrix), helping the model retain knowledge from previous tasks.</p><pre>class EWC:<br>    def __init__(self, model, dataset, device, lambda_ewc=15000):<br>        self.model = model<br>        self.device = device<br>        self.lambda_ewc = lambda_ewc<br>        self.fisher, self.optimal_params = self._compute_fisher(dataset)<br><br>    def _compute_fisher(self, dataset):<br>        dataloader = DataLoader(dataset, batch_size=64, shuffle=True)<br>        fisher = {name: torch.zeros_like(param) for name, param in self.model.named_parameters()}<br>        optimal_params = {name: param.clone().detach() for name, param in self.model.named_parameters()}<br>        self.model.eval()<br>        for images, labels in dataloader:<br>            images, labels = images.to(self.device), labels.to(self.device)<br>            self.model.zero_grad()<br>            outputs = self.model(images)<br>            loss = nn.functional.cross_entropy(outputs, labels)<br>            loss.backward()<br>            for name, param in self.model.named_parameters():<br>                if param.grad is not None:<br>                    fisher[name] += param.grad.detach() ** 2 / len(dataloader)<br>        return fisher, optimal_params<br><br>    def penalty(self, model):<br>        loss = 0<br>        for name, param in model.named_parameters():<br>            loss += torch.sum(self.fisher[name] * (param - self.optimal_params[name]) ** 2)<br>        return self.lambda_ewc * loss</pre><p>Prepare the MNIST Dataset for Two Tasks</p><pre>class CustomMNIST(Dataset):<br>    def __init__(self, original_dataset, digit_pairs, new_labels):<br>        self.data = []<br>        self.targets = []<br>        for img, label in original_dataset:<br>            if label in digit_pairs:<br>                self.data.append(img)<br>                self.targets.append(new_labels[digit_pairs.index(label)])<br>        self.data = torch.stack(self.data)<br>        self.targets = torch.tensor(self.targets, dtype=torch.long)<br><br>    def __getitem__(self, index):<br>        return self.data[index], self.targets[index]<br><br>    def __len__(self):<br>        return len(self.data)</pre><pre># Create datasets for Task1 and Task2<br>def get_mnist_subset(digit_pairs, new_labels, train=True):<br>    transform = transforms.Compose([transforms.ToTensor()])<br>    dataset = datasets.MNIST(root=&quot;./data&quot;, train=train, transform=transform, download=True)<br>    return CustomMNIST(dataset, digit_pairs, new_labels)</pre><p>Training and Evaluation Functions</p><pre>def train_epoch(model, train_loader, optimizer, criterion, device, ewc=None):<br>    &quot;&quot;&quot;Train the model for one epoch on the given train_loader.&quot;&quot;&quot;<br>    model.train()<br>    running_loss = 0.0<br>    correct = 0<br>    total = 0<br>    for images, labels in train_loader:<br>        images, labels = images.to(device), labels.to(device)<br>        optimizer.zero_grad()<br>        outputs = model(images)<br>        loss = criterion(outputs, labels)<br>        if ewc is not None:<br>            loss += ewc.penalty(model)<br>        loss.backward()<br>        optimizer.step()<br>        running_loss += loss.item()<br>        _, predicted = outputs.max(1)<br>        total += labels.size(0)<br>        correct += predicted.eq(labels).sum().item()<br>    epoch_loss = running_loss / len(train_loader)<br>    epoch_acc = correct / total<br>    return epoch_loss, epoch_acc</pre><pre>def evaluate_model(model, data_loader, criterion, device):<br>    &quot;&quot;&quot;Evaluate the model on the given data_loader and return loss and accuracy.&quot;&quot;&quot;<br>    model.eval()<br>    running_loss = 0.0<br>    correct = 0<br>    total = 0<br>    with torch.no_grad():<br>        for images, labels in data_loader:<br>            images, labels = images.to(device), labels.to(device)<br>            outputs = model(images)<br>            loss = criterion(outputs, labels)<br>            running_loss += loss.item()<br>            _, predicted = outputs.max(1)<br>            total += labels.size(0)<br>            correct += predicted.eq(labels).sum().item()<br>    avg_loss = running_loss / len(data_loader)<br>    accuracy = correct / total<br>    return avg_loss, accuracy</pre><p>Visualization Utility Functions</p><pre>def plot_final_bar_chart(acc_a_no_ewc, acc_b_no_ewc, acc_a_ewc, acc_b_ewc):<br>    &quot;&quot;&quot;Create a grouped bar chart showing final accuracies on Task A and Task B,<br>       both without and with EWC.&quot;&quot;&quot;<br>    scenarios = [&quot;No EWC&quot;, &quot;With EWC&quot;]<br>    # For each scenario, we&#39;ll show two bars: one for Task A, one for Task B<br>    task_a_accuracies = [acc_a_no_ewc * 100, acc_a_ewc * 100]<br>    task_b_accuracies = [acc_b_no_ewc * 100, acc_b_ewc * 100]<br><br>    x = np.arange(len(scenarios))  # e.g., [0, 1]<br>    width = 0.35  # width of the bars<br><br>    fig, ax = plt.subplots(figsize=(7, 5))<br><br>    # Plot Task A bars (shifted left)<br>    rects1 = ax.bar(x - width/2, task_a_accuracies, width, label=&quot;Task A&quot;, color=&quot;C0&quot;)<br>    # Plot Task B bars (shifted right)<br>    rects2 = ax.bar(x + width/2, task_b_accuracies, width, label=&quot;Task B&quot;, color=&quot;C1&quot;)<br><br>    ax.set_ylabel(&quot;Accuracy (%)&quot;)<br>    ax.set_title(&quot;Final Accuracies: No EWC vs. EWC&quot;)<br>    ax.set_xticks(x)<br>    ax.set_xticklabels(scenarios)<br>    ax.set_ylim(0, 110)  # a bit above 100 for clarity<br>    ax.legend()<br><br>    # Annotate each bar with its value<br>    def autolabel(rects):<br>        for rect in rects:<br>            height = rect.get_height()<br>            ax.annotate(f&quot;{height:.1f}&quot;,<br>                        xy=(rect.get_x() + rect.get_width()/2, height),<br>                        xytext=(0, 3),<br>                        textcoords=&quot;offset points&quot;,<br>                        ha=&quot;center&quot;, va=&quot;bottom&quot;)<br><br>    autolabel(rects1)<br>    autolabel(rects2)<br><br>    plt.tight_layout()<br>    plt.show()</pre><p>Main code which integrates all the above functionality</p><pre>if __name__ == &quot;__main__&quot;:<br>    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br>    # -------------------------------------------------------------------------<br>    # Define Tasks:<br>    # Task A: Distinguish between digits 0 and 1 (remapped to 0,1)<br>    # Task B: Distinguish between digits 2 and 3 (remapped to 0,1)<br>    # -------------------------------------------------------------------------<br>    train_task_a = get_mnist_subset([0, 1], [0, 1], train=True)<br>    test_task_a = DataLoader(get_mnist_subset([0, 1], [0, 1], train=False), batch_size=64, shuffle=False)<br><br>    train_task_b = get_mnist_subset([2, 3], [0, 1], train=True)<br>    test_task_b = DataLoader(get_mnist_subset([2, 3], [0, 1], train=False), batch_size=64, shuffle=False)<br><br>    # ------------------------------<br>    # Step 1: Train on Task A<br>    # ------------------------------<br>    print(&quot;=== [1] Training on Task A ===&quot;)<br>    model = EnhancedMLP().to(device)<br>    optimizer = optim.Adam(model.parameters(), lr=0.001)<br>    criterion = nn.CrossEntropyLoss()<br>    train_loader_a = DataLoader(train_task_a, batch_size=64, shuffle=True)<br><br>    # Train on Task A (10 epochs)<br>    num_epochs_A = 10<br>    for epoch in range(num_epochs_A):<br>        train_loss, train_acc = train_epoch(model, train_loader_a, optimizer, criterion, device)<br>    # Evaluate final performance on Task A<br>    _, acc_a_after = evaluate_model(model, test_task_a, criterion, device)<br>    print(f&quot;Final Task A Accuracy (after training A): {acc_a_after*100:.2f}%&quot;)<br><br>    # ------------------------------<br>    # Step 2: Continue Training on Task B WITHOUT EWC<br>    # ------------------------------<br>    print(&quot;\n=== [2] Training on Task B WITHOUT EWC ===&quot;)<br>    optimizer = optim.Adam(model.parameters(), lr=0.001)<br>    train_loader_b = DataLoader(train_task_b, batch_size=64, shuffle=True)<br><br>    num_epochs_B = 5<br>    for epoch in range(num_epochs_B):<br>        train_loss, train_acc = train_epoch(model, train_loader_b, optimizer, criterion, device)<br>    # Evaluate final performance on Task A and Task B<br>    _, acc_a_no_ewc = evaluate_model(model, test_task_a, criterion, device)<br>    _, acc_b_no_ewc = evaluate_model(model, test_task_b, criterion, device)<br>    print(f&quot;Final Task A Accuracy (No EWC): {acc_a_no_ewc*100:.2f}%&quot;)<br>    print(f&quot;Final Task B Accuracy (No EWC): {acc_b_no_ewc*100:.2f}%&quot;)<br><br>    # ------------------------------<br>    # Step 3: Reinitialize &amp; Train with EWC<br>    # ------------------------------<br>    print(&quot;\n=== [3] Training on Task B WITH EWC ===&quot;)<br>    # Reinitialize model &amp; train on Task A again<br>    model = EnhancedMLP().to(device)<br>    optimizer = optim.Adam(model.parameters(), lr=0.001)<br>    for epoch in range(num_epochs_A):<br>        train_loss, train_acc = train_epoch(model, train_loader_a, optimizer, criterion, device)<br><br>    # Compute Fisher info for EWC<br>    ewc_obj = EWC(model, train_task_a, device, lambda_ewc=15000)<br><br>    # Train on Task B with EWC<br>    optimizer = AdamW(model.parameters(), lr=0.0005, weight_decay=1e-4)<br>    for epoch in range(num_epochs_B):<br>        train_loss, train_acc = train_epoch(model, train_loader_b, optimizer, criterion, device, ewc=ewc_obj)<br><br>    # Evaluate final performance on Task A and Task B<br>    _, acc_a_ewc = evaluate_model(model, test_task_a, criterion, device)<br>    _, acc_b_ewc = evaluate_model(model, test_task_b, criterion, device)<br>    print(f&quot;Final Task A Accuracy (With EWC): {acc_a_ewc*100:.2f}%&quot;)<br>    print(f&quot;Final Task B Accuracy (With EWC): {acc_b_ewc*100:.2f}%&quot;)<br><br>    # ------------------------------<br>    # Step 4: Create a Bar Chart Comparing Final Accuracies<br>    # ------------------------------<br>    plot_final_bar_chart(<br>        acc_a_no_ewc,<br>        acc_b_no_ewc,<br>        acc_a_ewc,<br>        acc_b_ewc<br>    )</pre><p><a href="https://colab.research.google.com/drive/1gNFRaEm2k2UqNDehIHQfHFjeIyHBL4ND?usp=sharing">Google Colab</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*k87132zCuD_3_blM" /><figcaption>EWC Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*OfVbPhJevemJaiuhkZ-RfQ.png" /><figcaption>Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*nfjb-2Id86P7uPiaI-VTKQ.png" /><figcaption>Pros and Cons of Approaches</figcaption></figure><h3><strong>5. Open Challenges in Continual Learning</strong></h3><p>While approaches like Replay Buffer and EWC show promise, several key challenges remain:</p><ul><li><strong>Task-Agnostic Learning:</strong> Most methods assume clear task boundaries, yet real-world tasks may be undefined or continuously evolving.</li><li><strong>Balancing Stability and Plasticity:</strong> Achieving the right trade-off is difficult; too much stability hampers new learning, while excessive plasticity leads to forgetting.</li><li><strong>Evaluation Metrics:</strong> There is a need for standardized metrics that capture both retention and adaptability.</li><li><strong>Scalability:</strong> As the number of tasks increases, replay buffers may face memory constraints and EWC might over-constrain the network.</li><li><strong>Ethical Considerations:</strong> In applications handling sensitive data, continual learning raises privacy concerns when storing historical data or updating models dynamically.</li></ul><h3>6. The Future of Continual Learning</h3><ul><li><strong>Neuromorphic Hardware</strong>: Brain-inspired chips for faster, greener AI learning.</li><li><strong>Meta-Learning</strong>: Teaching AI to “learn how to learn” for rapid adaptation.</li><li><strong>Hybrid Methods</strong>: Merging replay buffers + regularization for balanced retention and flexibility.</li><li><strong>Industry Adoption</strong>: Autos, healthcare, and streaming giants pushing real-world CL adoption.</li></ul><p>These innovations aim to bridge the gap between lab breakthroughs and practical, lifelong AI systems.</p><h3>7. Conclusion</h3><p>Continual learning isn’t just a technical marvel — it’s the key to building AI that evolves like humans. By tackling <strong>catastrophic forgetting</strong> with methods like Replay Buffers and Elastic Weight Consolidation, we pave the way for:</p><ul><li>Autonomous cars that adapt to new roads without forgetting safety rules.</li><li>Medical AI that retains rare disease knowledge while learning new diagnostics.</li><li>Personalized assistants that grow <em>with</em> you, not against you.</li></ul><p>Yet challenges remain: balancing stability and plasticity, ethical data use, and scalable architectures. With emerging trends like neuromorphic hardware and hybrid learning, the future of AI is lifelong, resilient, and endlessly curious.</p><p><strong>Explore our notebooks</strong> to experiment with these methods firsthand — and join the quest for machines that never stop learning.</p><h3>8. References</h3><ul><li><a href="https://medium.com/@emddb/trustworthy-ai-and-the-crucial-need-to-overcome-catastrophic-forgetting-in-neural-networks-f4c8ece01db1">Trustworthy AI and the Crucial Need to Overcome Catastrophic Forgetting in Neural Networks</a></li><li><a href="https://medium.com/@fernando.dijkinga/catastrophic-forgetting-the-achilles-heel-of-deep-learning-a208de018b2f">Catastrophic Forgetting: The Achilles’ Heel of Deep Learning</a></li><li><a href="https://arxiv.org/abs/2312.10549">Catastrophic Forgetting in Deep Learning: A Comprehensive Taxonomy</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ec6c9bd7df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/catastrophic-forgetting-and-continual-learning-10ec6c9bd7df">Catastrophic Forgetting and Continual Learning</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Models with NVIDIA Triton and Optimizing Inference Pipelines]]></title>
            <link>https://medium.com/vannguardai/deploying-models-with-nvidia-triton-and-optimizing-inference-pipelines-f5c33d82dc03?source=rss----82aa7e5ff444---4</link>
            <guid isPermaLink="false">https://medium.com/p/f5c33d82dc03</guid>
            <category><![CDATA[inference-optimization]]></category>
            <category><![CDATA[inference-engine]]></category>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[triton-inference-server]]></category>
            <category><![CDATA[triton]]></category>
            <dc:creator><![CDATA[Faisalalishah]]></dc:creator>
            <pubDate>Fri, 02 May 2025 13:32:29 GMT</pubDate>
            <atom:updated>2025-05-02T13:32:29.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gqZEhXhOWr25Xz31.jpg" /><figcaption>Image Source: <a href="https://developer.nvidia.com/ko-kr/nvidia-triton-inference-server">https://developer.nvidia.com/ko-kr/nvidia-triton-inference-server</a></figcaption></figure><h3>Introduction</h3><p>Machine learning models are powerful, but deploying them efficiently is often a challenge. You might have a model that performs well during training but struggles to keep up in production. Maybe it’s slow, consumes too many resources, or doesn’t scale well.</p><p>This is where <strong>NVIDIA Triton Inference Server</strong> comes in. Triton is designed to make model deployment easier, faster, and more scalable. Whether you’re working with <strong>PyTorch, TensorFlow, ONNX, or even custom Python-based models</strong>, Triton can handle it all.</p><p>In this article, we’ll explore <strong>why and how</strong> to use Triton for deploying models, along with essential techniques to <strong>optimize inference performance</strong>.</p><h3>Why Choose NVIDIA Triton?</h3><p>If you’ve ever deployed a machine learning model manually, you know it’s not just about running a model. You need to:</p><ul><li><strong>Handle multiple models and frameworks</strong> (TensorFlow, PyTorch, ONNX, Python, etc.)</li><li><strong>Optimize inference speed</strong> to reduce latency</li><li><strong>Scale efficiently</strong> across CPUs, GPUs, and multiple instances</li><li><strong>Support batch processing</strong> to improve throughput</li><li><strong>Enable easy integration</strong> with REST and gRPC APIs</li></ul><p>Triton does all this <strong>out-of-the-box</strong> so you can focus on building better models instead of worrying about deployment headaches.</p><h3>Setting Up NVIDIA Triton</h3><h3>Step 1: Install and Run Triton</h3><p>You can quickly set up Triton using Docker. Run this command to pull the latest Triton image:</p><pre>docker pull nvcr.io/nvidia/tritonserver:latest</pre><p>Then, launch the server:</p><pre>docker run - gpus all -p 8000:8000 -p 8001:8001 -p 8002:8002 \<br>-v /path/to/model_repository:/models \<br>nvcr.io/nvidia/tritonserver:latest tritonserver - model-repository=/models</pre><p>Here, <em>/path/to/model_repository</em> is the directory where your models are stored.</p><h3>Step 2: Organizing the Model Repository</h3><p>Triton expects models to be structured in a specific way. Below is the <strong>unified structure</strong>, covering PyTorch, TensorFlow, ONNX, and Python-based models.</p><pre>/models <br> ├── my_pytorch_model <br> │ ├── 1 <br> │ │ ├── model.pt <br> │ ├── config.pbtxt <br> ├── my_tensorflow_model <br> │ ├── 1 <br> │ │ ├── model.savedmodel <br> │ ├── config.pbtxt <br> ├── my_onnx_model <br> │ ├── 1 <br> │ │ ├── model.onnx <br> │ ├── config.pbtxt <br> ├── my_python_model <br> │ ├── 1 <br> │ │ ├── model.py <br> │ ├── config.pbtxt <br> │ ├── requirements.txt</pre><p>The <em>requirements.txt </em>in python deployment should list dependencies:</p><p><strong>Good news!</strong> If you don’t provide a <em>config.pbtxt</em> file, <strong>Triton will automatically generate one for you</strong> when the server starts. However, manually defining <em>config.pbtxt</em> allows you to fine-tune important settings like <strong>dynamic batching, optimization, and backend configurations</strong>.</p><h3>Optimizing Inference Pipelines with Triton</h3><p>Triton isn’t just about deploying models — it’s about making them <strong>faster and more efficient</strong>. Here’s how you can optimize your inference pipeline:</p><h3>1. Dynamic Batching (Improve Throughput by Combining Requests)</h3><p>Dynamic batching allows Triton to <strong>combine multiple inference requests</strong> into a single batch, reducing the number of computations and increasing efficiency. This is particularly useful when requests arrive at irregular intervals.</p><p><strong>How to Enable:</strong></p><p>Add this to <em>config.pbtxt</em>:</p><pre>dynamic_batching { }</pre><h3>2. Multiple Model Instances (Parallel Execution for Faster Inference)</h3><p>Running multiple instances of a model can <strong>improve throughput</strong> by processing more requests simultaneously, especially on multi-GPU or multi-core CPU setups.</p><p><strong>How to Configure:</strong></p><p>Add this to <em>config.pbtxt</em>:</p><pre>instance_group [ { count: 2 }]</pre><h3>3. Model Optimization with TensorRT (Lower Latency with Faster Computation)</h3><p>TensorRT is an optimization engine that <strong>speeds up deep learning inference</strong> on NVIDIA GPUs by reducing precision and optimizing computations.</p><p><strong>How to Enable TensorRT Optimization:</strong></p><p>Modify <em>config.pbtxt</em> to include <em>TensorRT</em> settings:</p><pre>optimization {<br>  execution_accelerators {<br>    gpu_execution_accelerator : [<br>      {<br>        name : &quot;tensorrt&quot;<br>        parameters {<br>          key: &quot;precision_mode&quot;<br>          value: &quot;FP16&quot;<br>        }<br>      }<br>    ]<br>  }<br>}</pre><h3>4. Performance Analysis with perf_analyzer (Measure Impact of Optimizations)</h3><p>The <em>perf_analyzer</em> tool in Triton helps measure <strong>latency and throughput improvements</strong> after applying optimizations.</p><pre>perf_analyzer -m your_model_name - concurrency-range 1:8 - percentile=95</pre><h3>Serving Models with REST and gRPC APIs</h3><p>Python REST API Example:</p><pre>import requests <br>import numpy as np <br>url = &quot;http://localhost:8000/v2/models/&lt;model_name&gt;/infer&quot; <br>data = { &quot;inputs&quot;: [ { &quot;name&quot;: &quot;input_1&quot;, &quot;data&quot;: np.array([1.0, 2.0, 3.0]).tolist() } ] } <br>response = requests.post(url, json=data) <br>print(response.json())</pre><h3>Final Thoughts</h3><p>Deploying models doesn’t have to be a nightmare. NVIDIA Triton takes care of <strong>scalability, optimization, and efficiency</strong> so you can focus on building great models.</p><h3>Key Takeaways:</h3><ul><li><strong>Triton simplifies model deployment</strong> for TensorFlow, PyTorch, ONNX, and Python-based models</li><li><strong>Optimizing inference</strong> with dynamic batching, multi-instance models, and TensorRT</li><li><strong>Performance monitoring</strong> using perf_analyzer</li><li><strong>Serving models efficiently</strong> using REST and gRPC APIs</li><li><strong>Triton automatically generates config.pbtxt if missing</strong>, but manually defining it gives more control</li></ul><p>If you want to take your model deployment to the next level, <strong>give Triton a try!</strong></p><p>Got questions or feedback? Drop them in the comments below! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c33d82dc03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vannguardai/deploying-models-with-nvidia-triton-and-optimizing-inference-pipelines-f5c33d82dc03">Deploying Models with NVIDIA Triton and Optimizing Inference Pipelines</a> was originally published in <a href="https://medium.com/vannguardai">VannGuard AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>