<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by George Glyn on Medium]]></title>
        <description><![CDATA[Stories by George Glyn on Medium]]></description>
        <link>https://medium.com/@george03glyn?source=rss-f2c3bc2a367d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1Ed1_68K63IiaBLa34KO0A.jpeg</url>
            <title>Stories by George Glyn on Medium</title>
            <link>https://medium.com/@george03glyn?source=rss-f2c3bc2a367d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:50:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@george03glyn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build a Local MCP RAG Server with Python & ChromaDB]]></title>
            <link>https://medium.com/@george03glyn/build-a-local-mcp-rag-server-with-python-chromadb-f134133791dd?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f134133791dd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 18:37:58 GMT</pubDate>
            <atom:updated>2026-09-07T18:39:46.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Stuffing PDFs Into Prompts: Build a Local MCP RAG Server (Python + ChromaDB)</h3><p><strong>How to give Claude Desktop a dynamic local knowledge base without burning through your context window.</strong></p><p>You’ve probably been there: you hand your AI agent 50 enterprise PDFs, ask one simple architectural question, and watch your entire context window go up in flames.</p><p>Stuffing thousands of pages of raw documentation straight into an LLM’s system prompt isn’t an architecture — it’s an expensive memory leak. It results in a massive latency tax, skyrocketing token costs, and a model that loses track of crucial details in the noise.</p><p>What if your agent never sees your raw files until it actually needs them? What if it could dynamically query a private vector store and pull <em>only</em> the exact lines required to answer the user’s question?</p><p>Today, we are building a Dynamic RAG (Retrieval-Augmented Generation) Server using Python, ChromaDB, and the Model Context Protocol (MCP).</p><h3>The Architecture: Zero REST Glue Code</h3><p>In the past, connecting an LLM to a local database required standing up a FastAPI server, writing manual OpenAPI schemas, and hardcoding authentication headers.</p><p>With MCP, we can expose a single tool — search_knowledge_base—directly to the Claude Desktop app. When a domain question is asked, Claude calls the tool, ChromaDB finds the closest match by vector distance, and MCP hands back just the relevant chunk.</p><p>Here is the data flow:</p><p>Claude Desktop -&gt; MCP Server -&gt; ChromaDB</p><p>Let’s build it.</p><p>Let’s build it.</p><h3>Step 1: Install Dependencies</h3><p>We are going to use the latest MCP Python SDK (v2.x) and ChromaDB to spin up a persistent local vector store.</p><pre>pip install mcp chromadb</pre><h3>Step 2: Initialize the Server and Vector Store</h3><p>We need to initialize our MCPServer and point ChromaDB to a local path so our database survives between restarts.</p><pre>import os<br>import asyncio<br>from chromadb import PersistentClient<br>from mcp.server.mcpserver import MCPServer<br><br># 1. Initialize the MCPServer<br>mcp = MCPServer(&quot;Local RAG Knowledge Server&quot;)<br># 2. Setup ChromaDB persistent storage using an absolute path<br>DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), &quot;chroma_db&quot;)<br>client = PersistentClient(path=DB_PATH)<br>collection = client.get_or_create_collection(name=&quot;internal_docs&quot;)</pre><h3>Step 3: Seed the Knowledge Base</h3><p>Next, we load our internal engineering documents into the vector database.</p><p><em>Note: The first time you run </em><em>.add(), ChromaDB will quietly download a lightweight embedding model (</em><em>all-MiniLM-L6-v2) in the background to convert your text into vector coordinates. This is completely normal.</em></p><pre>def seed_knowledge_base():<br>    documents = [<br>        (<br>            &quot;doc_01&quot;,<br>            &quot;Recommended chunk size for production RAG systems is between 512 and 1024 tokens to balance context retention and retrieval precision.&quot;<br>        ),<br>        (<br>            &quot;doc_02&quot;,<br>            &quot;Vector database optimization requires tuning HNSW index parameters like M and ef_construction to maintain low search latency under heavy load.&quot;<br>        ),<br>        (<br>            &quot;doc_03&quot;,<br>            &quot;Database security proxies must inspect AST planner nodes rather than relying solely on regex or pre-flight EXPLAIN snapshots to prevent TOCTOU exploits.&quot;<br>        ),<br>    ]<br><br>    # Only seed if the collection is empty<br>    if collection.count() == 0:<br>        for doc_id, text in documents:<br>            collection.add(documents=[text], ids=[doc_id])<br>        print(&quot;[INFO] ChromaDB seeded successfully with engineering docs.&quot;)</pre><h3>Step 4: The MCP Tool Decorator (Auto-Schema Generation)</h3><p>This is where the magic happens. By wrapping our search function in @mcp.tool(), the SDK parses our docstrings and Python type hints to generate a perfect JSON-RPC schema automatically.</p><pre>@mcp.tool()<br>def search_knowledge_base(query: str) -&gt; str:<br>    &quot;&quot;&quot;Searches the internal engineering knowledge base using vector similarity and returns the closest matching document chunk.&quot;&quot;&quot;<br>    results = collection.query(query_texts=[query], n_results=1)<br><br>    # Extract the top matching document text<br>    if results and results[&quot;documents&quot;]:<br>        matched_text = results[&quot;documents&quot;][0][0]<br>        return matched_text<br><br>    return &quot;No relevant documentation found.&quot;<br><br># Run the server via standard input/output<br>if __name__ == &quot;__main__&quot;:<br>    seed_knowledge_base()<br>    asyncio.run(mcp.run(transport=&quot;stdio&quot;))</pre><p><em>Architecture aside: For this demo, we are only returning the single closest chunk (</em><em>n_results=1). In a production environment, you would typically pull the top-k chunks and pass them through a cross-encoder reranker.</em></p><h3>Step 5: Connecting to Claude Desktop</h3><p>To let Claude use your new local database, simply add the Python execution command to your claude_desktop_config.json file.</p><p><strong>(Windows path example):</strong></p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;local-rag&quot;: {<br>      &quot;command&quot;: &quot;C:\\Users\\&lt;YourUser&gt;\\.conda\\envs\\rag_env\\python.exe&quot;,<br>      &quot;args&quot;: [<br>        &quot;D:\\path\\to\\your\\main.py&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>Restart Claude Desktop.</p><h3>The Payoff: Grounded Retrieval</h3><p>Now, open Claude and ask: <em>“What is the recommended chunk size for production RAG systems according to our internal engineering docs?”</em></p><p>Instantly, you will see the execution badge light up: 🔨 Using tool: search_knowledge_base.</p><p>No prompt bloat. No massive context windows. The answer is grounded directly in your verifiable local facts instead of stochastic guessing.</p><h3>Next Up: Database Security &amp; AST Planner Validation</h3><p>Our agent can now read SQL tables and query vector databases. But granting an AI <em>write</em> access is where security breaks down. Naive regex won’t stop stacked statements or foreign data wrapper escapes.</p><p>In the next guide, we are spinning up a local PostgreSQL database to build a Human-in-the-Loop safety proxy that inspects AST planner nodes <em>before</em> execution.</p><p>Stay tuned.</p><p><em>If you found this breakdown helpful, be sure to check out the </em><a href="https://www.youtube.com/@GenAIwithGlyn"><strong><em>GenAI with Glyn</em></strong><em> </em></a><em>channel on YouTube for the </em><a href="https://youtu.be/x-cCjIDfXsA"><em>full video</em></a><em> walkthrough, and drop a comment below on what vector store you’re currently running in your stack!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f134133791dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Custom APIs for Your AI Agents: Build an MCP Server in 5 Minutes]]></title>
            <link>https://medium.com/@george03glyn/stop-writing-custom-apis-for-your-ai-agents-build-an-mcp-server-in-5-minutes-aed9f8a61db3?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed9f8a61db3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 13:01:59 GMT</pubDate>
            <atom:updated>2026-08-30T13:01:59.864Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Model Context Protocol (MCP) is the new open standard that decouples your AI from your backend infrastructure. Here is how to connect Claude to a live SQL database with zero custom API integrations.</strong></p><p>If you are building enterprise AI agents, you are probably drowning in custom Python code right now.</p><p>Need to connect your agent to a database? You write a custom Python wrapper. Need to fetch Jira tickets or query Slack? You build an entire API integration layer. In an enterprise environment with 10 databases and 5 different LLM frameworks (Claude, AutoGen, LangChain), this architecture collapses instantly.</p><p>This is the N × M integration nightmare. Your AI has to know the exact shape of every single data source it touches.</p><p>But there is a new industry standard that completely eliminates this problem: the <strong>Model Context Protocol (MCP)</strong>.</p><p>Think of MCP as the universal USB-C cable for AI. You write your database connection once, expose it via a single standardized server, and any compatible AI client can plug in, dynamically discover your tools, and use them.</p><p>In this tutorial, we are going to build a local MCP server in under 50 lines of Python (using the official v2 SDK) and connect Claude Desktop directly to a live SQLite database.</p><p>Let’s build it.</p><h3>Step 1: The Architecture &amp; Prerequisites</h3><p>We will be using the official Python mcp package. This high-level framework abstracts away the underlying JSON-RPC protocol complexity, allowing us to expose tools to the LLM using a single Python decorator.</p><p>Before we start, ensure you have the required packages installed in your virtual environment:</p><pre>pip install mcp</pre><p>You will also need the <a href="https://claude.ai/download">Claude Desktop App</a> installed on your machine.</p><h3>Step 2: Building the MCP Server</h3><p>Create a new file named mcp_server.py. We will start by importing our libraries and initializing the server.</p><p><em>(Note: We are using the </em><em>os module to force the SQLite database to be created in the exact same directory as our script. This prevents permission errors when Claude Desktop launches the server in the background).</em></p><pre>import sqlite3<br>import json<br>import os<br>import sys<br>from mcp.server.mcpserver import MCPServer<br><br># Initialize the MCP server<br>mcp = MCPServer(name=&quot;Enterprise_SQL_Agent&quot;)<br><br># Force the database to be created in the exact same folder as this script<br>BASE_DIR = os.path.dirname(os.path.abspath(__file__))<br>DB_PATH = os.path.join(BASE_DIR, &quot;enterprise.db&quot;)</pre><p>Next, let’s create a quick dummy database so our AI has something to query. We will route our setup logs to standard error (sys.stderr) so they don&#39;t corrupt the standard output stream that MCP uses to communicate.</p><pre>def setup_dummy_db():<br>    &quot;&quot;&quot;Create a sample employee database for the demo&quot;&quot;&quot;<br>    try:<br>        conn = sqlite3.connect(DB_PATH)<br>        cursor = conn.cursor()<br>        <br>        cursor.execute(&#39;&#39;&#39;CREATE TABLE IF NOT EXISTS employees <br>                          (id INTEGER PRIMARY KEY, name TEXT, role TEXT, salary INTEGER)&#39;&#39;&#39;)<br>        cursor.execute(&quot;DELETE FROM employees&quot;)<br>        <br>        employees = [<br>            (&quot;Alice&quot;, &quot;Data Scientist&quot;, 120000), <br>            (&quot;Bob&quot;, &quot;DevOps Engineer&quot;, 115000), <br>            (&quot;Charlie&quot;, &quot;AI Researcher&quot;, 135000)<br>        ]<br>        <br>        cursor.executemany(&quot;INSERT INTO employees (name, role, salary) VALUES (?, ?, ?)&quot;, employees)<br>        conn.commit()<br>        conn.close()<br>        print(&quot;Database initialized successfully.&quot;, file=sys.stderr)<br>    except Exception as e:<br>        print(f&quot;Database setup error: {e}&quot;, file=sys.stderr)</pre><h3>Step 3: Exposing the Database to the AI</h3><p>Here is where the magic happens. We write a standard Python function that executes a SQL query and returns the results. By simply adding the @mcp.tool() decorator, the server will instantly read the docstring and type hints to generate a perfect JSON schema for the LLM.</p><pre>@mcp.tool()<br>def query_employee_database(sql_query: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Executes a SQL SELECT query against the enterprise.db database.<br>    <br>    The database contains an &#39;employees&#39; table with columns:<br>    - id (INTEGER PRIMARY KEY)<br>    - name (TEXT)<br>    - role (TEXT)  <br>    - salary (INTEGER)<br>    <br>    SECURITY: Only READ operations (SELECT) are permitted.<br>    &quot;&quot;&quot;<br>    <br>    # Safety Check: Block destructive SQL commands<br>    dangerous_keywords = [&quot;DROP&quot;, &quot;DELETE&quot;, &quot;UPDATE&quot;, &quot;INSERT&quot;, &quot;ALTER&quot;]<br>    if any(keyword in sql_query.upper() for keyword in dangerous_keywords):<br>        return &quot;Error: Only SELECT queries are authorized for this tool.&quot;<br>    <br>    try:<br>        conn = sqlite3.connect(DB_PATH)<br>        cursor = conn.cursor()<br>        cursor.execute(sql_query)<br>        results = cursor.fetchall()<br>        <br>        # Format the output as JSON so the LLM can read it cleanly<br>        column_names = [description[0] for description in cursor.description]<br>        formatted_results = [dict(zip(column_names, row)) for row in results]<br>        <br>        conn.close()<br>        return json.dumps(formatted_results, indent=2)<br>    <br>    except Exception as e:<br>        return f&quot;Database error: {str(e)}&quot;</pre><p>Finally, we add the startup block.</p><pre>if __name__ == &quot;__main__&quot;:<br>    setup_dummy_db()<br>    mcp.run()</pre><h3>Step 4: Connecting Claude Desktop</h3><p>Now we need to tell Claude Desktop where our server is running.</p><ol><li>Open your File Explorer and navigate to your Claude AppData folder: %APPDATA%\Claude</li><li>Open claude_desktop_config.json in your editor.</li><li>Add the mcpServers block.</li></ol><p><strong>🚨 Crucial Windows Configuration Note:</strong> If you are using a virtual environment (like Conda or venv), you must provide the <strong>absolute path</strong> to your isolated python.exe, not just the global python command. Furthermore, you must use double backslashes (\\) for all paths.</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;enterprise-sql&quot;: {<br>      &quot;command&quot;: &quot;C:\\Users\\YourName\\.conda\\envs\\your_env\\python.exe&quot;,<br>      &quot;args&quot;: [<br>        &quot;D:\\Your\\Project\\Path\\mcp_server.py&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>Save the file and fully restart Claude Desktop.</p><h3>Step 5: The Payoff</h3><p>Open Claude Desktop and click the little “hammer” icon (Tools) in the bottom right corner of the chat box. You will see query_employee_database automatically registered.</p><p>Type this prompt:</p><blockquote>“Query the database and tell me which employee has the highest salary and what their role is.”</blockquote><p>Watch what happens. The AI reads the tool description, generates the exact SQL query it needs (SELECT * FROM employees ORDER BY salary DESC LIMIT 1;), executes it through our MCP server, and formats a natural language answer.</p><p><strong>Zero custom API integrations. The AI discovered the schema and queried the data dynamically.</strong></p><h3>What’s Next?</h3><p>This completely changes how we build enterprise agentic systems. You can use this exact same pattern to connect Slack, Jira, GitHub, or any internal company API to your AI agents.</p><p>This is just Episode 1 of my <strong>MCP Masterclass</strong>. If you want to see a full video walkthrough of this build, check out the tutorial on my YouTube channel, <a href="https://www.youtube.com/@GenAIwithGlyn"><strong>GenAI with Glyn</strong></a>:</p><p><a href="https://youtu.be/kKh6PLU_hXg">https://youtu.be/kKh6PLU_hXg</a></p><p>In Episode 2, we are leveling up to build <strong>Dynamic MCP RAG Servers</strong>, allowing your AI to instantly search through private corporate documents on the fly.</p><p><em>If you built something cool using this guide, drop a comment below and let me know what data source you connected!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed9f8a61db3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Gave an AI Agent Access to My Files… Then I Stopped It]]></title>
            <link>https://medium.com/@george03glyn/i-gave-an-ai-agent-access-to-my-files-then-i-stopped-it-8ec8614b2232?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec8614b2232</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 19:02:55 GMT</pubDate>
            <atom:updated>2026-08-23T19:02:55.539Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Implementing Human-in-the-Loop (HITL) in AutoGen with Google Gemini.</em></p><p>If you give an autonomous agent access to your system, you are one hallucination away from disaster. As a GenAI Data Science Engineer, I constantly build systems that optimize for efficiency, but efficiency without boundaries is dangerous. Tell an agent to “free up disk space,” and the fastest mathematical path to zero bytes is wiping the directory.</p><p>In the final episode of our foundational series for Genai with Glyn, we are implementing Human-in-the-Loop (HITL) governance to solve this exact alignment problem.</p><h3>The Alignment Problem: Intent vs. Authorization</h3><p>When an AI agent generates code, there is a fundamental difference between what it intends to do and what it is authorized to do. Microsoft AutoGen provides three execution modes:</p><ul><li>NEVER: Full autonomy with zero oversight.</li><li>TERMINATE: Pauses only at a termination condition.</li><li>ALWAYS: Halts before every single execution.</li></ul><p>By configuring our proxy agent to ALWAYS, we create a mandatory human approval gate.</p><h3>Building the Gatekeeper</h3><p>In our Python script, we configure Google Gemini as the planner and a UserProxyAgent as the human administrator.</p><pre>user_proxy = UserProxyAgent(<br>    name=&quot;Human_Admin&quot;,<br>    human_input_mode=&quot;ALWAYS&quot;,<br>    max_consecutive_auto_reply=5,<br>    code_execution_config={&quot;work_dir&quot;: &quot;workspace&quot;, &quot;use_docker&quot;: False}<br>)</pre><p>When tasked with cleaning up logs, our agent proposed deleting the directory. Because of our gatekeeper, execution froze. Instead of approving, I provided real-time feedback: <em>“Do not delete any files. Create a ZIP archive instead.”</em></p><p>The agent ingested the constraint, replanned, and output a safe archiving script. The AI proposed the action, but the human authorized it.</p><h3>Production Safety Boundaries</h3><p>Keep in mind, an interactive prompt pause is a governance layer, not a complete security boundary. Enterprise safety requires defense-in-depth:</p><ul><li>Docker or gVisor for isolated execution sandboxes.</li><li>Strict Least-Privilege IAM roles.</li><li>Immutable audit logging.</li><li>Explicit tool allow-listing.</li></ul><h3>The Next Evolution</h3><p>Autonomous does not have to mean uncontrolled. With intelligence, memory, and safety now established, we are ready to connect these agents to enterprise systems.</p><p>Watch the full breakdown and grab the code on my channel.</p><p><a href="https://www.youtube.com/watch?v=_TTKUtLc55o">https://www.youtube.com/watch?v=_TTKUtLc55o</a></p><p>What specific enterprise workflows are you hoping to automate next as we move into our upcoming Model Context Protocol (MCP) series?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec8614b2232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cure Your AI Agent’s Amnesia: Building a RAG Pipeline with AutoGen & ChromaDB]]></title>
            <link>https://medium.com/@george03glyn/cure-your-ai-agents-amnesia-building-a-rag-pipeline-with-autogen-chromadb-911c7f6ab8d1?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/911c7f6ab8d1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 13:27:44 GMT</pubDate>
            <atom:updated>2026-08-16T13:27:44.908Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous tutorial on <strong>Genai with Glyn</strong>, we gave our AI agents superpowers by connecting them to the live internet. We built an autonomous team capable of searching the web, analyzing data, and writing reports.</p><p>But there was one massive problem: <strong>Amnesia.</strong></p><p>Standard LLMs are stateless. The second your terminal script finishes executing, the agents forget everything. If you want to build enterprise-grade AI tools — whether it is an HR policy bot, a financial analyst, or a code reviewer — your agents need long-term memory.</p><p>Today, we are going to fix that amnesia. We will build a Retrieval-Augmented Generation (RAG) pipeline using Microsoft AutoGen, Google Gemini, and a local ChromaDB vector database. By the end of this guide, our AI will instantly read, memorize, and answer highly specific questions about the dense, 50-page <strong>DeepSeek-V3 Technical Report</strong> in under 5 seconds.</p><h3>The Problem with Context Windows</h3><p>Why not just drop the entire PDF into the Gemini context window?</p><p>While modern models like Gemini 1.5 Pro boast massive context limits, forcing a 50-page document into a prompt for <em>every single query</em> is slow, inefficient, and expensive. Furthermore, while a single PDF might fit, an entire corporate knowledge base spanning hundreds of documents will not.</p><p>Instead, we use a <strong>Vector Database</strong>.</p><ol><li>Our Memory Agent takes the DeepSeek PDF and chops it into tiny, readable chunks.</li><li>It converts those chunks into vector embeddings and saves them in ChromaDB.</li><li>When we ask a question, ChromaDB instantly searches its database, retrieves only the relevant chunks, and hands them to our Gemini Assistant to synthesize an answer.</li></ol><p>It is fast, cost-effective, and infinitely scalable.</p><h3>Step 1: Project Setup</h3><p>First, let’s set up our Python workspace. Open your terminal and install the required packages. We need AutoGen with the retrievechat extension, ChromaDB, and a few rendering dependencies.</p><pre>pip install &quot;pyautogen[retrievechat]&quot; chromadb pypdf ipython markdownify</pre><p>Once installed, create a new folder in your directory called data. This will act as our local knowledge base. Download the <a href="https://www.google.com/search?q=https://arxiv.org/pdf/2412.19437.pdf">DeepSeek-V3 Technical Report from arXiv</a> and drop the PDF directly into this data/ folder.</p><h3>Step 2: Configuring the AI Brain</h3><p>Create a new file named rag_agent.py. First, we need to set up our LLM configuration. We are routing Google Gemini through its official OpenAI-compatible endpoint so it interfaces perfectly with AutoGen.</p><pre>import os<br>from dotenv import load_dotenv<br>from autogen import AssistantAgent<br>from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent<br><br>load_dotenv()<br><br># Setup Gemini Config via OpenAI Endpoint<br>llm_config_gemini = {<br>    &quot;config_list&quot;: [<br>        {<br>            &quot;api_type&quot;: &quot;openai&quot;,<br>            &quot;model&quot;: &quot;gemini-3.5-flash&quot;,<br>            &quot;api_key&quot;: os.environ.get(&quot;GEMINI_API_KEY&quot;),<br>            &quot;base_url&quot;: &quot;https://generativelanguage.googleapis.com/v1beta/openai/&quot;<br>        }<br>    ]<br>}<br><br># Create the Assistant<br>assistant = AssistantAgent(<br>    name=&quot;Assistant&quot;,<br>    system_message=&quot;You are a highly analytical AI assistant. Answer questions strictly and precisely based on the retrieved context from the research paper. If the answer is not in the context, state that you do not know.&quot;,<br>    llm_config=llm_config_gemini,<br>)</pre><p><strong>Guardrails:</strong> Notice the system_message. By strictly instructing the agent to state <em>&quot;I do not know&quot;</em> if the information is missing from the retrieved context, we effectively prevent AI hallucinations.</p><h3>Step 3: Building the Memory Agent (ChromaDB)</h3><p>Now for the magic. AutoGen features a built-in agent specifically designed for vector databases: the RetrieveUserProxyAgent. Because AutoGen natively supports ChromaDB, we do not have to write any complex ingestion loops or chunking algorithms manually.</p><pre># Create the Memory Agent (The RAG Vector Database)<br>rag_proxy = RetrieveUserProxyAgent(<br>    name=&quot;MemoryAgent&quot;,<br>    human_input_mode=&quot;NEVER&quot;,<br>    max_consecutive_auto_reply=2,<br>    retrieve_config={<br>        &quot;task&quot;: &quot;qa&quot;,<br>        &quot;docs_path&quot;: [&quot;data/deepseek_v3_report.pdf&quot;], <br>        &quot;collection_name&quot;: &quot;deepseek_knowledge_base&quot;,<br>        &quot;chunk_token_size&quot;: 1000,<br>        &quot;get_or_create&quot;: True, <br>    },<br>    code_execution_config=False<br>)</pre><p>Look at the retrieve_config dictionary. By pointing docs_path to our data folder and setting get_or_create to True, AutoGen will automatically build a local, persistent vector database on our hard drive. ChromaDB silently downloads a local embedding model in the background and does all the heavy lifting.</p><h3>Step 4: Execution and Querying</h3><p>Finally, let’s initiate the chat and ask our pipeline a highly technical, multi-part question to test its retrieval capabilities.</p><pre>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Agent is reading the DeepSeek-V3 document and building memories in ChromaDB...&quot;)<br>    <br>    rag_proxy.initiate_chat(<br>        assistant,<br>        problem=&quot;Based on the DeepSeek-V3 document, what is the Multi-head Latent Attention (MLA) architecture used for and how does it impact training efficiency?&quot;<br>    )</pre><h3>The Result</h3><p>When you run python rag_agent.py, watch the terminal logs. During the initial execution, ChromaDB reads the 50-page PDF, generates the vector embeddings, and stores them locally. Within seconds, the agent searches the vector space, retrieves the exact paragraphs regarding Multi-head Latent Attention, and Gemini synthesizes a precise technical summary.</p><p>Even better, if you look at your file directory, you will see a new chromadb/ folder. Your agent now has persistent memory. If you run the script again with a new question, it skips the ingestion phase completely and answers almost instantly.</p><p>Your AI agents are no longer stuck with amnesia. You can drop API documentation, HR policies, or financial ledgers into that data folder, and your agent will memorize all of it.</p><p>📺 <strong>Prefer a visual guide?</strong> <a href="https://www.youtube.com/watch?v=AqewE2sgG1I">[Watch the full YouTube tutorial here]</a></p><p><em>What massive dataset or documentation are you going to have your AI agent memorize next? Let me know in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911c7f6ab8d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Autonomous AI Agents with AutoGen, Gemini, and Custom Tools]]></title>
            <link>https://medium.com/@george03glyn/build-autonomous-ai-agents-with-autogen-gemini-and-custom-tools-c48b8488f2fa?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48b8488f2fa</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 19:31:41 GMT</pubDate>
            <atom:updated>2026-08-09T19:35:30.450Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered why most AI agents act like isolated islands? They are stuck inside their own code, relying entirely on old training data, and are completely blind to the live internet.</p><p>When building advanced generative AI solutions, this limitation becomes a massive bottleneck. If you ask a standard model about current events, changing regulations, or live weather, it will hallucinate or fail.</p><p>The solution? <strong>Tool-Enabled Agents.</strong></p><p>In this tutorial, we are going to build a multi-agent system using <strong>AutoGen</strong> and <strong>Google Gemini</strong> that can autonomously search the live web, gather real-time data, and synthesize a complete report.</p><p>Let’s give your AI superpowers.</p><ul><li>📺 <em>Prefer watching a video walkthrough? You can watch the complete video tutorial on </em><a href="https://www.youtube.com/watch?v=xa6umm418k8"><em>YouTube</em></a><em>.</em></li></ul><h3>🏗️ The Architecture: A Multi-Agent Team</h3><p>Instead of asking one single AI model to do everything — which often leads to confusion and errors — we are going to divide the work across a small, specialized team.</p><p>Our architecture consists of three distinct roles:</p><ol><li><strong>User Proxy Agent:</strong> The manager and execution engine. It doesn’t generate content; it simply executes Python functions (our tools) and passes messages between agents.</li><li><strong>Lead Researcher:</strong> Our search specialist. We equip this agent with system prompt instructions and give it direct access to a web search tool.</li><li><strong>Summary Writer:</strong> The synthesizer. This agent has no internet access. Its only job is to take the raw, messy data gathered by the researcher and format it into a clean Markdown summary.</li></ol><h3>🛠️ Step 1: Building the Custom Search Tool</h3><p>A golden rule in AI development is modularity. We will keep our custom tools inside a separate tools/ folder away from the main agent logic.</p><p>Create a file named tools/tavily_search.py. We will use the Tavily Search API to pull live web data.</p><pre>import os<br>from typing import Annotated<br>from tavily import TavilyClient<br><br># Initialize the client using the environment variable<br>tavily_client = TavilyClient(api_key=os.environ.get(&quot;TAVILY_API_KEY&quot;))<br><br># Use Annotated to explicitly define the parameter for the LLM<br>def web_search(<br>    query: Annotated[str, &quot;The specific search query string to look up on the internet&quot;]<br>) -&gt; str:<br>    &quot;&quot;&quot;<br>    Searches the internet to get the results for a given query.<br>    &quot;&quot;&quot;<br>    try:<br>        response = tavily_client.search(query, max_results=3)<br>        return str(response.get(&#39;results&#39;, []))<br>    except Exception as e:<br>        return f&quot;Error during search: {e}&quot;</pre><blockquote><strong><em>Pro-Tip:</em></strong><em> Notice the </em><em>Annotated type hint? This is crucial for tool calling. It gives the Gemini model a plain English description of the parameter so it knows exactly how to format its function call without throwing errors.</em></blockquote><h3>🧠 Step 2: Configuring Gemini with AutoGen</h3><p>Connecting Google Gemini to AutoGen requires a specific configuration to ensure stable tool calling. Instead of using the native Google SDK (which can sometimes throw MALFORMED_FUNCTION_CALL errors with AutoGen), we will route Gemini through its official <strong>OpenAI-compatible endpoint</strong>.</p><p>Create your main.py file and add the following configuration:</p><pre>import os<br>from dotenv import load_dotenv<br>from autogen import ConversableAgent, GroupChat, GroupChatManager, register_function<br>from tools.tavily_search import web_search<br><br>load_dotenv()<br><br># Setup LLM Config using Gemini&#39;s OpenAI compatibility endpoint<br>llm_config_gemini = {<br>    &quot;config_list&quot;: [<br>        {<br>            &quot;api_type&quot;: &quot;openai&quot;,<br>            &quot;model&quot;: &quot;gemini-3.5-flash&quot;, <br>            &quot;api_key&quot;: os.environ.get(&quot;GEMINI_API_KEY&quot;),<br>            &quot;base_url&quot;: &quot;https://generativelanguage.googleapis.com/v1beta/openai/&quot;<br>        }<br>    ]<br>}</pre><p>By setting the api_type to openai and defining the base_url, AutoGen handles the complex tool schemas perfectly.</p><h3>🤖 Step 3: Defining the Agents</h3><p>Now, we instantiate our team using the ConversableAgent class and link our custom search tool using register_function.</p><pre># 1. Create the User Proxy (The Executor)<br>user_proxy = ConversableAgent(<br>    name=&quot;UserProxy&quot;,<br>    human_input_mode=&quot;NEVER&quot;,<br>    code_execution_config=False<br>)<br><br># 2. Create the Lead Researcher (The Tool Caller)<br>lead_researcher = ConversableAgent(<br>    name=&quot;LeadResearcher&quot;,<br>    system_message=&quot;You are a search specialist. Use the web_search tool to find live data on the internet.&quot;,<br>    llm_config=llm_config_gemini<br>)<br><br># 3. Create the Summary Writer (The Formatter)<br>summary_writer = ConversableAgent(<br>    name=&quot;SummaryWriter&quot;,<br>    system_message=&quot;You are a Summary Writer. Your job is to format the findings into a clean Markdown summary.&quot;,<br>    llm_config=llm_config_gemini<br>)<br><br># 4. Register Custom Tools<br>register_function(<br>    web_search,<br>    caller=lead_researcher,<br>    executor=user_proxy,<br>    name=&quot;web_search&quot;,<br>    description=&quot;Searches the internet to get results for a query.&quot;<br>)</pre><h3>🚀 Step 4: Orchestrating the Group Chat</h3><p>Finally, we place all three agents into a GroupChat. To prevent the agents from speaking out of turn, we use speaker_selection_method=&quot;round_robin&quot;, which forces a strict, predictable order: User -&gt; Researcher -&gt; Writer.</p><pre># Initialize the Group Chat<br>groupchat = GroupChat(<br>    agents=[user_proxy, lead_researcher, summary_writer],<br>    messages=[],<br>    max_round=10,<br>    speaker_selection_method=&quot;round_robin&quot;<br>)<br><br>manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config_gemini)<br><br>if __name__ == &quot;__main__&quot;:<br>    # Start the conversation workflow<br>    chat_result = user_proxy.initiate_chat(<br>        manager,<br>        message=&quot;Research global AI regulations in 2026 and write a 300-word summary.&quot;<br>    )<br>    <br>    # Extract and display strictly the final summary<br>    print(&quot;\n&quot; + &quot;=&quot; * 50)<br>    print(&quot;FINAL SUMMARY&quot;)<br>    print(&quot;=&quot; * 50)<br>    print(chat_result.summary)</pre><p>When you run python main.py, the magic happens.</p><p>The Lead Researcher identifies that it needs live 2026 data and outputs a structured function call. The User Proxy intercepts the call, hits the live internet, and feeds the raw search results back into the chat. The researcher conducts follow-up searches if necessary, and then passes the baton to the Summary Writer, who produces a flawless, up-to-date report.</p><h3>Conclusion</h3><p>You have successfully transitioned from building static chatbots to engineering an autonomous, tool-using AI team. By keeping your tools modular, dividing agent responsibilities, and leveraging robust API endpoints, the possibilities for what you can build are practically limitless.</p><p>For a full video walkthrough of this build, check out the tutorial on the <strong>GenAI with Glyn</strong> YouTube channel!</p><p>What custom tools are you going to give your agents first? Let me know in the comments.</p><p><em>GenAI with Glyn</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48b8488f2fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI Financial Analyst under 10 Minutes (Gemini + AutoGen)]]></title>
            <link>https://medium.com/@george03glyn/build-an-ai-financial-analyst-under10-minutes-gemini-autogen-4b17b83e8ce4?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b17b83e8ce4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 10:53:46 GMT</pubDate>
            <atom:updated>2026-08-11T07:20:51.129Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wanted to look at some stock data, but you end up spending 30 minutes just writing long Python code, fixing API errors, and making charts look presentable?</p><p>It is tiring.</p><p>Welcome to AI with Glyn! I am George, and today we are skipping all that hard work. I am going to show you how to build a smart AI team using Microsoft’s AutoGen framework and Google’s new Gemini 3.1 Pro preview model. Basically, we are making our own AI Financial Analyst that gets live data and builds custom charts completely by itself.</p><p>Let’s jump right into the code.</p><h3>1. The Environment Setup (Pro-Tip!)</h3><p>Instead of writing one huge script, think of this like hiring a mini tech startup right inside our computer. But before we hire them, we need to set up their office.</p><p><strong>Important Pro-Tip:</strong> Make sure you use a Python 3.11 or 3.12 environment (I highly recommend Conda). If you use newer versions like Python 3.14, you might get annoying setup errors when installing data science tools.</p><p>Create a file named requirements.txt and add these tools:</p><pre>pyautogen~=0.2.0<br>google-generativeai<br>python-dotenv<br>yfinance<br>matplotlib<br>pandas</pre><p>Install them by running this in your terminal:</p><pre>pip install -r requirements.txt</pre><p>Next, create a .env file in the same folder to securely store your Google Gemini API key:</p><pre>GOOGLE_GEMINI_API_KEY=your_api_key_here</pre><h3>2. Hiring Your AI Team</h3><p>Now, let’s create our main script. Create a file named main.py. We are going to set up two AI agents to work together.</p><ul><li><strong>The Senior Data Scientist:</strong> This agent uses the Gemini 3.1 Pro preview model. It has the smarts to write our data science code.</li><li><strong>The Project Manager:</strong> This agent does not write code. It simply runs the code from the Data Scientist, adds missing files, and fixes errors.</li></ul><p>Here is the code to set them up:</p><pre>import autogen<br>import os<br>from dotenv import load_dotenv<br><br># Load secrets from the .env file<br>load_dotenv()<br><br># ==========================================<br># AI with Glyn - Multi-Agent Task Manager<br># Project: Autonomous Financial Analyst<br># ==========================================<br><br># 1. Configure the LLM to use Google Gemini 3.1 Pro Preview<br>config_list = [<br>    {<br>        &quot;model&quot;: &quot;gemini-1.5-pro&quot;, # Note: AutoGen routes to the latest Pro model via the API key<br>        &quot;api_key&quot;: os.environ.get(&quot;GOOGLE_GEMINI_API_KEY&quot;),<br>        &quot;api_type&quot;: &quot;google&quot; <br>    }<br>]<br><br>llm_config = {<br>    &quot;seed&quot;: 42,<br>    &quot;config_list&quot;: config_list,<br>    &quot;temperature&quot;: 0.2,<br>}<br><br># 2. Setup the &quot;Senior Data Scientist&quot; <br>senior_engineer = autogen.AssistantAgent(<br>    name=&quot;Senior_Data_Scientist&quot;,<br>    llm_config=llm_config,<br>    system_message=&quot;&quot;&quot;You are a Senior Data Scientist. Your job is to write robust, production-ready Python code. <br>    Provide the complete code block for the Project Manager to execute. Append TERMINATE when the task is fully complete.&quot;&quot;&quot;<br>)<br><br># 3. Setup the &quot;Project Manager&quot; <br>project_manager = autogen.UserProxyAgent(<br>    name=&quot;Project_Manager&quot;,<br>    human_input_mode=&quot;NEVER&quot;, <br>    max_consecutive_auto_reply=10,<br>    is_termination_msg=lambda x: x.get(&quot;content&quot;, &quot;&quot;).rstrip().endswith(&quot;TERMINATE&quot;),<br>    code_execution_config={<br>        &quot;work_dir&quot;: &quot;finance_workspace&quot;, <br>        &quot;use_docker&quot;: False <br>    },<br>    system_message=&quot;You are the Project Manager. You execute the code provided by the Senior Data Scientist, install missing dependencies, and report back any errors.&quot;<br>)</pre><h3>3. Assigning the Task</h3><p>Alright, let’s give our new startup a job. We will ask them to use the yfinance tool to get Nvidia&#39;s stock data for the last 6 months, make a nice chart, and save it as an image.</p><p>Add this to the bottom of your main.py file:</p><pre># 4. Define the High-Level Data Task<br>data_task = &quot;&quot;&quot;<br>Write a complete Python script that does the following:<br>1. Uses the &#39;yfinance&#39; library to fetch the historical stock price data for Nvidia (NVDA) over the last 6 months.<br>2. Uses &#39;matplotlib&#39; and &#39;pandas&#39; to plot the closing price over time.<br>3. Adds a title, grid lines, and labels to the chart to make it look professional.<br>4. Saves the chart as an image file named &#39;nvidia_stock_chart.png&#39; in the current directory and prints a success message.<br><br>Please write the complete code block. I will execute it. Ensure all necessary imports are included.<br>&quot;&quot;&quot;<br><br># 5. Initiate the Collaboration<br>print(&quot;Initializing AI Startup... Handing off task to the Senior Data Scientist.\n&quot;)<br><br>project_manager.initiate_chat(<br>    senior_engineer,<br>    message=data_task<br>)</pre><h3>4. The Magic (Execution)</h3><p>Now… take your hands completely off the keyboard.</p><p>Run python main.py in your terminal and watch the screen. You can actually see the agents talking to each other! The Gemini Data Scientist writes the code, passes it over, and the Project Manager runs it. If your computer is missing a tool like matplotlib, the manager sees it, installs it, and tries again automatically.</p><p>In just a few seconds, a perfect Nvidia stock chart will appear in your folder. They just worked together to build a perfect financial visualization, and you did not write a single line of data science code.</p><h3>See it in Action</h3><p>It is amazing how fast you can build things when you have AI doing the heavy lifting. If you want to see this code run live, check out the full video tutorial on my YouTube channel!</p><p><a href="https://www.youtube.com/watch?v=mOLxKuxXhkM">https://www.youtube.com/watch?v=mOLxKuxXhkM</a></p><p>Drop a comment letting me know what you want our AI startup to build next, hit subscribe, and I will catch you guys in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b17b83e8ce4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Database Optimization for Production RAG Systems (2026 Guide)]]></title>
            <link>https://medium.com/@george03glyn/vector-database-optimization-for-production-rag-systems-2026-guide-ecc2f468042d?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc2f468042d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 05:58:40 GMT</pubDate>
            <atom:updated>2026-03-01T05:58:40.596Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>FAANG-Level Architecture, HNSW Tuning, Benchmarking, Security Standards &amp; Cost Optimization</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OONzsZPcCHXb1IXIRAA_gg.png" /></figure><p>Over the last year, I’ve watched countless teams build amazing GenAI demos, only to watch them completely melt down in production.</p><p>If your RAG system is slow, hallucinating, or expensive, your vector database is the bottleneck.</p><p>Most GenAI demos work. Very few production systems scale. This guide shows how real production AI systems optimize vector databases for:</p><ul><li><strong>&lt;100ms</strong> P95 latency</li><li><strong>0.90+</strong> Recall@10</li><li><strong>1K–10K</strong> QPS throughput</li><li><strong>SOC 2 / ISO 27001</strong> compliance</li><li><strong>Cost-efficient</strong> scaling</li></ul><p>This is not a beginner guide. This is production-grade system design.</p><h3>Why Vector Database Optimization Matters</h3><p>In a production RAG system, the flow looks like this:</p><p><strong>User Query → Embedding → Vector Search → Reranking → LLM → Response</strong></p><p>If vector search is poorly optimized:</p><p>❌ Latency spikes</p><p>❌ Recall drops</p><p>❌ Hallucinations increase</p><p>❌ Infrastructure costs grow</p><p>❌ User trust decreases</p><p>The vector database is the intelligence layer of your RAG architecture.</p><h3>1️⃣ Production Retrieval Architecture (Deep System Design)</h3><p><strong>Baseline Production Retrieval Flow</strong></p><pre>┌─────────────────────┐      <br>│ User Query          ├──► ┌─────────────────────┐<br>└─────────────────────┘    │ API Gateway (Auth)  │<br>                           └──────────┬──────────┘<br>                                      ▼<br>                           ┌─────────────────────┐<br>                           │ Query Preprocessor  │<br>                           │ - Clean text        │<br>                           │ - PII masking       │<br>                           └──────────┬──────────┘<br>                                      ▼<br>                           ┌─────────────────────┐<br>                           │ Embedding Service   │<br>                           │ (GPU / API based)   │<br>                           └──────────┬──────────┘<br>                                      ▼<br>                           ┌─────────────────────┐<br>                           │ Vector DB (HNSW)    │<br>                           │ ANN Retrieval       │<br>                           └──────────┬──────────┘<br>                                      ▼<br>                           ┌─────────────────────┐<br>                           │ Reranker (CrossEnc) │<br>                           └──────────┬──────────┘<br>                                      ▼<br>                           ┌─────────────────────┐<br>                           │ LLM (Generation)    │<br>                           └──────────┬──────────┘<br>                                      ▼<br>                               Final Response</pre><h4>Why Each Layer Exists</h4><p><strong>API Gateway:</strong></p><ul><li>JWT authentication</li><li>Rate limiting</li><li>RBAC enforcement</li><li>Audit logging</li></ul><p><em>(Prevents abuse and injection attacks.)</em></p><p><strong>Query Preprocessing:</strong></p><p>Enterprise systems must mask PII before embedding, normalize queries and expand synonyms.</p><p><em>Why?</em> Embeddings are incredibly hard to delete once indexed. <strong>Never embed raw PII.</strong></p><p><strong>Embedding Layer Optimization:</strong></p><ul><li>Batch embeddings (30–50% cost reduction)</li><li>Use smaller models when acceptable</li><li>Cache frequent embeddings</li></ul><h3>2️⃣ FAANG-Level Scalable Vector Architecture</h3><p>When datasets grow beyond 10M+ vectors, single-node systems fail.</p><p><strong>Multi-Node Sharded Architecture</strong></p><pre>┌──────────────┐<br>         │ Load Balancer│<br>         └───────┬──────┘<br>                 ▼<br>┌────────────────────────────────┐<br>│ Query Router                   │<br>│ - Tenant routing               │<br>│ - Shard selection              │<br>└──────────┬───────────┬─────────┘<br>           ▼           ▼<br>    ┌──────────────┐ ┌──────────────┐<br>    │   Shard A    │ │   Shard B    │<br>    │ (HNSW Index) │ │ (HNSW Index) │<br>    └──────────────┘ └──────────────┘<br>           ▼           ▼<br>         Merge + Deduplicate<br>                 ▼<br>          Reranker Layer<br>                 ▼<br>                LLM</pre><h4>Why Sharding Is Critical</h4><p>For 100M+ vectors, single-node setups suffer from extreme memory pressure, agonizing rebuild times and scaling bottlenecks.</p><p><strong>Production rule:</strong> Keep shard size &lt; 20M vectors per node.</p><p><strong>Benefits:</strong> Parallel search, drastically lower latency and horizontal scalability.</p><h3>3️⃣ HNSW Deep Tuning (Production Settings)</h3><p>HNSW (Hierarchical Navigable Small World) is the most widely used ANN algorithm. You must tune three critical parameters:</p><p><strong>1. M (Graph Connectivity)</strong></p><ul><li>Higher M = Higher recall, but higher memory usage.</li><li><em>Production value:</em> M = 32</li></ul><p><strong>2. efConstruction</strong></p><p>Controls index quality.</p><ul><li>Higher = Better recall, but slower indexing.</li><li><em>Recommended:</em> 400–800</li></ul><p><strong>3. efSearch</strong></p><p>Controls runtime search quality.</p><ul><li>Higher = Better recall, but higher latency.</li><li><em>Production strategy:</em> Create cost-aware retrieval tiers (e.g., Premium users → efSearch=256; Free users → efSearch=64).</li></ul><h3>4️⃣ Industry-Standard Technologies (2026)</h3><p>Common production vector databases include:</p><ul><li><strong>Pinecone</strong> (Managed, enterprise-ready)</li><li><strong>Weaviate</strong></li><li><strong>Milvus</strong></li><li><strong>Qdrant</strong></li><li><strong>Elasticsearch / OpenSearch</strong> (Hybrid search)</li><li><strong>FAISS</strong> (Self-hosted, research-grade)</li></ul><p>Selection heavily depends on compliance requirements, budget, dataset size and hybrid search needs.</p><h3>5️⃣ Hybrid Search (Enterprise Precision Pattern)</h3><pre>Query ├──► BM25 (Keyword Search)<br>      └──► Vector Search (HNSW)<br>                │<br>          Results Merge<br>                ↓<br>            Reranker<br>                ↓<br>               LLM</pre><p>Vector search captures semantic similarity. BM25 captures exact keywords.</p><p>Combined improvement: <strong>Precision increases 12–25%.</strong></p><p>Widely used in legal search, enterprise document systems and financial AI platforms.</p><h3>6️⃣ Benchmarking Framework (How FAANG Teams Measure)</h3><p>Never deploy without benchmarking.</p><p><strong>Offline Metrics</strong></p><ul><li>Recall@k, MRR, nDCG</li><li><em>Target:</em> Recall@10 &gt; 0.90</li></ul><p><strong>Online Metrics</strong></p><pre>| Metric        | Target       |<br>|---------------|-------------|<br>| P50 Latency   | &lt; 30 ms     |<br>| P95 Latency   | &lt; 100 ms    |<br>| P99 Latency   | &lt; 150 ms    |<br>| Throughput    | 1K–10K QPS  |<br>| Error Rate    | &lt; 0.1%      |</pre><p><strong>Memory Calculation Example</strong></p><p>For 1M vectors (768 dimensions, float32):</p><ul><li>768 × 4 bytes = 3,072 bytes/vector</li><li>≈ 3GB per 1M vectors</li><li>HNSW overhead: +30–50%</li><li><strong>Total: 4–5GB per 1M vectors</strong></li></ul><p><em>Optimization:</em> Use Product Quantization to reduce footprint to ~1GB.</p><h3>7️⃣ Enterprise Security &amp; Compliance Standards</h3><p>Production vector systems must support:</p><p><strong>Data Protection:</strong></p><ul><li>AES-256 encryption at rest</li><li>TLS 1.3 in transit</li><li>VPC isolation &amp; Private endpoints</li><li>RBAC &amp; Namespace isolation</li></ul><p><strong>Compliance:</strong></p><p>SOC 2 Type II, ISO 27001, GDPR, HIPAA (Healthcare), PCI-DSS (Fintech).</p><p><strong>Critical Rule:</strong> Never store raw PII inside embeddings. Mask or tokenize before indexing.</p><h3>8️⃣ Cost Optimization Model</h3><p>Cost sources include Embedding APIs, Storage, Compute and Network.</p><p><strong>Optimization strategies:</strong></p><p>✔ Batch embeddings</p><p>✔ Use smaller embedding models</p><p>✔ Quantization</p><p>✔ Redis / semantic caching</p><p>✔ Auto-scaling replicas</p><p>✔ Dynamic efSearch tuning</p><p><strong>Production goal:</strong> &lt;$0.002 per query</p><h3>9️⃣ Real Production Case Study</h3><p><strong>The Setup:</strong></p><ul><li>Dataset: 10M documents</li><li>Embedding: 768-dim</li><li>Infrastructure: 3 nodes</li></ul><p><strong>Before optimization:</strong></p><ul><li>P95 latency: 180ms</li><li>Recall@10: 0.82</li></ul><p><strong>After tuning:</strong></p><ul><li>M = 32, efSearch = 128</li><li>Hybrid search enabled</li><li>Cross-encoder reranker added</li></ul><p><strong>Results:</strong></p><ul><li>P95 latency: 78ms</li><li>Recall@10: 0.94</li><li>Cost per query ↓ 27%</li></ul><h3>Common Production Mistakes</h3><p>❌ Using default HNSW parameters</p><p>❌ No recall benchmarking</p><p>❌ Ignoring rerankers</p><p>❌ No tenant isolation</p><p>❌ Embedding raw PII</p><p>❌ No monitoring</p><h3>Final Thoughts</h3><p>Vector databases are not just storage. They are the intelligence backbone of production RAG systems.</p><p>If optimized correctly:</p><p>You reduce hallucinations. You reduce latency. You reduce cost. You increase trust.</p><p><strong>What vector database are you currently using in your stack? Let me know in the comments below!</strong> <em>If you found this technical breakdown helpful, follow me for my next deep dive on RAG vs Agents vs Fine-Tuning.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc2f468042d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build & Deploy a Production LLM API (FastAPI + Docker + Scaling Guide)]]></title>
            <link>https://medium.com/@george03glyn/build-deploy-a-production-llm-api-fastapi-docker-scaling-guide-5bf6b1976080?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf6b1976080</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 20:43:21 GMT</pubDate>
            <atom:updated>2026-02-16T20:51:34.623Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Design, Deploy, and Scale Real-World LLM Services for Production</strong></p><p><strong>SEO Keywords:</strong> Production LLM Deployment, FastAPI AI Backend, Deploy LLM API, Scalable ML System, LLM in Production, Docker AI Deployment, Generative AI Backend, AI System Design, MLOps for LLM, Production AI Architecture</p><h3>🚀 Why Most LLM APIs Fail in Production</h3><p>Many developers successfully build LLM demos, but production systems fail due to:</p><ul><li>High latency</li><li>Uncontrolled costs</li><li>Poor scalability</li><li>No security or rate limiting</li><li>Unstable deployments</li><li>No monitoring or logging</li></ul><p>A real-world AI system must be <strong>scalable, secure, observable, and cost-efficient</strong> — not just functional.</p><p>In this guide, we will design and deploy a <strong>production-grade LLM API</strong> using FastAPI, Docker, and scalable architecture patterns used in real-world AI platforms.</p><h3>What You Will Build</h3><p>A production-ready LLM backend capable of:</p><ul><li>Serving AI responses via REST API</li><li>Handling concurrent users</li><li>Streaming responses in real-time</li><li>Deploying using Docker</li><li>Scaling for production workloads</li><li>Monitoring cost, latency, and performance</li></ul><h3>Real-World LLM System Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yauHa3BbC36wj5VQ26WbRg.png" /></figure><p><strong>Client → API Layer → LLM Service → Cache / Queue → Monitoring</strong></p><h3>Key Components</h3><ul><li><strong>FastAPI</strong> — High-performance async API framework</li><li><strong>LLM Engine</strong> — OpenAI / Local / Hosted model</li><li><strong>Redis / Cache</strong> — Reduce repeated inference cost</li><li><strong>Queue (Optional)</strong> — Handle heavy workloads</li><li><strong>Docker</strong> — Containerized deployment</li><li><strong>Monitoring</strong> — Track latency, tokens, and errors</li></ul><p>This architecture ensures scalability, reliability, and performance.</p><h3>Step 1 — Build the FastAPI LLM Endpoint</h3><pre>from fastapi import FastAPI<br>from openai import OpenAI<br><br>app = FastAPI()<br>client = OpenAI()</pre><pre>@app.post(&quot;/generate&quot;)<br>async def generate(prompt: str):<br>    response = client.chat.completions.create(<br>        model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]<br>    )<br>    return {&quot;response&quot;: response.choices[0].message.content}</pre><p>This creates a simple AI API endpoint.</p><h3>Step 2 — Enable Async &amp; Concurrent Requests</h3><p>FastAPI supports async processing, allowing multiple users to use the AI simultaneously.</p><pre>@app.post(&quot;/chat&quot;)<br>async def chat(prompt: str):<br>    result = await llm_call(prompt)<br>    return {&quot;response&quot;: result}</pre><p>Async improves throughput and reduces blocking latency.</p><h3>Step 3 — Streaming Responses (Real-Time UX)</h3><p>Streaming improves user experience and reduces perceived latency.</p><pre>from fastapi.responses import StreamingResponse</pre><pre>@app.post(&quot;/stream&quot;)<br>async def stream(prompt: str):<br>    def generate():<br>        for chunk in llm_stream(prompt):<br>            yield chunk<br>    return StreamingResponse(generate(), media_type=&quot;text/plain&quot;)</pre><p>Streaming is critical for chat applications and copilots.</p><h3>Step 4 — Dockerize the AI Service</h3><p>Create a <strong>Dockerfile</strong>:</p><pre>FROM python:3.10<br><br>WORKDIR /app<br>COPY . /app<br><br>RUN pip install -r requirements.txt<br><br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Build &amp; run:</p><pre>docker build -t llm-api .<br>docker run -p 8000:8000 llm-api</pre><p>Containerization ensures reproducibility and easy deployment.</p><h3>Step 5 — Scaling the LLM API</h3><p>Production systems must handle:</p><ul><li>High traffic</li><li>Multiple users</li><li>Heavy inference load</li></ul><h3>Scaling Options</h3><p><strong>Horizontal Scaling</strong></p><ul><li>Run multiple API containers</li><li>Load balance using Nginx / Cloud LB</li></ul><p><strong>GPU / Inference Scaling</strong></p><ul><li>Use GPU for local models</li><li>Batch requests for efficiency</li></ul><p><strong>Queue-Based Scaling</strong></p><ul><li>Use Redis / RabbitMQ for heavy workloads</li><li>Process jobs asynchronously</li></ul><p><strong>Kubernetes (Advanced)</strong></p><ul><li>Auto-scale based on traffic</li><li>Self-healing deployments</li></ul><h3>Step 6 — Cost Optimization</h3><p>LLM usage can become expensive without optimization.</p><p>Best practices:</p><ul><li>Cache repeated queries</li><li>Use smaller models when possible</li><li>Limit max tokens</li><li>Compress prompts</li><li>Use batching for embeddings/inference</li><li>Monitor token usage per request</li></ul><p>Cost control is essential for real-world AI systems.</p><h3>Step 7 — Security &amp; Production Safety</h3><p>A production AI API must be secure.</p><p>Add:</p><ul><li>API authentication (JWT / API key)</li><li>Rate limiting</li><li>Prompt injection protection</li><li>Input validation</li><li>Abuse monitoring</li><li>Secure logging (no sensitive data)</li></ul><h3>Step 8 — Monitoring &amp; Observability</h3><p>Track:</p><ul><li>Latency per request</li><li>Token usage</li><li>Error rate</li><li>Response time</li><li>Throughput</li><li>Cost per user</li></ul><p>Tools:</p><ul><li>Prometheus + Grafana</li><li>OpenTelemetry</li><li>Cloud monitoring dashboards</li></ul><p>Observability separates <strong>prototype vs production systems</strong>.</p><h3>Step 9 — Production Checklist</h3><p>Before deploying:</p><ul><li>Async API enabled</li><li>Streaming implemented</li><li>Dockerized</li><li>Rate limiting added</li><li>Authentication enabled</li><li>Logging configured</li><li>Monitoring active</li><li>Caching implemented</li><li>Cost tracking enabled</li><li>Load tested</li></ul><p>If all checked → production-ready.</p><h3>Real-World Applications</h3><p>This architecture powers:</p><ul><li>AI SaaS platforms</li><li>Chatbots &amp; copilots</li><li>RAG systems</li><li>Enterprise AI assistants</li><li>Document intelligence systems</li><li>AI automation platforms</li></ul><p>Most modern AI products rely on scalable LLM APIs.</p><h3>Conclusion</h3><p>Building an LLM model is easy — <strong>building a production AI system is engineering</strong>.</p><p>A real-world AI backend must be:</p><ul><li>Scalable</li><li>Secure</li><li>Observable</li><li>Cost-efficient</li><li>Reliable</li></ul><p>By combining FastAPI, Docker, async processing, and scalable architecture, you can transform simple AI prototypes into <strong>enterprise-grade AI platforms</strong>.</p><h3>Want to Build Production AI Systems?</h3><p>I design and build <strong>production-ready Generative AI, LLM, and RAG systems</strong> with scalable architecture, deployment, and optimization.</p><p>Open to:</p><ul><li>Freelance AI projects</li><li>Consulting &amp; system design</li><li>Production AI deployment</li></ul><p>Let’s connect 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf6b1976080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Production-Ready RAG Chatbot with LangChain (Step-by-Step)]]></title>
            <link>https://medium.com/@george03glyn/build-a-production-ready-rag-chatbot-with-langchain-step-by-step-a85f3def32ac?source=rss-f2c3bc2a367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85f3def32ac</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[George Glyn]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 18:08:03 GMT</pubDate>
            <atom:updated>2026-02-14T18:27:03.029Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Design, Deploy, and Scale a Real-World Generative AI System Using Retrieval-Augmented Generation</strong></p><p><strong>SEO Keywords:</strong> Retrieval-Augmented Generation, RAG Chatbot, LangChain Tutorial, Generative AI, Production LLM Architecture, Enterprise AI, Semantic Search, Vector Database, FastAPI Deployment, End-to-End RAG Pipeline, Context-Aware AI</p><h3>🚀 Why Most AI Chatbots Fail in Production</h3><p>Most LLM applications fail in real-world environments because they hallucinate, lack access to fresh or private data, and cannot reason over domain-specific knowledge. Traditional language models rely only on training data, which becomes outdated and unreliable for enterprise use.</p><p><strong>Retrieval-Augmented Generation (RAG)</strong> solves this problem by combining semantic search, real-time knowledge retrieval, and LLM reasoning to produce grounded and accurate responses.</p><p>This architecture powers modern enterprise copilots, intelligent search systems, and production-grade AI assistants.</p><h3>What You Will Build</h3><p>A scalable, context-aware AI assistant capable of:</p><ul><li>Reading PDFs and documents</li><li>Converting text into embeddings</li><li>Storing vectors in a semantic database</li><li>Retrieving relevant context for each query</li><li>Generating grounded responses using an LLM</li><li>Deploying as a production-ready API</li></ul><h3>Tech Stack</h3><ul><li>Python</li><li>LangChain</li><li>OpenAI / LLM</li><li>FAISS / Pinecone</li><li>FastAPI</li><li>Docker</li><li>Cloud (AWS / Azure)</li></ul><h3>System Architecture</h3><p><strong>Indexing Pipeline (Offline)</strong><br> Documents → Cleaning → Chunking → Embeddings → Vector Database</p><p><strong>Query Pipeline (Online)</strong><br> User Query → Vector Search → Retrieve Context → LLM → Final Response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpFwq_a5tl_4wdBGR4M-Eg.png" /></figure><h3>Why This Architecture Works</h3><ul><li>Chunking preserves semantic meaning and improves retrieval accuracy</li><li>Embeddings enable semantic search instead of keyword matching</li><li>Retrieval before generation reduces hallucination</li><li>Separate indexing and query pipelines allow independent scaling and optimization</li></ul><h3>Step 1: Document Processing</h3><pre>documents = load_documents(&quot;data/&quot;)<br>chunks = split_text(documents, chunk_size=800, overlap=100)</pre><p>Best Practices:</p><ul><li>Clean noisy text</li><li>Use semantic chunking</li><li>Preserve context</li></ul><h3>Step 2: Create Embeddings</h3><pre>from langchain.embeddings import OpenAIEmbeddings<br>embedding_model = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;)<br>vectors = embedding_model.embed_documents(chunks)</pre><p>Better embeddings → Better retrieval → Better answers</p><h3>Step 3: Store in Vector Database</h3><pre>from langchain.vectorstores import FAISS<br>vector_db = FAISS.from_documents(chunks, embedding_model)</pre><p>FAISS: fast, local, cost-effective<br>Pinecone / Weaviate: scalable production solutions</p><h3>Step 4: Retrieval + Context-Aware Generation</h3><pre>docs = vector_db.similarity_search(query, k=4)<br>context = &quot;\n&quot;.join([d.page_content for d in docs])<br>response = llm.invoke(context + &quot;\nQuestion: &quot; + query)</pre><p>This produces factual, domain-aware, and reliable answers grounded in real data.</p><h3>Step 5: Deploy as a Production API</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.post(&quot;/chat&quot;)<br>def chat(query: str):<br>    docs = vector_db.similarity_search(query, k=4)<br>    context = &quot;\n&quot;.join([d.page_content for d in docs])<br>    answer = llm.invoke(context + &quot;\nQuestion: &quot; + query)<br>    return {&quot;response&quot;: answer}</pre><p>Production Features:</p><ul><li>REST API integration</li><li>Dockerized deployment</li><li>Cloud scalability</li><li>Easy integration with applications</li></ul><h3>RAG vs Fine-Tuning</h3><p>Feature RAG Fine-Tuning Uses external data Yes No Hallucination Low Medium Real-time updates Easy Requires retraining Cost Lower long-term Higher Domain knowledge Strong Moderate Speed Medium Fast Best for Knowledge systems Behavior tuning</p><p><strong>Best Production Setup:</strong> RAG combined with lightweight fine-tuning.</p><h3>Evaluation: Measuring System Quality</h3><p>Key Metrics:</p><ul><li>Retrieval Accuracy</li><li>Faithfulness (grounded answers)</li><li>Hallucination Rate</li><li>Latency per query</li><li>Token cost per request</li><li>Human evaluation</li></ul><p>A good RAG system balances accuracy, speed, and cost.</p><h3>Cost Optimization</h3><ul><li>Embed documents once and reuse</li><li>Cache frequent queries</li><li>Batch embeddings for large datasets</li><li>Use smaller retrieval models when possible</li><li>Compress and deduplicate chunks</li></ul><h3>Security and Enterprise Considerations</h3><ul><li>Data privacy and secure document handling</li><li>Authentication and role-based access control</li><li>Prompt injection protection</li><li>Rate limiting and abuse prevention</li><li>Encrypted vector storage</li></ul><h3>Advanced Production Optimizations</h3><ul><li>Hybrid Search (vector + keyword)</li><li>Reranking models for better context selection</li><li>Guardrails and hallucination detection</li><li>Chunk tuning for improved retrieval</li><li>Monitoring and logging</li><li>Kubernetes autoscaling</li></ul><h3>Performance Optimization</h3><ul><li>Async FastAPI for concurrency</li><li>Streaming LLM responses</li><li>Background document indexing</li><li>GPU or quantized inference</li><li>Vector database sharding</li></ul><h3>Real-World Applications</h3><ul><li>Enterprise Knowledge Assistants</li><li>AI Copilots</li><li>Customer Support AI</li><li>Legal / Medical AI Systems</li><li>Document Intelligence Platforms</li><li>Internal Automation Systems</li></ul><p>RAG is the foundation of modern LLM-powered applications.</p><h3>Conclusion</h3><p>Retrieval-Augmented Generation transforms unreliable language models into production-grade AI systems grounded in real data. By combining semantic search with LLM reasoning, RAG dramatically improves accuracy, reliability, and trust.</p><p>Mastering RAG is essential for engineers building scalable, enterprise-grade Generative AI systems. With proper evaluation, optimization, and deployment, this architecture can scale from a simple prototype to a full production AI platform.</p><p>If this guide helped you, follow me on Medium for more real-world AI/ML system design tutorials.</p><p>I regularly publish production-level guides on:</p><ul><li>RAG Systems</li><li>LLM Engineering</li><li>AI Architecture</li><li>MLOps &amp; Scaling AI</li></ul><p>Clap 👏 and share to support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85f3def32ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>