<?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 shivam on Medium]]></title>
        <description><![CDATA[Stories by shivam on Medium]]></description>
        <link>https://medium.com/@shivamcode21?source=rss-bf867c4752cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b35efrBZ5JAATQm7</url>
            <title>Stories by shivam on Medium</title>
            <link>https://medium.com/@shivamcode21?source=rss-bf867c4752cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:53:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivamcode21/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[Part 4 — From Retrieved Knowledge to Rich Agent Responses]]></title>
            <link>https://medium.com/@shivamcode21/part-4-from-retrieved-knowledge-to-rich-agent-responses-cbd45ecd2d73?source=rss-bf867c4752cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbd45ecd2d73</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[data-enrichment]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[shivam]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 07:58:08 GMT</pubDate>
            <atom:updated>2026-10-19T07:58:08.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xW6FlNU9zjyeiu7ij7mDcA.png" /></figure><h4>Finding the right information is only half the job</h4><p>In the previous article, we explored how raw data can be transformed into agent-ready knowledge.</p><p>We discussed data sources, normalization, enrichment, indexing, retrieval, and ranking.</p><p>But there is another important question:</p><p><strong>Once an AI agent finds the right information, how should it present that information to the user?</strong></p><p>Imagine a customer asks:</p><p>“Can you recommend black running shoes under ₹5,000 in size 9?”</p><p>The agent searches the product catalog and finds three matching products.</p><p>At this point, the retrieval process has done its job.</p><p>But returning three raw database records is not a good user experience.</p><p>The customer doesn’t want to read product IDs, internal attributes, inventory fields, or database structures.</p><p>They want useful recommendations that help them make a decision.</p><p>This is where response generation becomes important.</p><p>In this article, we’ll explore how an AI agent turns retrieved information into clear, useful, and structured responses.</p><h4>1. Retrieval results are not user responses</h4><p>Let’s say a product search service returns this record:</p><pre>{<br>  &quot;product_id&quot;: &quot;PROD-1024&quot;,<br>  &quot;title&quot;: &quot;Men&#39;s Running Shoes&quot;,<br>  &quot;color&quot;: &quot;Black&quot;,<br>  &quot;size&quot;: &quot;9&quot;,<br>  &quot;price&quot;: 4299,<br>  &quot;currency&quot;: &quot;INR&quot;,<br>  &quot;availability&quot;: &quot;in_stock&quot;,<br>  &quot;brand&quot;: &quot;Example Brand&quot;,<br>  &quot;description&quot;: &quot;Lightweight running shoes designed for everyday training.&quot;<br>}</pre><p>This is useful information for an application.</p><p>But imagine showing this JSON directly to a customer.</p><p>It contains the right information, but it doesn’t communicate naturally.</p><p>The agent needs to transform this record into something more helpful:</p><p><strong>Men’s Running Shoes</strong></p><ul><li>Price: ₹4,299</li><li>Color: Black</li><li>Size: 9</li><li>Availability: In stock</li></ul><p>Lightweight shoes suitable for everyday training.</p><p>This is a simple example, but it highlights an important distinction:</p><ul><li>Retrieval finds relevant information.</li><li>Response generation turns that information into something useful for the user.</li></ul><p>These responsibilities should work together, but they are not the same thing.</p><h4>2. Give the agent structured information, not just text</h4><p>One common mistake is to send retrieved information to an LLM as a large block of unstructured text.</p><p>A better approach is to preserve the structure of the information.</p><p>For example, instead of sending:</p><pre>Men&#39;s Running Shoes, Black, Size 9,<br>Price 4299 INR, In Stock,<br>Lightweight running shoes for everyday training.</pre><p>Send a structured record:</p><pre>{<br>  &quot;id&quot;: &quot;PROD-1024&quot;,<br>  &quot;name&quot;: &quot;Men&#39;s Running Shoes&quot;,<br>  &quot;attributes&quot;: {<br>    &quot;color&quot;: &quot;Black&quot;,<br>    &quot;size&quot;: &quot;9&quot;<br>  },<br>  &quot;price&quot;: {<br>    &quot;amount&quot;: 4299,<br>    &quot;currency&quot;: &quot;INR&quot;<br>  },<br>  &quot;availability&quot;: &quot;in_stock&quot;,<br>  &quot;description&quot;: &quot;Lightweight running shoes for everyday training.&quot;<br>}</pre><p>Why does this matter?</p><p>Because structured information makes it easier for the agent to:</p><ul><li>Understand individual attributes.</li><li>Compare multiple records.</li><li>Identify missing information.</li><li>Follow user constraints.</li><li>Generate consistent responses.</li><li>Pass reliable information to other application components.</li></ul><p>It also makes the system easier to extend.</p><p>The same idea works beyond ecommerce.</p><p>A travel agent can receive structured hotel records. An IT support agent can receive structured ticket information. A finance operations agent can receive structured transaction records.</p><p>The domain changes, but the principle stays the same.</p><h4>3. The agent needs to understand what the user actually wants</h4><p>Not every user wants the same kind of response.</p><p>Consider these questions:</p><p><strong>Question A:</strong> “Find me black running shoes under ₹5,000.”</p><p>The user wants recommendations.</p><p><strong>Question B:</strong> “Is this product available in size 9?”</p><p>The user wants a direct availability answer.</p><p><strong>Question C:</strong> “Compare these three products.”</p><p>The user wants a comparison.</p><p><strong>Question D:</strong> “Show me the cheapest option.”</p><p>The user wants a ranking based on price.</p><p>All four questions may use the same product catalog and retrieval service.</p><p>But the response should be different.</p><p>This means response generation should consider more than just the retrieved records.</p><p>It should consider:</p><ol><li>What the user asked.</li><li>What information was retrieved.</li><li>What constraints were applied.</li><li>What type of answer is expected.</li><li>What information is still missing.</li></ol><p>The agent should not blindly summarize everything it receives.</p><p>It should select the information that helps answer the actual question.</p><h4>4. Separate answer generation from response presentation</h4><p>There is an important design decision when building an AI agent engine.</p><p>The content of an answer and the way that answer is displayed are two different concerns.</p><p>For example, the agent may determine that three products are relevant and prepare the following information:</p><pre>{<br>  &quot;response_type&quot;: &quot;product_recommendations&quot;,<br>  &quot;message&quot;: &quot;I found three options that match your requirements.&quot;,<br>  &quot;items&quot;: [<br>    {<br>      &quot;id&quot;: &quot;PROD-1024&quot;,<br>      &quot;name&quot;: &quot;Men&#39;s Running Shoes&quot;,<br>      &quot;price&quot;: 4299,<br>      &quot;currency&quot;: &quot;INR&quot;,<br>      &quot;availability&quot;: &quot;in_stock&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;PROD-1058&quot;,<br>      &quot;name&quot;: &quot;Lightweight Running Shoes&quot;,<br>      &quot;price&quot;: 3899,<br>      &quot;currency&quot;: &quot;INR&quot;,<br>      &quot;availability&quot;: &quot;in_stock&quot;<br>    }<br>  ]<br>}</pre><p>This is a structured response.</p><p>A web application could display it as product cards.</p><p>A mobile application could display it in a different layout.</p><p>A messaging application could convert it into a simple text message.</p><p>An API consumer could process the JSON directly.</p><p>The underlying information remains the same.</p><p>Only the presentation changes.</p><p>This separation is useful because it prevents the agent’s reasoning and business logic from becoming tightly coupled to a particular user interface.</p><p><strong>The agent should decide what to communicate. The application should decide how to display it.</strong></p><h4>5. Rich responses are more than formatted text</h4><p>A good AI agent should not always return a paragraph.</p><p>Depending on the task, a response might contain:</p><ul><li>Text explanations.</li><li>Product cards.</li><li>Comparison tables.</li><li>Images.</li><li>Links to relevant records.</li><li>Order status details.</li><li>Suggested next actions.</li><li>Structured API data.</li></ul><p>Let’s take a product recommendation example.</p><p>Instead of returning:</p><p>“I found three running shoes. The first costs ₹4,299, the second costs ₹3,899, and the third costs ₹4,599.”</p><p>The application could display three product cards containing:</p><ul><li>Product name.</li><li>Actual product image, when available.</li><li>Price.</li><li>Selected attributes.</li><li>Availability.</li><li>A link to view the product.</li></ul><p>This makes the interaction easier to understand.</p><p>The same approach applies to other domains.</p><p>An IT support agent might display a ticket summary with its current status and priority.</p><p>A travel agent might display hotel options with prices, ratings, and location details.</p><p>A customer support agent might display an order summary with delivery status and relevant actions.</p><p>The important point is that the response format should match the task.</p><h4>6. Never let the LLM invent application data</h4><p>This is one of the most important parts of building reliable agent responses.</p><p>Suppose a product record contains:</p><pre>{<br>  &quot;id&quot;: &quot;PROD-1024&quot;,<br>  &quot;name&quot;: &quot;Men&#39;s Running Shoes&quot;,<br>  &quot;price&quot;: 4299,<br>  &quot;image_url&quot;: &quot;https://example.com/images/shoes-1024.jpg&quot;<br>}</pre><p>The agent can explain the product and recommend it.</p><p>But it should not invent a different product ID, price, availability status, or image URL.</p><p>These values should come from trusted application data.</p><p>A safer design is:</p><ol><li>Retrieve actual records from the search system.</li><li>Give the LLM the relevant information for reasoning and explanation.</li><li>Preserve stable record IDs in the response.</li><li>Let the application resolve images, links, and other display details from authoritative records.</li><li>Verify information that may change, such as price and availability, before important actions.</li></ol><p>For example, the LLM may decide that PROD-1024 is a good recommendation.</p><p>The application then uses that ID to load the actual product image and product link.</p><p>This avoids depending on the LLM to generate URLs or other values that must be correct.</p><p>If an image is unavailable, the application should simply display the product without one.</p><p>A missing image is better than an invented image.</p><h4>7. Keep responses grounded in retrieved information</h4><p>An AI agent should be able to explain what it found, but it should also know what it did not find.</p><p>Suppose a customer asks:</p><p>“Is this shoe waterproof?”</p><p>The retrieved product record contains information about color, size, material, and price, but nothing about waterproofing.</p><p>The agent should not assume that the shoe is waterproof just because it is designed for running.</p><p>It should respond honestly:</p><p>“I couldn’t find waterproofing information in the available product details. Would you like me to help you check another option?”</p><p>This is better than producing a confident but unsupported answer.</p><p>A useful response-generation process should follow a few basic rules:</p><ul><li>Use retrieved information as the source of factual claims.</li><li>Respect the filters and constraints applied during retrieval.</li><li>Do not fill missing fields with guesses.</li><li>Clearly communicate uncertainty.</li><li>Ask a follow-up question when essential information is missing.</li></ul><p>The goal is not to make every answer sound confident.</p><p>The goal is to make every answer useful and trustworthy.</p><h4>8. A reusable response-generation flow</h4><p>We can now bring these ideas together.</p><p>A reusable AI Agent Engine can follow this general process:</p><pre>User Message<br>     |<br>     v<br>Understand User Intent<br>     |<br>     v<br>Execute Relevant Capability<br>     |<br>     v<br>Retrieve and Rank Information<br>     |<br>     v<br>Prepare Structured Context<br>     |<br>     v<br>Generate Response Content<br>     |<br>     v<br>Validate Response Data<br>     |<br>     v<br>Build Response for Application<br>     |<br>     v<br>Display to User</pre><p>Each stage has a clear responsibility.</p><p><strong>Understand User Intent</strong></p><p>Identify what the user is asking and what kind of result they expect.</p><p><strong>Execute Relevant Capability</strong></p><p>Select the appropriate capability and run its required operations.</p><p><strong>Retrieve and Rank Information</strong></p><p>Find relevant records and prioritize them using user constraints and business rules.</p><p><strong>Prepare Structured Context</strong></p><p>Pass the relevant records and conversation context to the response-generation stage.</p><p><strong>Generate Response Content</strong></p><p>Create a natural explanation based on the available information.</p><p><strong>Validate Response Data</strong></p><p>Check that important IDs, prices, availability, and other application values are grounded in trusted sources.</p><p><strong>Build Response for Application</strong></p><p>Prepare a structured response that the consuming application can render.</p><p>This approach keeps the overall system reusable while allowing different applications to provide their own presentation.</p><h4>9. Why this matters for a domain-agnostic Agent Engine</h4><p>Let’s step back and look at the bigger picture.</p><p>We started with the idea of building an engine that can support different domains.</p><p>That means we should avoid designing the entire response system around one specific application.</p><p>A commerce agent may need product cards.</p><p>A travel agent may need hotel and flight options.</p><p>An IT support agent may need ticket summaries and troubleshooting steps.</p><p>A finance operations agent may need transaction summaries and structured reports.</p><p>These applications have different response requirements.</p><p>But they share a common foundation:</p><ul><li>Understand what the user needs.</li><li>Gather relevant information.</li><li>Prepare that information in a structured way.</li><li>Generate a useful explanation.</li><li>Return a response that the application can present.</li></ul><p>This is why response generation and presentation should be treated as reusable parts of the engine, with domain-specific information and rendering handled separately.</p><h4>Conclusion</h4><p>Building a useful AI agent doesn’t end when the correct information is retrieved.</p><p>The agent must turn that information into a response that is understandable, relevant, and grounded in actual data.</p><p>We have explored how structured context, response generation, validation, and presentation work together to make that possible.</p><p>The larger lesson is:</p><p><strong>Good retrieval helps an agent find the right information. Good response design helps the user make sense of it.</strong></p><p>In the next article, we’ll explore another important part of agent-ready knowledge: <strong>how images and other media can become useful sources of information for AI agents.</strong></p><p>Because sometimes, the information an agent needs is not available in text alone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbd45ecd2d73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3 — From Raw Data to Agent-Ready Knowledge]]></title>
            <link>https://medium.com/@shivamcode21/part-3-from-raw-data-to-agent-ready-knowledge-637d86c79d0c?source=rss-bf867c4752cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/637d86c79d0c</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[shivam]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 11:55:23 GMT</pubDate>
            <atom:updated>2026-10-12T11:55:23.147Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building the knowledge layer that turns application data into reliable inputs for an AI Agent Engine</h4><p>In the previous article, we moved from the abstract AI Agent Engine architecture to a concrete real-time ecommerce agent.</p><p>We separated routing, Capability Modules, state, tools, actions, retrieval, resolution, and rendering.</p><p>That gives the agent a structure for <strong>how to operate</strong>.</p><p>But there is another question:</p><blockquote><strong><em>What information should the agent operate on?</em></strong></blockquote><p>This is where many AI systems become unreliable.</p><p>A model can have excellent orchestration and still produce poor results when the underlying data is:</p><ul><li>inconsistent</li><li>poorly structured</li><li>difficult to search</li><li>missing useful attributes</li><li>disconnected from the source of truth</li><li>mixed together without clear semantics</li></ul><p>Raw application data is not automatically agent-ready knowledge.</p><p>A production agent usually needs a data pipeline that transforms source records into representations optimized for:</p><ul><li>semantic understanding</li><li>structured filtering</li><li>ranking</li><li>entity resolution</li><li>response generation</li><li>deterministic business rules</li></ul><p>The basic transformation looks like:</p><pre>Raw Application Data<br>        ↓<br>Source Adapters<br>        ↓<br>Normalization<br>        ↓<br>Canonical Knowledge Model<br>        ↓<br>Metadata Enrichment<br>        ↓<br>Search Document<br>        ↓<br>Indexing<br>        ↓<br>Retrieval + Filtering + Ranking<br>        ↓<br>Agent-Ready Knowledge</pre><p>The important idea is that <strong>the search index is not the source of truth</strong>.</p><p>It is a derived representation of the source data, designed for the way an AI agent needs to retrieve information.</p><blockquote><em>In this article, we will move from raw records to searchable knowledge and look at the code patterns that make that pipeline reliable.</em></blockquote><h4>1. Raw Application Data Is Designed for Applications, Not Agents</h4><p>Most systems already have data.</p><p>An ecommerce platform has products.</p><p>A support system has incidents and knowledge articles.</p><p>A booking platform has availability and reservations.</p><p>A recruiting system has candidates and job descriptions.</p><p>But application data is usually optimized for transactions and storage, not semantic retrieval.</p><p>Imagine a product record like this:</p><pre>{<br>  &quot;id&quot;: 48192,<br>  &quot;title&quot;: &quot;Relaxed Fit Cotton Overshirt - Olive&quot;,<br>  &quot;body_html&quot;: &quot;&lt;p&gt;A lightweight overshirt...&lt;/p&gt;&quot;,<br>  &quot;product_type&quot;: &quot;Overshirts&quot;,<br>  &quot;vendor&quot;: &quot;Example Brand&quot;,<br>  &quot;tags&quot;: &quot;olive, cotton, casual, menswear&quot;,<br>  &quot;variants&quot;: [<br>    {<br>      &quot;id&quot;: 9001,<br>      &quot;price&quot;: &quot;2499.00&quot;,<br>      &quot;option1&quot;: &quot;M&quot;,<br>      &quot;available&quot;: true<br>    },<br>    {<br>      &quot;id&quot;: 9002,<br>      &quot;price&quot;: &quot;2499.00&quot;,<br>      &quot;option1&quot;: &quot;L&quot;,<br>      &quot;available&quot;: false<br>    }<br>  ],<br>  &quot;images&quot;: [<br>    {&quot;src&quot;: &quot;https://example.com/image-1.jpg&quot;}<br>  ]<br>}</pre><p>This is perfectly reasonable application data.</p><p>But the agent may need to answer:</p><blockquote><em>“Show me relaxed cotton overshirts in olive, under ₹3,000, preferably something casual.”</em></blockquote><p>That request contains multiple concepts:</p><ul><li>product type</li><li>material</li><li>color</li><li>style</li><li>price constraint</li><li>ranking preference</li></ul><p>The raw record does not necessarily expose those concepts in a consistent representation.</p><p>The first problem is therefore not vector search.</p><p>The first problem is <strong>data representation</strong>.</p><h4>2. The First Step: Normalize Everything</h4><p>Different source systems expose different schemas.</p><p>Even two versions of the same API can represent the same concept differently.</p><pre>Source A<br>price = &quot;2499.00&quot;<br> <br>Source B<br>price = 2499<br> <br>Source C<br>minimum_price = 2499<br>maximum_price = 2999<br> <br>Source D<br>variants = [...]</pre><p>If the agent runtime has to understand all four formats, the runtime becomes tightly coupled to the source systems.</p><p>Instead, normalize first.</p><p>A normalized model might look like:</p><pre>from dataclasses import dataclass, field<br>from typing import Any, Optional<br> <br> <br>@dataclass<br>class NormalizedProduct:<br>    id: str<br>    title: str<br>    handle: str<br> <br>    product_type: str<br>    vendor: str<br> <br>    tags: list[str] = field(default_factory=list)<br>    colors: list[str] = field(default_factory=list)<br>    sizes: list[str] = field(default_factory=list)<br> <br>    price_min: float = 0.0<br>    price_max: float = 0.0<br> <br>    image_url: str = &quot;&quot;<br>    product_url: str = &quot;&quot;<br> <br>    in_stock: bool = False<br>    description: str = &quot;&quot;<br> <br>    variants: list[dict[str, Any]] = field(default_factory=list)<br> <br>    created_at: Optional[str] = None<br>    updated_at: Optional[str] = None</pre><p>Now the rest of the system does not care where the data came from.</p><p>The source adapter’s job is:</p><pre>External Schema<br>      ↓<br>Source Adapter<br>      ↓<br>NormalizedProduct</pre><p>The agent engine works with the normalized representation.</p><h4>3. Normalization Is More Than Renaming Fields</h4><p>A useful normalization layer should also calculate things the agent will repeatedly need.</p><p>For example:</p><ul><li>price ranges</li><li>inventory state</li><li>available sizes</li><li>available colors</li><li>cleaned descriptions</li><li>canonical URLs</li><li>normalized tags</li><li>variant summaries</li></ul><p>Here is a simplified example:</p><pre>import re<br> <br> <br>def normalize_product(raw: dict, base_url: str) -&gt; NormalizedProduct:<br>    variants = raw.get(&quot;variants&quot;, [])<br> <br>    prices = []<br>    for variant in variants:<br>        price = variant.get(&quot;price&quot;)<br>        if price is None:<br>            continue<br> <br>        try:<br>            prices.append(float(price))<br>        except (TypeError, ValueError):<br>            continue<br> <br>    price_min = min(prices) if prices else 0.0<br>    price_max = max(prices) if prices else 0.0<br> <br>    tags = raw.get(&quot;tags&quot;, [])<br>    if isinstance(tags, str):<br>        tags = [<br>            tag.strip()<br>            for tag in tags.split(&quot;,&quot;)<br>            if tag.strip()<br>        ]<br> <br>    in_stock = any(<br>        bool(variant.get(&quot;available&quot;))<br>        for variant in variants<br>    )<br> <br>    body_html = raw.get(&quot;body_html&quot;) or &quot;&quot;<br>    description = re.sub(r&quot;&lt;[^&gt;]+&gt;&quot;, &quot; &quot;, body_html)<br>    description = re.sub(r&quot;\s+&quot;, &quot; &quot;, description).strip()<br> <br>    handle = raw.get(&quot;handle&quot;, &quot;&quot;)<br> <br>    return NormalizedProduct(<br>        id=str(raw.get(&quot;id&quot;)),<br>        title=raw.get(&quot;title&quot;, &quot;&quot;),<br>        handle=handle,<br>        product_type=raw.get(&quot;product_type&quot;, &quot;&quot;),<br>        vendor=raw.get(&quot;vendor&quot;, &quot;&quot;),<br>        tags=tags,<br>        price_min=price_min,<br>        price_max=price_max,<br>        product_url=f&quot;{base_url.rstrip(&#39;/&#39;)}/products/{handle}&quot;,<br>        in_stock=in_stock,<br>        description=description[:500],<br>        variants=variants,<br>    )</pre><p>The real implementation may contain more schema-specific logic for options, variants, metadata, images, and source quirks.</p><p>The important design decision is not the exact helper function.</p><p>It is this:</p><blockquote><strong><em>Normalize once, then make the rest of the system consume the normalized model.</em></strong></blockquote><p>That keeps source-specific complexity outside the agent runtime.</p><h4>4. Keep the Canonical Entity Separate From the Search Representation</h4><p>This is one of the most important ideas in the entire pipeline.</p><p>The system should have at least two representations:</p><pre>Canonical Entity<br>      |<br>      +---- Source-of-truth fields<br>      +---- Full variants<br>      +---- Full metadata<br>      +---- Transactional data<br>      +---- Stable IDs<br>      |<br>      ↓<br>Search Representation<br>      |<br>      +---- Searchable text<br>      +---- Filterable attributes<br>      +---- Ranking signals<br>      +---- Display references</pre><p>The canonical entity answers:</p><blockquote><em>“What is the actual record?”</em></blockquote><p>The search representation answers:</p><blockquote><em>“How should this record be discovered?”</em></blockquote><p>These are different questions.</p><p>A search index should therefore not replace the database or source system.</p><p>It should point back to a stable entity identity.</p><p>For example:</p><pre>document_id = f&quot;{tenant_id}_{entity.id}&quot;</pre><p>The exact identifier strategy can differ, but the principle should remain:</p><blockquote><strong><em>Every searchable document must map back to a canonical entity.</em></strong></blockquote><p>That becomes extremely important later when the LLM selects a result.</p><h4>5. Think About Data in Three Different Dimensions</h4><p>A common mistake is trying to put every field into one giant text blob.</p><p>Instead, classify the data.</p><p><strong>Data type:</strong> Semantic fields<br><strong>Examples:</strong> title, description, material, style, features<br><strong>Primary purpose:</strong> semantic matching</p><p><strong>Data type:</strong> Structured fields<br><strong>Examples:</strong> price, stock, category, segment<br><strong>Primary purpose:</strong> filtering and deterministic rules</p><p><strong>Data type:</strong> Canonical/display fields<br><strong>Examples:</strong> ID, URL, images, variants<br><strong>Primary purpose:</strong> resolution and rendering</p><p>Consider:</p><blockquote><em>“Show me black products under ₹2,000 that are currently available.”</em></blockquote><p>The semantic part might be:</p><blockquote><em>black products</em></blockquote><p>The structured constraints are:</p><pre>price &lt;= 2000<br>in_stock = true</pre><p>The agent should not expect semantic similarity alone to enforce those conditions.</p><p>This leads to a useful rule:</p><blockquote><strong><em>Use semantic search to find what is relevant. Use structured filters to enforce what is true.</em></strong></blockquote><h4>6. Build a Searchable Knowledge Model</h4><p>Once the entity is normalized, create a search-oriented document.</p><p>A simplified representation might look like:</p><pre>def to_search_document(<br>    product: NormalizedProduct,<br>    tenant_id: str,<br>) -&gt; dict:<br>    content = {<br>        &quot;title&quot;: product.title,<br>        &quot;description&quot;: product.description,<br>        &quot;category&quot;: product.product_type,<br>        &quot;brand&quot;: product.vendor,<br>        &quot;tags&quot;: product.tags,<br>        &quot;colors&quot;: product.colors,<br>        &quot;sizes&quot;: product.sizes,<br>        &quot;price_min&quot;: product.price_min,<br>        &quot;price_max&quot;: product.price_max,<br>        &quot;in_stock&quot;: product.in_stock,<br>    }<br> <br>    metadata = {<br>        &quot;entity_id&quot;: product.id,<br>        &quot;tenant_id&quot;: tenant_id,<br>        &quot;handle&quot;: product.handle,<br>        &quot;product_url&quot;: product.product_url,<br>        &quot;image_url&quot;: product.image_url,<br>        &quot;variants&quot;: product.variants,<br>    }<br> <br>    return {<br>        &quot;id&quot;: f&quot;{tenant_id}_{product.id}&quot;,<br>        &quot;content&quot;: content,<br>        &quot;metadata&quot;: metadata,<br>    }</pre><p>Notice the separation.</p><h4>Search content</h4><p>The content is designed for discovery.</p><h4>Metadata</h4><p>The metadata is designed for filters, resolution, and rendering.</p><p>This separation gives you much more control over the search layer.</p><h4>7. Not Every Field Belongs in the Embedding</h4><p>This is where search quality starts becoming an engineering problem.</p><p>Suppose we build one giant string:</p><pre>Title + description + variants + URLs + internal IDs + inventory + all metadata + everything else</pre><p>It may technically work.</p><p>But it is not necessarily a good semantic representation.</p><p>The embedding should emphasize information that helps answer:</p><blockquote><em>“Is this entity relevant to this query?”</em></blockquote><p>For example:</p><pre>def build_searchable_text(product: NormalizedProduct) -&gt; str:<br>    parts = [<br>        f&quot;Product: {product.title}&quot;,<br>        f&quot;Category: {product.product_type}&quot;,<br>        f&quot;Brand: {product.vendor}&quot;,<br>    ]<br> <br>    if product.colors:<br>        parts.append(<br>            f&quot;Colors: {&#39; &#39;.join(product.colors)}&quot;<br>        )<br> <br>    if product.sizes:<br>        parts.append(<br>            f&quot;Sizes: {&#39; &#39;.join(product.sizes)}&quot;<br>        )<br> <br>    if product.tags:<br>        parts.append(<br>            f&quot;Tags: {&#39; &#39;.join(product.tags)}&quot;<br>        )<br> <br>    if product.description:<br>        parts.append(<br>            f&quot;Description: {product.description[:300]}&quot;<br>        )<br> <br>    return &quot; | &quot;.join(filter(None, parts))</pre><p>Now the semantic representation is intentional.</p><p>We are not embedding everything.</p><p>We are building a <strong>retrieval-oriented view</strong> of the entity.</p><h4>8. Structured Metadata Should Be First-Class</h4><p>Some information is better represented structurally.</p><p>For example:</p><pre>{<br>  &quot;price_min&quot;: 1499,<br>  &quot;price_max&quot;: 1999,<br>  &quot;in_stock&quot;: true,<br>  &quot;category&quot;: &quot;overshirts&quot;,<br>  &quot;segment&quot;: &quot;men&quot;<br>}</pre><p>That lets the retrieval layer do something like:</p><pre>results = await search_index.search(<br>    query=&quot;casual cotton overshirt&quot;,<br>    filters={<br>        &quot;price_max&quot;: 2000,<br>        &quot;in_stock&quot;: True,<br>        &quot;segment&quot;: &quot;men&quot;,<br>    },<br>)</pre><p>The architectural separation is:</p><pre>Natural Language<br>      ↓<br>Query Understanding<br>      ↓<br>Semantic Query + Structured Filters<br>      ↓<br>Retrieval</pre><p>This is much more reliable than asking an LLM to inspect ten semantic results and manually decide whether each one is under budget or in stock.</p><h4>9. Raw Attributes Are Often Not Enough</h4><p>Even after normalization, source data can still be too weak for semantic retrieval.</p><p>Imagine these titles:</p><pre>&quot;AB-4720 Olive&quot;<br>&quot;AB-4720 Black&quot;<br>&quot;AB-4720 Beige&quot;</pre><p>A human may understand that the shared product line is important.</p><p>The raw fields may not expose it as a first-class attribute.</p><p>This is where <strong>metadata enrichment</strong> becomes useful.</p><p>You can create additional structured attributes such as:</p><pre>base_product_name<br>product_line<br>color<br>material<br>category<br>subcategory<br>occasion<br>style<br>vibe<br>segment<br>pattern<br>fit</pre><p>The key is not to generate arbitrary prose.</p><p>The key is to turn useful unstructured signals into <strong>controlled structure</strong>.</p><h4>10. Use the LLM at Ingestion Time, Not Only at Query Time</h4><p>This is one of the strongest patterns in the implementation.</p><p>Instead of making the online agent repeatedly interpret the same raw catalog record, use an LLM during ingestion to extract structured attributes.</p><pre>Raw Entity<br>     ↓<br>LLM Extraction<br>     ↓<br>Structured Attributes<br>     ↓<br>Persist<br>     ↓<br>Search Index</pre><p>A simplified extractor might return:</p><pre>{<br>  &quot;base_product_name&quot;: &quot;overshirt&quot;,<br>  &quot;product_line&quot;: &quot;relaxed fit&quot;,<br>  &quot;color&quot;: &quot;olive&quot;,<br>  &quot;material&quot;: &quot;cotton&quot;,<br>  &quot;category&quot;: &quot;topwear&quot;,<br>  &quot;subcategory&quot;: &quot;overshirt&quot;,<br>  &quot;style&quot;: [&quot;casual&quot;],<br>  &quot;occasion&quot;: [&quot;everyday&quot;],<br>  &quot;segment&quot;: &quot;men&quot;<br>}</pre><p>Now the query-time agent does not have to rediscover these facts.</p><h4>11. Make LLM Extraction Structured</h4><p>The model should return a constrained structure rather than free-form prose.</p><p>For example:</p><pre>from dataclasses import dataclass, field<br>from typing import Optional<br> <br> <br>@dataclass<br>class ExtractedAttributes:<br>    base_product_name: str = &quot;&quot;<br>    product_line: Optional[str] = None<br>    color: Optional[str] = None<br>    material: Optional[str] = None<br> <br>    category: Optional[str] = None<br>    subcategory: Optional[str] = None<br> <br>    occasion: list[str] = field(default_factory=list)<br>    style: list[str] = field(default_factory=list)<br> <br>    segment: Optional[str] = None</pre><p>And the prompt should define clear rules:</p><pre>Extract structured attributes.<br> <br>Rules:<br>- Normalize string values to lowercase.<br>- Return null when a scalar cannot be determined.<br>- Return [] when an array cannot be determined.<br>- Use only values from the provided taxonomy.<br>- Prefer explicit source metadata over inference.<br>- Do not invent values.<br>- Return JSON only.</pre><p>The exact prompt can vary by domain.</p><p>The architectural principle is:</p><blockquote><strong><em>Use the LLM to enrich the representation, then persist that representation so the online agent does not have to rediscover it every time.</em></strong></blockquote><h4>12. Why a Taxonomy Matters</h4><p>Without controlled vocabulary, enrichment becomes inconsistent.</p><p>One entity might be classified as:</p><pre>casual</pre><p>Another as:</p><pre>everyday casual</pre><p>Another as:</p><pre>casualwear</pre><p>Semantic search may tolerate this.</p><p>Structured filtering usually does not.</p><p>A taxonomy creates an allowed vocabulary.</p><p>For example:</p><pre>category<br> ├── topwear<br> ├── bottomwear<br> ├── footwear<br> └── accessories<br> <br>style<br> ├── casual<br> ├── formal<br> ├── minimal<br> └── sporty</pre><p>The taxonomy can be stored as configuration rather than hard-coded into the runtime.</p><p>That gives you:</p><pre>Domain Configuration<br>        ↓<br>Extraction Rules<br>        ↓<br>Normalized Attributes<br>        ↓<br>Search Metadata</pre><p>This is another way to keep the engine reusable across domains.</p><h4>13. Source Data Should Win When It Is Explicit</h4><p>A generated attribute should not silently become more authoritative than an explicit source field.</p><p>Suppose the source system explicitly says:</p><pre>{<br>  &quot;gender&quot;: &quot;Women&quot;<br>}</pre><p>But the model infers:</p><pre>unisex</pre><p>The deterministic source value should win.</p><p>The code should enforce that.</p><p>A simplified example:</p><pre>def resolve_segment(<br>    extracted_segment: str | None,<br>    source_metadata: dict,<br>) -&gt; str | None:<br>    explicit = (<br>        source_metadata.get(&quot;target_gender&quot;)<br>        or source_metadata.get(&quot;gender&quot;)<br>        or &quot;&quot;<br>    ).strip().lower()<br> <br>    if explicit in {&quot;men&quot;, &quot;women&quot;}:<br>        return explicit<br> <br>    return extracted_segment</pre><p>This illustrates a broader rule:</p><blockquote><strong><em>LLM inference can enrich data, but deterministic source data should remain authoritative when it exists.</em></strong></blockquote><h4>14. Keep the Search Layer Provider-Independent</h4><p>At this point, we have a useful internal representation.</p><p>We should not immediately tie it to one search provider.</p><p>A provider-independent interface can look like:</p><pre>class SearchIndex:<br>    async def upsert(<br>        self,<br>        documents: list[dict],<br>    ) -&gt; None:<br>        ...<br> <br>    async def search(<br>        self,<br>        query: str,<br>        filters: dict | None = None,<br>        limit: int = 10,<br>    ) -&gt; list[dict]:<br>        ...</pre><p>This gives us a clean architecture:</p><pre>Normalized Knowledge<br>        ↓<br>Search Document<br>        ↓<br>SearchIndex Interface<br>        ↓<br>Provider Adapter<br>        ↓<br>Vector / Full-text / Hybrid Engine</pre><p>The implementation can then use:</p><ul><li>vector search</li><li>full-text search</li><li>hybrid search</li><li>database search</li><li>a hosted search service</li></ul><p>The engine should not care which one is underneath.</p><h4>15. Vector Search Is One Part of Retrieval</h4><p>Semantic search is useful when the user expresses an idea rather than an exact keyword.</p><p>For example:</p><blockquote><em>“Something I can wear for a relaxed weekend lunch.”</em></blockquote><p>There may be no literal field containing the phrase “relaxed weekend lunch.”</p><p>Semantic search can still find plausible candidates.</p><p>But semantic search should not be expected to enforce every hard constraint.</p><p>A better retrieval pipeline is:</p><pre>User Request<br>      ↓<br>Query Understanding<br>      ↓<br>Semantic Query<br>+ Structured Filters<br>      ↓<br>Candidate Retrieval<br>      ↓<br>Business Ranking<br>      ↓<br>Final Results</pre><p>This is much closer to how production retrieval systems should be designed.</p><h4>16. Hybrid Search Often Makes More Sense Than Pure Vector Search</h4><p>Consider the query:</p><blockquote><em>“iPhone 15 case black”</em></blockquote><p>Part of the request is semantic.</p><p>Part is exact.</p><p>A pure vector search may retrieve conceptually similar cases.</p><p>A keyword or exact-match layer can help preserve important lexical signals.</p><p>That is why a hybrid strategy is often useful:</p><pre>Query<br>                   |<br>          +--------+--------+<br>          |                 |<br>          v                 v<br>     Semantic Search    Keyword Search<br>          |                 |<br>          +--------+--------+<br>                   |<br>                   v<br>             Candidate Set<br>                   |<br>                   v<br>                 Ranking</pre><p>A concrete implementation can expose the balance as configuration rather than hard-code it into the agent.</p><p>For example:</p><pre>results = await search_index.search(<br>    query=query,<br>    filters=filters,<br>    semantic_weight=0.7,<br>    reranking=True,<br>)</pre><p>The important part is not the number.</p><p>It is that retrieval strategy is an explicit system concern.</p><h4>17. Business Rules Belong After Retrieval</h4><p>Suppose semantic retrieval returns:</p><pre>Product A — highly relevant — out of stock<br>Product B — highly relevant — in stock<br>Product C — relevant — in stock<br>Product D — highly relevant — wrong segment<br>Product E — relevant — in stock</pre><p>A semantic engine has done its job.</p><p>It found relevant candidates.</p><p>But relevance is not the same as usefulness.</p><p>A business-aware ranking stage can apply:</p><pre>Relevance<br>Availability<br>Price constraints<br>Priority<br>Recency<br>Domain rules<br>Inventory<br>Popularity</pre><p>The architecture becomes:</p><pre>Candidates<br>   ↓<br>Business Reranker<br>   ├── relevance<br>   ├── availability<br>   ├── constraints<br>   ├── priority<br>   └── domain rules<br>   ↓<br>Final Results</pre><p>This separation prevents business logic from disappearing inside a prompt.</p><h4>18. Search Metadata Should Also Support Ranking</h4><p>The search document should carry useful signals.</p><p>For example:</p><pre>{<br>  &quot;price_min&quot;: 1499,<br>  &quot;price_max&quot;: 1999,<br>  &quot;in_stock&quot;: true,<br>  &quot;variant_availability_pct&quot;: 82.5,<br>  &quot;bestseller&quot;: true,<br>  &quot;category&quot;: &quot;topwear&quot;,<br>  &quot;segment&quot;: &quot;men&quot;<br>}</pre><p>Now the ranking layer can reason over structured data.</p><p>This is much easier to test than a prompt that says:</p><blockquote><em>“Prefer products that are available and popular.”</em></blockquote><p>A good design makes ranking inputs explicit.</p><h4>19. Write Search Documents in Batches</h4><p>Production ingestion rarely means one entity.</p><p>It means hundreds, thousands, or millions.</p><p>So indexing should be batched.</p><p>For example:</p><pre>async def index_documents(<br>    search_index: SearchIndex,<br>    documents: list[dict],<br>    batch_size: int = 100,<br>):<br>    for start in range(0, len(documents), batch_size):<br>        batch = documents[start:start + batch_size]<br>        await search_index.upsert(batch)</pre><p>Batching helps control:</p><ul><li>memory</li><li>network overhead</li><li>API request counts</li><li>retry scope</li><li>failure isolation</li></ul><p>The production implementation can make batch size configurable and change it independently of the knowledge model.</p><h4>20. Do Not Recompute Expensive Enrichment Unnecessarily</h4><p>Once LLM enrichment enters the ingestion pipeline, cost becomes a concern.</p><p>Imagine a catalog with 50,000 products.</p><p>A nightly full re-run that sends all 50,000 products through an LLM is wasteful if only 20 products changed.</p><p>This is why derived representations need change detection.</p><p>A simple pattern is:</p><pre>Source Entity<br>     ↓<br>Deterministic Content Hash<br>     ↓<br>Compare with Indexed Hash<br>     ↓<br>Changed?<br>  /      \<br>No       Yes<br> |         |<br>Skip     Re-process</pre><p>For example:</p><pre>import hashlib<br>import json<br> <br> <br>def content_hash(product: NormalizedProduct) -&gt; str:<br>    source_fields = {<br>        &quot;title&quot;: product.title,<br>        &quot;product_type&quot;: product.product_type,<br>        &quot;vendor&quot;: product.vendor,<br>        &quot;tags&quot;: sorted(product.tags),<br>        &quot;colors&quot;: sorted(product.colors),<br>        &quot;sizes&quot;: sorted(product.sizes),<br>        &quot;price_min&quot;: product.price_min,<br>        &quot;price_max&quot;: product.price_max,<br>        &quot;description&quot;: product.description,<br>        &quot;image_url&quot;: product.image_url,<br>    }<br> <br>    payload = json.dumps(<br>        source_fields,<br>        sort_keys=True,<br>        default=str,<br>    )<br> <br>    return hashlib.md5(<br>        payload.encode(&quot;utf-8&quot;)<br>    ).hexdigest()</pre><p>Then:</p><pre>if existing_hash == current_hash:<br>    skip_product()<br>else:<br>    reprocess_product()</pre><p>This simple mechanism can make a huge difference for large catalogs.</p><h4>21. Separate Semantic Changes From Operational Changes</h4><p>Not every field change should trigger expensive semantic reprocessing.</p><p>Inventory is a good example.</p><p>A product can move from:</p><pre>inventory = 10</pre><p>to:</p><pre>inventory = 9</pre><p>without changing its semantic identity.</p><p>If the semantic representation is:</p><pre>&quot;Black cotton overshirt, relaxed fit&quot;</pre><p>there is no reason to regenerate the entire semantic representation just because inventory changed.</p><p>This suggests multiple change dimensions:</p><pre>Source Change<br>   |<br>   +---- Semantic content changed?<br>   |<br>   +---- Structured metadata changed?<br>   |<br>   +---- Operational state changed?</pre><p>A mature ingestion system can then choose the cheapest required update.</p><h4>22. The Ingestion Pipeline Becomes a Workflow</h4><p>By this point, the data path is no longer a single function.</p><p>It is a workflow:</p><pre>1. Detect Source<br>       ↓<br>2. Fetch Records<br>       ↓<br>3. Normalize<br>       ↓<br>4. Enrich<br>       ↓<br>5. Persist Derived Attributes<br>       ↓<br>6. Build Search Documents<br>       ↓<br>7. Index<br>       ↓<br>8. Cache / Publish<br>       ↓<br>9. Record Sync Status</pre><p>A simplified orchestrator might look like:</p><pre>async def ingest_catalog(<br>    source,<br>    search_index: SearchIndex,<br>    attribute_extractor,<br>):<br>    raw_items = await source.fetch_items()<br> <br>    entities = [<br>        normalize_product(item)<br>        for item in raw_items<br>    ]<br> <br>    extracted = await attribute_extractor.extract_batch(<br>        entities<br>    )<br> <br>    for entity, attrs in zip(entities, extracted):<br>        apply_attributes(entity, attrs)<br> <br>    documents = [<br>        to_search_document(entity, tenant_id=&quot;demo&quot;)<br>        for entity in entities<br>    ]<br> <br>    await search_index.upsert(documents)<br> <br>    return {<br>        &quot;processed&quot;: len(entities),<br>        &quot;indexed&quot;: len(documents),<br>    }</pre><p>This is simplified, but it reveals the architecture clearly.</p><p>The real implementation adds more concerns:</p><ul><li>retries</li><li>caching</li><li>batching</li><li>taxonomy configuration</li><li>sync logging</li><li>partial failure handling</li><li>change detection</li><li>provider adapters</li><li>status tracking</li></ul><p>The core workflow stays the same.</p><h4>23. A Real Implementation Adds a Source Factory</h4><p>When there are multiple ways to obtain the same domain data, source selection should also be a separate concern.</p><p>A simple pattern looks like:</p><pre>class SourceFactory:<br>    def __init__(self, sources: dict[str, object]):<br>        self.sources = sources<br> <br>    def get(self, source_name: str):<br>        try:<br>            return self.sources[source_name]<br>        except KeyError as exc:<br>            raise ValueError(<br>                f&quot;Unknown source: {source_name}&quot;<br>            ) from exc</pre><p>Then the orchestrator does not need to know how a particular source works:</p><pre>source = source_factory.get(&quot;catalog&quot;)<br>raw_items = await source.fetch_items()</pre><p>This is the data-side equivalent of the Factory and Registry patterns discussed in Article 1.</p><h4>24. Image Data Is Also Knowledge</h4><p>Images are another example of data that is not automatically useful to an agent.</p><p>A product may have:</p><ul><li>gallery images</li><li>diagrams</li><li>size charts</li><li>promotional images</li><li>images containing useful text</li></ul><p>An agent cannot reliably reason about all of that simply because an image URL exists.</p><p>The pipeline can therefore become:</p><pre>Product Images<br>      ↓<br>Image Discovery<br>      ↓<br>OCR / Vision Extraction<br>      ↓<br>Structured or Summarized Text<br>      ↓<br>Search Representation</pre><p>This is another reason the raw source record is not the same thing as agent-ready knowledge.</p><p>We will go deeper into image and media pipelines later in the series.</p><h4>25. The Search Index Should Be Designed for the Agent’s Questions</h4><p>Instead of asking:</p><blockquote><em>“What fields does my database have?”</em></blockquote><p>ask:</p><blockquote><em>“What questions will the agent need to answer?”</em></blockquote><p>For a product discovery capability, for example:</p><pre>What is this product?<br>What category is it?<br>What materials are available?<br>Which colors are available?<br>Is it in stock?<br>What is the price?<br>What products are similar?<br>What should I recommend for this occasion?</pre><p>That suggests data such as:</p><pre>Identity<br>Title<br>Description<br>Category<br>Subcategory<br> <br>Attributes<br>Color<br>Material<br>Size<br>Fit<br>Style<br>Occasion<br> <br>Constraints<br>Price<br>Availability<br>Segment<br> <br>Presentation<br>Images<br>URL<br>Variants<br> <br>Ranking<br>Popularity<br>Recency<br>Inventory signals</pre><p>This is what <strong>agent-ready</strong> actually means.</p><p>It does not mean:</p><blockquote><em>“We put the record into a vector database.”</em></blockquote><p>It means:</p><blockquote><strong><em>The information has been represented in a way that supports the agent’s reasoning and deterministic operations.</em></strong></blockquote><h4>26. Agent-Ready Knowledge Is a Derived Layer</h4><p>A useful mental model is:</p><pre>Source System<br>     |<br>     v<br>Canonical Data<br>     |<br>     v<br>Agent Knowledge Pipeline<br>     |<br>     +---- Normalization<br>     +---- Enrichment<br>     +---- Search representation<br>     +---- Metadata<br>     +---- Ranking signals<br>     +---- Indexing<br>     |<br>     v<br>Agent-Ready Knowledge<br>     |<br>     v<br>AI Agent</pre><p>The agent does not need to understand every quirk of the source system.</p><p>It receives a representation designed for retrieval and action.</p><p>That dramatically reduces coupling.</p><h4>27. Put the Source Adapter at the Edge</h4><p>The architecture from Article 1 emphasized domain boundaries.</p><p>The same principle applies to data.</p><p>A source adapter should absorb source-specific details.</p><pre>External Systems<br>              /     |      \<br>             /      |       \<br>        Source A Source B Source C<br>             \      |      /<br>              \     |     /<br>               v    v    v<br>              Source Adapters<br>                     |<br>                     v<br>              Normalized Model<br>                     |<br>                     v<br>              Knowledge Pipeline<br>                     |<br>                     v<br>                Search Layer</pre><p>Now the rest of the agent engine is insulated from the source schema.</p><p>That is exactly what an adapter boundary is supposed to accomplish.</p><h4>28. What the Agent Should Receive at Query Time</h4><p>After all of this work, the online agent should not need to parse raw records.</p><p>It should receive something more deliberate.</p><p>For example:</p><pre>{<br>  &quot;id&quot;: &quot;48192&quot;,<br>  &quot;title&quot;: &quot;Relaxed Fit Cotton Overshirt&quot;,<br>  &quot;category&quot;: &quot;topwear&quot;,<br>  &quot;attributes&quot;: {<br>    &quot;color&quot;: &quot;olive&quot;,<br>    &quot;material&quot;: &quot;cotton&quot;,<br>    &quot;style&quot;: [&quot;casual&quot;],<br>    &quot;segment&quot;: &quot;men&quot;<br>  },<br>  &quot;pricing&quot;: {<br>    &quot;min&quot;: 2499,<br>    &quot;max&quot;: 2499<br>  },<br>  &quot;availability&quot;: {<br>    &quot;in_stock&quot;: true,<br>    &quot;available_sizes&quot;: [&quot;M&quot;, &quot;XL&quot;]<br>  },<br>  &quot;presentation&quot;: {<br>    &quot;image_url&quot;: &quot;https://example.com/image.jpg&quot;,<br>    &quot;url&quot;: &quot;https://example.com/products/overshirt&quot;<br>  }<br>}</pre><p>Now the Capability Module can reason over a much cleaner representation.</p><p>When the agent needs authoritative details, it can resolve the entity back to the canonical source.</p><p>That gives us:</p><pre>Search Representation<br>        ↓<br>Candidate / Reference<br>        ↓<br>Entity Resolution<br>        ↓<br>Canonical Entity</pre><p>This is the bridge between the knowledge layer and the runtime architecture we designed in Part 1.</p><h4>29. A Complete Retrieval Example</h4><p>Let’s put the pieces together.</p><p>Suppose the user asks:</p><blockquote><em>“Find me a casual olive cotton overshirt under ₹3,000.”</em></blockquote><p>The request can be transformed into:</p><pre>{<br>  &quot;semantic_query&quot;: &quot;casual olive cotton overshirt&quot;,<br>  &quot;filters&quot;: {<br>    &quot;price_max&quot;: 3000,<br>    &quot;in_stock&quot;: true<br>  }<br>}</pre><p>Then:</p><pre>User Request<br>      ↓<br>Query Understanding<br>      ↓<br>Semantic Query + Filters<br>      ↓<br>Search Index<br>      ↓<br>Candidate Results<br>      ↓<br>Business Reranker<br>      ↓<br>Resolved Entities<br>      ↓<br>Capability Module<br>      ↓<br>Response</pre><p>A simplified implementation:</p><pre>query = &quot;casual olive cotton overshirt&quot;<br> <br>filters = {<br>    &quot;price_max&quot;: 3000,<br>    &quot;in_stock&quot;: True,<br>}<br> <br>candidates = await search_index.search(<br>    query=query,<br>    filters=filters,<br>    limit=20,<br>)<br> <br>ranked = rerank(<br>    candidates,<br>    user_query=query,<br>)<br> <br>final_entities = [<br>    resolve_entity(result[&quot;entity_id&quot;])<br>    for result in ranked[:5]<br>]</pre><p>Notice what is not happening.</p><p>The LLM is not inventing the products.</p><p>The LLM is not checking inventory manually.</p><p>The LLM is not resolving arbitrary URLs.</p><p>The LLM is helping interpret the request and reason about the retrieved candidates.</p><p>The surrounding system enforces the boundaries.</p><h4>30. What Happens When Data Changes?</h4><p>Agent-ready knowledge is not a one-time build.</p><p>The source data changes.</p><p>Therefore the derived knowledge must change too.</p><p>A practical update model is:</p><pre>Source Change<br>      ↓<br>Change Detection<br>      ↓<br>Determine Affected Fields<br>      ↓<br>Re-run Required Enrichment<br>      ↓<br>Update Search Representation<br>      ↓<br>Update Index<br>      ↓<br>Record Sync Result</pre><p>This is where webhooks, scheduled syncs, queues, or event-driven processing become useful.</p><p>The important concept is:</p><blockquote><strong><em>The search index is a continuously maintained derived view of the source system.</em></strong></blockquote><p>That mental model leads to much better production design.</p><h4>31. Failure Handling Is Part of the Knowledge Pipeline</h4><p>Imagine a catalog of 10,000 entities.</p><p>During ingestion:</p><ul><li>9,970 succeed</li><li>20 fail during enrichment</li><li>10 fail during indexing</li></ul><p>The pipeline should not necessarily throw away all successful work.</p><p>Instead, track failures explicitly.</p><p>For example:</p><pre>from dataclasses import dataclass<br> <br> <br>@dataclass<br>class FailedEntity:<br>    entity_id: str<br>    error: str<br> <br> <br>@dataclass<br>class IngestionResult:<br>    success_count: int<br>    failed_count: int<br>    failed_details: list[FailedEntity]</pre><p>This gives operations a real answer to:</p><blockquote><em>“What happened during the sync?”</em></blockquote><p>That is much more useful than a single boolean called success.</p><h4>32. Bound the Size of Search Documents</h4><p>Another practical problem is search-provider limits.</p><p>Large descriptions, long metadata values, or large extracted text can exceed field or document limits.</p><p>A production pipeline should therefore include a deterministic size gate.</p><p>The pattern is:</p><pre>Build Document<br>      ↓<br>Measure Serialized Size<br>      ↓<br>Within Limit?<br>   /        \<br> Yes        No<br> |           |<br>Keep      Compress / Trim<br>              |<br>              v<br>        Validate Again<br>              |<br>              v<br>             Index</pre><p>For example:</p><pre>import json<br> <br> <br>def serialized_size(content: dict) -&gt; int:<br>    return len(<br>        json.dumps(<br>            content,<br>            ensure_ascii=False,<br>            default=str,<br>        )<br>    )</pre><p>The implementation can then apply:</p><ol><li>semantic compression for long text</li><li>deterministic trimming as a fallback</li><li>final validation before indexing</li></ol><p>The important principle is:</p><blockquote><strong><em>Never assume source payloads are small enough for your search layer.</em></strong></blockquote><h4>33. Retrieval Data Has Different Lifecycles</h4><p>Not every field changes at the same speed.</p><p>You can think of data as having different lifecycles:</p><pre>Slow-changing semantic data<br>- title<br>- description<br>- material<br>- category<br> <br>Medium-changing metadata<br>- tags<br>- collections<br>- attributes<br> <br>Fast-changing operational data<br>- inventory<br>- availability<br>- price<br> <br>User/session data<br>- conversation context<br>- preferences<br>- recent interactions</pre><p>This suggests a more efficient system.</p><p>Not every change should trigger the same pipeline.</p><p>For example:</p><pre>Title changed<br>    → semantic re-enrichment<br>    → re-index<br> <br>Inventory changed<br>    → metadata update<br>    → no semantic re-enrichment<br> <br>Conversation changed<br>    → update agent state<br>    → do not touch catalog index</pre><p>Once you model these lifecycles explicitly, performance becomes much easier to reason about.</p><h4>34. The Most Important Data Boundary</h4><p>At this point, we can make a more precise statement about the relationship between data and the AI Agent Engine.</p><p>The engine needs <strong>knowledge interfaces</strong>.</p><p>The domain provides the data.</p><p>The source systems provide canonical records.</p><p>The ingestion pipeline creates a retrieval-oriented representation.</p><p>The search layer finds candidates.</p><p>The resolver connects references back to canonical entities.</p><p>So:</p><pre>Source Systems<br>      ↓<br>Domain Data Adapters<br>      ↓<br>Normalization<br>      ↓<br>Knowledge Enrichment<br>      ↓<br>Search / Retrieval Layer<br>      ↓<br>Capability Module<br>      ↓<br>AI Agent Engine</pre><p>That is the data-side equivalent of the architecture from Article 1.</p><h4>35. A Practical Reference Architecture</h4><p>Putting everything together:</p><pre>Source Systems<br>                              |<br>                              v<br>                       +--------------+<br>                       |   Adapters   |<br>                       +--------------+<br>                              |<br>                              v<br>                       +--------------+<br>                       | Normalization|<br>                       +--------------+<br>                              |<br>                              v<br>                     +------------------+<br>                     | Canonical Model  |<br>                     +------------------+<br>                              |<br>                +-------------+-------------+<br>                |                           |<br>                v                           v<br>        Structured Enrichment         Searchable Text<br>                |                           |<br>                +-------------+-------------+<br>                              |<br>                              v<br>                     +----------------+<br>                     | Search Document |<br>                     +----------------+<br>                              |<br>                              v<br>                    +-------------------+<br>                    | Search / Indexing |<br>                    +-------------------+<br>                              |<br>                              v<br>                 +------------------------+<br>                 | Retrieval + Filtering  |<br>                 | + Business Ranking     |<br>                 +------------------------+<br>                              |<br>                              v<br>                    Agent Capability<br>                              |<br>                              v<br>                       AI Agent Engine</pre><p>And the conceptual data model becomes:</p><pre>Canonical Entity<br>      |<br>      +---- Identity<br>      +---- Source Fields<br>      +---- Full Attributes<br>      +---- Operational Data<br>      |<br>      +---- Derived Knowledge<br>               |<br>               +---- Semantic Representation<br>               +---- Structured Metadata<br>               +---- Ranking Signals<br>               +---- Search Index</pre><h4>36. The Code Pattern to Remember</h4><p>Most of the article can be reduced to one pipeline:</p><pre>raw_items = await source.fetch_items()<br> <br>entities = [<br>    normalize_product(item)<br>    for item in raw_items<br>]<br> <br>attributes = await attribute_extractor.extract_batch(<br>    entities<br>)<br> <br>for entity, attrs in zip(entities, attributes):<br>    apply_attributes(entity, attrs)<br> <br>documents = [<br>    to_search_document(entity, tenant_id)<br>    for entity in entities<br>]<br> <br>await search_index.upsert(documents)</pre><p>That is the heart of the system.</p><p>Everything else is production engineering around it:</p><ul><li>retries</li><li>caching</li><li>batching</li><li>change detection</li><li>failure isolation</li><li>observability</li><li>taxonomy</li><li>provider adapters</li><li>partial updates</li><li>document size limits</li></ul><p>The goal is not to make this function larger.</p><p>The goal is to keep the responsibilities behind these steps clean.</p><h4>37. What Does “Agent-Ready” Really Mean?</h4><p>By now we can define it precisely.</p><p>Data is <strong>agent-ready</strong> when it is:</p><h4>Understandable</h4><p>The information is represented in consistent, meaningful structures.</p><h4>Searchable</h4><p>The representation supports semantic and lexical retrieval.</p><h4>Filterable</h4><p>Important constraints are represented as structured fields.</p><h4>Rankable</h4><p>Business signals are available to ranking logic.</p><h4>Resolvable</h4><p>Every result maps to a canonical entity.</p><h4>Updatable</h4><p>Changes in source data can propagate to the derived representation.</p><h4>Auditable</h4><p>The system can explain where a result came from and when it was indexed.</p><h4>Domain-aware</h4><p>The representation contains useful domain-specific knowledge without forcing the core runtime to become domain-specific.</p><p>That is a much stronger definition than:</p><blockquote><em>“We embedded the documents.”</em></blockquote><h4>38. The Big Lesson</h4><p>The quality of an AI agent is heavily influenced by the quality of the information layer underneath it.</p><p>A model cannot reliably reason over data that the system cannot reliably retrieve.</p><p>And retrieval cannot be reliable when the underlying representation is inconsistent.</p><p>That gives us a chain:</p><pre>Better Source Adapters<br>        ↓<br>Better Normalization<br>        ↓<br>Better Knowledge Representation<br>        ↓<br>Better Retrieval<br>        ↓<br>Better Agent Decisions<br>        ↓<br>Better User Experience</pre><p>The agent is only as good as the information pipeline feeding it.</p><h4>Conclusion</h4><p>In the first article, we defined the architecture of a reusable <strong>AI Agent Engine</strong>.</p><p>This article addressed the layer underneath it:</p><p><strong>How does raw application data become knowledge that the engine can actually use?</strong></p><p>The answer is not simply:</p><blockquote><em>Put the data into a vector database.</em></blockquote><p>A more reliable approach is:</p><pre>Raw Data<br>   ↓<br>Source Adapters<br>   ↓<br>Normalization<br>   ↓<br>Canonical Model<br>   ↓<br>Structured Enrichment<br>   ↓<br>Search Representation<br>   ↓<br>Semantic / Hybrid Retrieval<br>   ↓<br>Structured Filtering<br>   ↓<br>Business Ranking<br>   ↓<br>Entity Resolution<br>   ↓<br>AI Agent</pre><p>A useful rule of thumb is:</p><blockquote><strong><em>Keep canonical data authoritative. Use derived representations for discovery. Use structured metadata for constraints. Use the LLM for interpretation and enrichment — not as the source of truth.</em></strong></blockquote><p>That separation is what allows the data layer to scale without turning the agent runtime into a collection of source-specific rules.</p><h4>Final Overview:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4nsWtFn8xnll-n3bTtQVg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=637d86c79d0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 — From Architecture to a Real AI Agent]]></title>
            <link>https://medium.com/@shivamcode21/part-2-from-architecture-to-a-real-ai-agent-6b6d7d810ef8?source=rss-bf867c4752cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b6d7d810ef8</guid>
            <dc:creator><![CDATA[shivam]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 15:22:45 GMT</pubDate>
            <atom:updated>2026-10-07T15:22:45.244Z</atom:updated>
            <content:encoded><![CDATA[<h4>Turning the AI Agent Engine architecture into a real-time ecommerce system</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFAVtzbNsNwVPm6Chg3_-Q.png" /></figure><p>In Part 1, we designed the architecture of a domain-agnostic <strong>AI Agent Engine</strong>.</p><p>We deliberately stayed above implementation details. We talked about routing, Capability Modules, conversation state, retrieval, tools, actions, entity resolution, rendering, and observability.</p><p>But architecture becomes meaningful only when we build something with it.</p><p>So now we start implementing.</p><p>For the rest of this series, we will use <strong>ecommerce as our running example</strong>.</p><p>The goal is not to build a chatbot with a few ecommerce prompts.</p><p>The goal is to take the reusable Agent Engine from Part 1 and instantiate it into a <strong>real-time domain-specific AI agent</strong>.</p><p>This article is the bridge: first define the complete system, then open each boundary and implement it.</p><h4>1. Start With a Real Conversation</h4><p>Imagine the user says:</p><blockquote><strong><em>User:</em></strong><em> I’m looking for a black casual shirt under ₹2,500.</em></blockquote><p>Then:</p><blockquote><strong><em>User:</em></strong><em> Show me more.</em></blockquote><p>Then:</p><blockquote><strong><em>User:</em></strong><em> Does the second one have an M?</em></blockquote><p>Then:</p><blockquote><strong><em>User:</em></strong><em> Add it to my cart.</em></blockquote><p>Finally:</p><blockquote><strong><em>User:</em></strong><em> Where is my order?</em></blockquote><p>This tiny conversation already requires retrieval, state, entity resolution, tools, actions, routing, rendering, and observability.</p><p>That is exactly why ecommerce is a useful running example.</p><h4>2. What Are We Actually Building?</h4><p>The first thing to make clear is that we are <strong>not building an ecommerce chatbot</strong>.</p><p>We are building a reusable <strong>AI Agent Engine</strong> that can be instantiated for a specific domain.</p><p>Ecommerce is simply the first concrete domain we are using to exercise the architecture.</p><p>A useful way to think about the relationship is:</p><pre>AI Agent Engine<br>                           |<br>        +------------------+------------------+<br>        |                  |                  |<br>        v                  v                  v<br>  Ecommerce Agent     IT Support Agent    Travel Agent<br>        |                  |                  |<br>        v                  v                  v<br>   Chat / API /        Chat / API /       Chat / API /<br>   other channels      other channels     other channels</pre><p>The engine provides the common runtime:</p><pre>Router<br>  +<br>Capability Modules<br>  +<br>Conversation State<br>  +<br>Retrieval<br>  +<br>Tools<br>  +<br>Actions<br>  +<br>Entity Resolution<br>  +<br>Response / Rendering<br>  +<br>Observability</pre><p>The domain supplies the parts that are specific to the application:</p><pre>Domain<br>  ↓<br>Capabilities<br>  ↓<br>Knowledge<br>  ↓<br>External Systems<br>  ↓<br>Business Rules</pre><p>For ecommerce, that might mean product discovery, order support, cart operations, returns, product knowledge, and commerce APIs.</p><p>For another domain, the same runtime could support ticket search, incident management, travel planning, document retrieval, account operations, or other workflows.</p><p>This distinction is important because a <strong>chatbot is only one delivery interface</strong>.</p><p>The same agent can be exposed through:</p><pre>Web Chat<br>API<br>Voice<br>Messaging<br>Embedded Application<br>Other Interfaces</pre><p>The interface should not define the architecture.</p><p>The Agent Engine owns the execution model; the application provides the domain capabilities and integrations.</p><p>So the implementation target for this article is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K-UPp04K2rHHO4IySKXnA.png" /></figure><blockquote><strong><em>The Agent Engine is the reusable system. The domain agent is an instantiation of that system. The chatbot is one possible interface to it.</em></strong></blockquote><p>With that boundary established, ecommerce becomes a useful running example rather than the definition of the architecture.</p><h4>3. Ecommerce Is Our Example, Not Our Architecture</h4><p>Ecommerce gives us a compact example that exercises many agent problems:</p><p>Find products<br>Retrieval</p><p>Recommend products<br>Capability Module + Retrieval</p><p>Show me more<br>State</p><p>The second one<br>Entity Resolution</p><p>Check stock<br>Tool / authoritative data</p><p>Add to cart<br>Action</p><p>Track an order<br>Tool</p><p>Return an item<br>Tool + Action</p><p>Product cards<br>Rendering</p><p>Debug a result<br>Observability</p><p>The same engine could later support:</p><pre>AI Agent Engine<br>      |<br>      +---- Ecommerce Agent<br>      +---- IT Support Agent<br>      +---- Travel Agent<br>      +---- Recruiting Agent<br>      +---- Finance Operations Agent</pre><p>Only the domain capabilities and integrations change.</p><h4>4. What Does Real-Time Mean?</h4><p>Real-time does not simply mean “the LLM responds quickly.”</p><p>For our system, it means the runtime can process an interaction as a sequence of events:</p><pre>User Message<br>    ↓<br>Request Accepted<br>    ↓<br>Route Selected<br>    ↓<br>Capability Started<br>    ↓<br>Retrieval / Tool Calls<br>    ↓<br>Result Produced<br>    ↓<br>Response Streamed<br>    ↓<br>Conversation State Updated</pre><p>A useful event model might contain:</p><pre>request.received<br>route.selected<br>retrieval.started<br>retrieval.completed<br>tool.started<br>tool.completed<br>action.started<br>action.completed<br>response.delta<br>response.completed</pre><p>The exact event protocol can evolve later. The architectural requirement is that the conversation layer can carry both natural-language output and runtime events.</p><h4>5. Layer One: Chat / API Interface</h4><p>A production agent needs a real-time interface with clear transport boundaries.</p><p>For example, a WebSocket or API layer can handle Redis-backed session state, message-size limits, connection checks, tracing, runtime execution, and response persistence.</p><p>A simplified excerpt from the actual implementation:</p><pre>async def _receive_json_capped(websocket: WebSocket) -&gt; dict:<br>    &quot;&quot;&quot;Parse one WebSocket text frame as JSON; reject oversized payloads.&quot;&quot;&quot;<br>    text = await websocket.receive_text()<br> <br>    if len(text.encode(&quot;utf-8&quot;)) &gt; _MAX_WS_BYTES:<br>        raise ValueError(&quot;WebSocket message too large&quot;)<br> <br>    return json.loads(text)<br> <br> <br>async def _send_json_with_timeout(<br>    websocket: WebSocket,<br>    payload: Dict,<br>    *,<br>    warning_message: str,<br>    timeout_seconds: Optional[int] = None,<br>) -&gt; bool:<br>    &quot;&quot;&quot;Best-effort WebSocket send that cannot hang forever.&quot;&quot;&quot;<br>    if not _is_websocket_connected(websocket):<br>        return False<br> <br>    timeout = timeout_seconds or _WS_SEND_TIMEOUT_SECONDS<br> <br>    try:<br>        await asyncio.wait_for(<br>            websocket.send_json(payload),<br>            timeout=timeout,<br>        )<br>        return True<br>    except asyncio.TimeoutError:<br>        logger.warning(<br>            &quot;%s: send timed out after %ss&quot;,<br>            warning_message,<br>            timeout,<br>        )<br>    except WebSocketDisconnect:<br>        logger.warning(&quot;%s: client disconnected&quot;, warning_message)<br> <br>    return False</pre><p>This is an important distinction.</p><p>The interface layer is responsible for transport concerns:</p><ul><li>accepting WebSocket messages</li><li>validating message size</li><li>checking connection state</li><li>sending responses safely</li><li>managing session state</li><li>attaching client/channel context</li></ul><p>It does <strong>not</strong> contain the product-recommendation logic.</p><p>That logic enters through the Agent Engine.</p><h4>6. Layer Two: Routing</h4><p>The actual graph starts with a conversation-limit gate and then intent detection.</p><p>A graph-based runtime can express this routing explicitly using LangGraph’s StateGraph:</p><pre>builder = StateGraph(SupportState)<br> <br>builder.add_node(<br>    &quot;conversation_limit_gate&quot;,<br>    conversation_limit_gate_with_logging,<br>)<br> <br>builder.add_node(<br>    &quot;detect_intent&quot;,<br>    detect_intent_node_with_logging,<br>)<br> <br>builder.add_conditional_edges(<br>    &quot;conversation_limit_gate&quot;,<br>    route_after_limit_gate,<br>    {<br>        &quot;detect_intent&quot;: &quot;detect_intent&quot;,<br>        &quot;end&quot;: END,<br>    },<br>)</pre><p>The next routing decision is also explicit:</p><pre>builder.add_conditional_edges(<br>    &quot;detect_intent&quot;,<br>    route_to_data_collection_with_escalation,<br>    {<br>        &quot;escalation_handler&quot;: &quot;escalation_handler&quot;,<br>        &quot;data_collection_delivery&quot;: &quot;data_collection_delivery&quot;,<br>        &quot;order_intent&quot;: &quot;order_intent&quot;,<br>        &quot;product_details_intent&quot;: &quot;product_details_intent&quot;,<br>        &quot;cart_management_intent&quot;: &quot;cart_management_intent&quot;,<br>        &quot;recommendations_intent&quot;: &quot;recommendations_intent&quot;,<br>        &quot;unknown_handler&quot;: &quot;unknown_handler&quot;,<br>    },<br>)</pre><p>This is the architecture we discussed in Part 1 becoming real code:</p><pre>Incoming message<br>      ↓<br>conversation_limit_gate<br>      ↓<br>detect_intent<br>      ↓<br>route_to_data_collection_with_escalation<br>      ↓<br>specific capability / handler</pre><p>Notice that routing is not implemented as one giant LLM prompt.</p><p>The graph has explicit nodes and explicit conditional transitions.</p><p>That gives the runtime a deterministic structure around model-driven intent detection.</p><h4>7. Layer Three: Capability Modules</h4><p>This is where the reusable Capability Module pattern becomes important.</p><p>Instead of creating a separate hand-written implementation for every ecommerce capability, a runtime can use a <strong>generic capability factory</strong>.</p><p>The graph can create concrete capabilities from the shared factory:</p><pre>generic_product_details_node = create_generic_skill_node(<br>    agent_name=&quot;product_details&quot;,<br>    topic=&quot;product_inquiry&quot;,<br>    entity_type=&quot;product&quot;,<br>    legacy_fields=[<br>        &quot;product_link&quot;,<br>        &quot;inquiry_product_info&quot;,<br>        &quot;product_selection_matches&quot;,<br>    ],<br>)<br> <br>generic_order_status_node = create_generic_skill_node(<br>    agent_name=&quot;order_status&quot;,<br>    topic=&quot;order_status&quot;,<br>    entity_type=&quot;order&quot;,<br>    legacy_fields=[<br>        &quot;selected_order_id&quot;,<br>        &quot;order_status_by_id&quot;,<br>        &quot;known_orders&quot;,<br>    ],<br>    auto_ground_tool=(<br>        &quot;get_recent_orders&quot;<br>        if get_bool(&quot;ORDER_GROUNDING_ENABLED&quot;, True)<br>        else None<br>    ),<br>)<br> <br>generic_cart_management_node = create_generic_skill_node(<br>    agent_name=&quot;cart_management&quot;,<br>    topic=&quot;cart_management&quot;,<br>    entity_type=&quot;cart&quot;,<br>    legacy_fields=[],<br>)<br> <br>generic_recommendations_node = create_generic_skill_node(<br>    agent_name=&quot;recommendations&quot;,<br>    topic=&quot;product_recommendation&quot;,<br>    entity_type=&quot;product&quot;,<br>    legacy_fields=[],<br>    auto_ground_tool=(<br>        &quot;search_products&quot;<br>        if get_bool(&quot;SEARCH_GROUNDING_ENABLED&quot;, True)<br>        else None<br>    ),<br>)</pre><p>This is much closer to what a reusable Agent Engine looks like in practice.</p><p>The graph defines <strong>what capabilities exist</strong>.</p><p>The generic node factory defines <strong>how those capabilities execute</strong>.</p><p>That separation is what lets the same execution machinery support product inquiries, order status, cart management, recommendations, policy questions, and other capabilities.</p><p>The generic node itself is responsible for things such as:</p><ul><li>loading prompts</li><li>loading tools</li><li>building conversation context</li><li>invoking the model</li><li>running tool calls</li><li>extracting entities</li><li>updating context</li><li>tracking actions</li><li>tracing execution</li><li>handling errors</li></ul><p>So a Capability Module is not simply a prompt.</p><p>It is an executable runtime boundary.</p><h4>8. Product Discovery: Our First Real Capability</h4><p>For:</p><blockquote><em>“I’m looking for a black casual shirt under ₹2,500.”</em></blockquote><p>we want:</p><pre>Natural Language<br>      ↓<br>Query Understanding<br>      ↓<br>Semantic Query + Structured Constraints<br>      ↓<br>Retrieval<br>      ↓<br>Filtering<br>      ↓<br>Ranking<br>      ↓<br>Product Candidates</pre><p>For example:</p><pre>from dataclasses import dataclass<br> <br> <br>@dataclass<br>class ProductQuery:<br>    semantic_query: str<br>    filters: dict[str, object]<br>    limit: int = 10<br> <br> <br>query = ProductQuery(<br>    semantic_query=&quot;black casual shirt&quot;,<br>    filters={<br>        &quot;price_max&quot;: 2500,<br>        &quot;in_stock&quot;: True,<br>    },<br>)</pre><p>The semantic query captures relevance.</p><p>The structured filters enforce truth.</p><p>That distinction becomes critical when we build retrieval.</p><h2>9. Where Does Product Knowledge Come From?</h2><p>The capability needs information about:</p><pre>Products<br>Collections<br>Variants<br>Prices<br>Inventory<br>Images<br>Descriptions<br>Categories<br>Tags<br>Metadata</pre><p>So we need a Knowledge Layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6uIrqvV29ECXqmylajUCQ.png" /></figure><p>The runtime consumes a knowledge interface.</p><p>It should not know how a particular source system stores its records.</p><p>The deep dive into normalization, enrichment, indexing, and search comes in Part 3.</p><h4>10. Retrieval Is a Separate Layer</h4><p>Retrieval is not “ask the LLM which products are good.”</p><p>A first retrieval pipeline is:</p><pre>User Request<br>    ↓<br>Query Understanding<br>    ↓<br>Semantic Query + Filters<br>    ↓<br>Search Index<br>    ↓<br>Candidate Set<br>    ↓<br>Business Ranking<br>    ↓<br>Resolved Entities</pre><p>A provider-independent interface can be:</p><pre>class SearchIndex:<br>    async def search(<br>        self,<br>        query: str,<br>        filters: dict | None = None,<br>        limit: int = 10,<br>    ) -&gt; list[dict]:<br>        raise NotImplementedError</pre><p>Later this can be backed by vector, keyword, hybrid, database, or hosted search infrastructure.</p><p>The Agent Engine should not depend on one provider.</p><h4>11. Conversation State: The Difference Between Chat and an Agent</h4><p>The actual project state is richer than the small ConversationState example normally shown in tutorials.</p><p>A production agent state model should contain both operational state and structured conversation context.</p><p>For example:</p><pre>class SupportState(TypedDict, total=False):<br>    messages: List[HumanMessage]<br>    phone_number: Optional[str]<br>    client_id: Optional[str]<br>    conversation_id: Optional[str]<br> <br>    selected_order_id: Optional[str]<br>    known_orders: Optional[List[Dict]]<br>    order_status_by_id: Optional[Dict[str, str]]<br> <br>    detected_intents: Optional[List[Dict]]<br>    detected_tags: Optional[List[str]]<br>    conversation_tags: Optional[List[str]]<br> <br>    customer_message: Optional[str]<br>    type: Optional[str]<br>    response_type: Optional[str]<br> <br>    product_link: Annotated[<br>        Optional[str],<br>        deletable_field_reducer,<br>    ]<br> <br>    requested_size: Annotated[<br>        Optional[str],<br>        deletable_field_reducer,<br>    ]<br> <br>    selected_variant_id: Annotated[<br>        Optional[str],<br>        deletable_field_reducer,<br>    ]<br> <br>    cart: Optional[CartSnapshot]<br>    conversation_context: Optional[ConversationContext]</pre><p>The important part is conversation_context.</p><p>It tracks topics, entities, focal entities, customer identifiers, pending questions, and recent actions.</p><p>For example, the project defines:</p><pre>class EntityDTO(TypedDict, total=False):<br>    entity_type: str<br>    entity_id: Optional[str]<br>    entity_value: str<br>    source: str<br>    discovered_at: str<br>    summary: Optional[Dict[str, Any]]<br>    full_data: Optional[Dict[str, Any]]<br>    metadata: Optional[Dict[str, Any]]</pre><p>and:</p><pre>class FocalEntityDTO(TypedDict, total=False):<br>    entity_type: str<br>    entity_id: Optional[str]<br>    entity_value: str<br>    confidence: str<br>    set_at: str</pre><p>This is the real reason a follow-up such as:</p><blockquote><em>“Show me more.”</em></blockquote><p>can be meaningful.</p><p>The agent does not have to reconstruct the entire meaning from the latest message alone.</p><p>The conversation context carries the information required to continue the workflow.</p><h4>12. Entity Resolution: “The Second One”</h4><p>Suppose the previous response displayed:</p><pre>1. Classic Black Shirt       → product_101<br>2. Relaxed Oxford Shirt      → product_205<br>3. Casual Cotton Shirt       → product_331</pre><p>The user asks:</p><blockquote><em>“Does the second one have an M?”</em></blockquote><p>The model should not invent a product ID.</p><p>The runtime already knows:</p><pre>position 2<br>    ↓<br>product_205</pre><p>The resolver then loads the canonical entity:</p><pre>entity = await product_resolver.resolve(<br>    entity_id=&quot;product_205&quot;<br>)</pre><p>Now the system can inspect authoritative variant data.</p><p>The principle is:</p><blockquote><strong><em>Natural language can identify a reference. The system should resolve that reference to a stable entity.</em></strong></blockquote><h4>13. Tools: Reading Authoritative External Data</h4><p>The project does not hardcode tools directly inside every skill.</p><p>Tools are loaded through the tool registry used by the generic skill node:</p><pre>from fashion_bot.core.tool_registry import (<br>    aget_tools_for_agent,<br>    get_agent_config,<br>)</pre><p>Inside the generic execution layer, tools are invoked asynchronously.</p><p>The implementation supports LangChain tools as well as function-style fallbacks:</p><pre>async def _ainvoke_tool(tool: Any, tool_args: Any) -&gt; Any:<br>    tool_ainvoke = getattr(tool, &quot;ainvoke&quot;, None)<br> <br>    if callable(tool_ainvoke):<br>        try:<br>            return await tool_ainvoke(tool_args)<br>        except TypeError:<br>            pass<br> <br>    fn = (<br>        getattr(tool, &quot;coroutine&quot;, None)<br>        or getattr(tool, &quot;func&quot;, None)<br>        or getattr(tool, &quot;fn&quot;, None)<br>    )<br> <br>    if fn and callable(fn):<br>        args = tool_args if isinstance(tool_args, dict) else {}<br>        result = fn(**args)<br> <br>        if asyncio.iscoroutine(result):<br>            return await result<br> <br>        return result<br> <br>    if hasattr(tool, &quot;invoke&quot;):<br>        return await asyncio.to_thread(<br>            tool.invoke,<br>            tool_args,<br>        )<br> <br>    return await asyncio.to_thread(<br>        tool,<br>        tool_args,<br>    )</pre><p>This is a real production boundary.</p><p>The model can decide that it needs information.</p><p>The tool registry supplies the available operation.</p><p>The tool performs the external-system operation.</p><p>The result is then brought back into the agent execution loop.</p><p>The same generic mechanism can therefore support things such as:</p><pre>search_products<br>get_recent_orders<br>get_policy_information<br>order operations<br>cart operations<br>other domain-specific tools</pre><p>The important architectural rule remains:</p><blockquote><strong><em>The model decides when information is needed; the tool is responsible for obtaining authoritative information.</em></strong></blockquote><h4>14. Retrieval and Tools Solve Different Problems</h4><p>Retrieval answers:</p><blockquote><strong><em>Which entities are relevant?</em></strong></blockquote><p>Examples:</p><ul><li>products</li><li>documents</li><li>policies</li><li>destinations</li></ul><p>Tools answer:</p><blockquote><strong><em>What does the external system currently say?</em></strong></blockquote><p>Examples:</p><ul><li>order status</li><li>shipment status</li><li>current inventory</li><li>account information</li><li>appointment availability</li></ul><p>So:</p><pre>Discovery Request<br>    → Retrieval<br> <br>Order Status Request<br>    → Tool<br> <br>Policy Question<br>    → Retrieval<br> <br>Account Mutation<br>    → Action</pre><p>A mature agent uses all of these selectively.</p><h4>15. Actions: Changing the Real World</h4><p>The codebase explicitly tracks state-changing operations.</p><p>Actions can be represented as structured state:</p><pre>class ActionDTO(TypedDict, total=False):<br>    action_type: str<br>    action_name: str<br>    performed_at: str<br> <br>    parameters: Dict[str, Any]<br> <br>    success: bool<br>    result_summary: str<br> <br>    topic_id: Optional[str]</pre><p>The generic skill node also imports action helpers:</p><pre>from fashion_bot.utils.context_helpers import (<br>    is_action_tool,<br>    create_action_dto,<br>    add_action_to_context,<br>    extract_action_parameters,<br>    extract_action_result_summary,<br>)</pre><p>That gives the runtime a distinction between:</p><pre>Read operation<br>    ↓<br>Tool result<br> <br>State-changing operation<br>    ↓<br>Action<br>    ↓<br>ActionDTO stored in conversation context</pre><p>This matters for operations such as placing an order, cancelling an order, updating an order, or initiating a return.</p><p>The agent should be able to understand not only what the external system returned, but also what mutation has already happened in the conversation.</p><p>That prevents the model from treating a completed action as if it had never occurred.</p><h4>16. Deterministic Work Should Stay Deterministic</h4><p>Do not ask the model to perform work that software can perform exactly.</p><p>Bad boundary:</p><pre>LLM<br> ├── calculate price<br> ├── decide stock<br> ├── resolve product ID<br> ├── mutate cart<br> └── invent order status</pre><p>Better boundary:</p><pre>LLM<br> └── interpret intent / language<br> <br>Runtime<br> ├── routing<br> ├── validation<br> ├── state<br> └── orchestration<br> <br>Retrieval<br> └── find candidates<br> <br>Tools<br> └── read authoritative systems<br> <br>Actions<br> └── mutate authoritative systems<br> <br>Resolver<br> └── map references to canonical entities</pre><p>The model reasons.</p><p>The system enforces.</p><h4>17. Rendering: The Agent Result Is Not the UI</h4><p>A capability may return:</p><pre>[<br>    {<br>        &quot;id&quot;: &quot;product_101&quot;,<br>        &quot;title&quot;: &quot;Classic Black Shirt&quot;,<br>        &quot;price&quot;: 2199,<br>        &quot;image_url&quot;: &quot;...&quot;,<br>    }<br>]</pre><p>The UI may need:</p><pre>{<br>  &quot;type&quot;: &quot;product_card&quot;,<br>  &quot;id&quot;: &quot;product_101&quot;,<br>  &quot;title&quot;: &quot;Classic Black Shirt&quot;,<br>  &quot;price&quot;: &quot;₹2,199&quot;,<br>  &quot;image&quot;: &quot;...&quot;,<br>  &quot;actions&quot;: [<br>    &quot;view&quot;,<br>    &quot;add_to_cart&quot;<br>  ]<br>}</pre><p>The agent should not depend on a specific frontend.</p><p>So:</p><pre>Capability Result<br>       ↓<br>Entity Resolution<br>       ↓<br>Response Model<br>       ↓<br>Renderer / Channel Adapter<br>       ↓<br>Web / API / Voice / Messaging</pre><p>Rendering is another boundary.</p><h4>18. One Request, End to End</h4><p>Now we can follow an actual request through the current implementation.</p><p>Suppose the web user sends:</p><blockquote><em>“Find me a black casual shirt under ₹2,500.”</em></blockquote><p>The WebSocket layer builds the conversation state and invokes the centralized runtime.</p><p>The actual implementation uses a runtime contract:</p><pre>runtime = _get_websocket_runtime()<br>runtime_holder: Dict[str, str] = {}<br> <br>async def _execute_turn(_ctx):<br>    result, langsmith_trace_id = await invoke_graph_with_tracing(<br>        state,<br>        trace_id,<br>        user_identifier,<br>        input_message=message,<br>        trace_graph_internally=False,<br>    )<br> <br>    runtime_holder[&quot;langsmith_trace_id&quot;] = langsmith_trace_id<br> <br>    if &quot;messages&quot; in result and result[&quot;messages&quot;]:<br>        final_message = result[&quot;messages&quot;][-1]<br>        reply_text = (<br>            final_message.content<br>            if hasattr(final_message, &quot;content&quot;)<br>            else str(final_message)<br>        )<br>    elif &quot;customer_message&quot; in result:<br>        reply_text = result[&quot;customer_message&quot;]<br>    else:<br>        reply_text = &quot;&quot;<br> <br>    return RuntimeResult(<br>        handled=True,<br>        reply_text=reply_text,<br>        state_snapshot=state,<br>    ), result<br> <br>run_result = await runtime.run_turn(<br>    channel=&quot;web&quot;,<br>    client_id=client_id,<br>    user_id=user_identifier,<br>    inbound_payload={<br>        &quot;_runtime_message_text&quot;: message<br>    },<br>    execute_fn=_execute_wrapper,<br>    trace_id=trace_id,<br>)</pre><p>The graph invocation itself is real LangGraph execution:</p><pre>result = await graph.ainvoke(state)<br> <br>result = ensure_assistant_message_for_skip_final(<br>    state_before_invoke=state,<br>    result=result,<br>)</pre><p>So the actual flow is:</p><pre>WebSocket<br>   ↓<br>Redis-backed session state<br>   ↓<br>centralized runtime.run_turn()<br>   ↓<br>LangGraph graph.ainvoke()<br>   ↓<br>conversation_limit_gate<br>   ↓<br>detect_intent<br>   ↓<br>conditional routing<br>   ↓<br>generic skill / handler<br>   ↓<br>tools + context updates<br>   ↓<br>LangGraph result<br>   ↓<br>WebSocket response</pre><p>This is much closer to the implementation we are actually documenting.</p><p>It also shows why the architecture is larger than the LLM call itself.</p><h4>19. “Show Me More” Is a State Problem</h4><p>The second request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qjW-DExAWUZuTtrpymH5A.png" /></figure><p>The user did not repeat the original search.</p><p>State supplied the missing context.</p><p>This is one of the first places where a stateless LLM wrapper stops being sufficient.</p><h4>20. “Add the Second One” Crosses Multiple Boundaries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jumu9lQ2cP0bX9BXFzwpJg.png" /></figure><p>“Second one” is not an ecommerce API concept.</p><p>It is a conversational reference.</p><p>The runtime translates it into a canonical entity before performing the action.</p><h4>21. “Where Is My Order?” Takes a Different Path</h4><pre>&quot;Where is my order?&quot;<br>       ↓<br>Order Support<br>       ↓<br>Identify order context<br>       ↓<br>Order Tool<br>       ↓<br>External System<br>       ↓<br>Authoritative status<br>       ↓<br>Response</pre><p>No product retrieval is required.</p><p>No vector search is required.</p><p>No product ranking is required.</p><p>The architecture prevents every request from being forced through the same pipeline.</p><h4>22. The Complete Runtime:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu4iNkWz9pBdBnBYUdjCSQ.png" /></figure><h4>23. The Data Side</h4><p>The runtime is only half the system.</p><p>The other half is the knowledge plane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*VYYlLvsDkyn_Pe0TwfjYng.png" /></figure><p>This gives us two major planes:</p><pre>AI AGENT SYSTEM<br> <br>        ┌───────────────────────────────┐<br>        │       Runtime Plane           │<br>        │                               │<br>        │ Router → Capabilities →       │<br>        │ State → Tools → Actions →     │<br>        │ Resolution → Rendering        │<br>        └──────────────┬────────────────┘<br>                       │<br>                       │ consumes<br>                       ▼<br>        ┌───────────────────────────────┐<br>        │       Knowledge Plane          │<br>        │                               │<br>        │ Sources → Normalize →         │<br>        │ Enrich → Index → Retrieve     │<br>        └───────────────────────────────┘</pre><p>The knowledge plane prepares information.</p><p>The runtime plane uses it.</p><h4>24. What We Need to Build</h4><p>We can now turn the architecture into an implementation checklist.</p><h4>Runtime</h4><ol><li><strong>Conversation API</strong> — accept messages and stream responses/events.</li><li><strong>Router</strong> — map requests to Capability Modules.</li><li><strong>Capability Registry</strong> — register and instantiate capabilities.</li><li><strong>Conversation State</strong> — persist context across turns.</li><li><strong>Entity Resolver</strong> — resolve conversational references to canonical entities.</li><li><strong>Tool Layer</strong> — read authoritative external systems.</li><li><strong>Action Layer</strong> — perform validated mutations.</li><li><strong>Response Model</strong> — create channel-independent agent results.</li><li><strong>Renderer</strong> — convert results into channel output.</li><li><strong>Observability</strong> — trace routing, retrieval, tools, actions, latency, and errors.</li></ol><h4>Knowledge</h4><ol><li><strong>Source Adapters</strong> — connect to domain systems.</li><li><strong>Normalization</strong> — convert source schemas into canonical models.</li><li><strong>Enrichment</strong> — create useful structured attributes.</li><li><strong>Search Representation</strong> — build semantic and structured retrieval documents.</li><li><strong>Indexing</strong> — publish the derived representation.</li><li><strong>Retrieval</strong> — find and rank candidates.</li></ol><h4>25. A Practical Implementation Structure</h4><p>The architecture can be implemented with a small set of clear boundaries:</p><pre>Agent Application<br>│<br>├── Interface Layer<br>├── Runtime<br>├── Router<br>├── Capability Modules<br>├── Conversation State<br>├── Retrieval<br>├── Tool Registry<br>├── Action Layer<br>├── Entity Resolution<br>├── Response / Rendering<br>└── Observability</pre><p>The exact directory structure is an implementation detail.</p><p>What matters is that each responsibility has a clear boundary and can evolve independently.</p><p>The following sections focus on those runtime boundaries rather than tying the architecture to a particular repository layout.</p><h4>26. The Real Agent Runtime Contract</h4><p>The project does not use the tiny AgentRuntime.handle() abstraction from a tutorial.</p><p>The real WebSocket path uses the centralized runtime contract:</p><pre>run_result = await runtime.run_turn(<br>    channel=&quot;web&quot;,<br>    client_id=client_id,<br>    user_id=user_identifier,<br>    inbound_payload={<br>        &quot;_runtime_message_text&quot;: message<br>    },<br>    execute_fn=_execute_wrapper,<br>    trace_id=trace_id,<br>)</pre><p>The runtime is deliberately outside the LangGraph itself.</p><p>That separation is useful because the runtime can handle concerns such as:</p><ul><li>channel identity</li><li>single-flight behavior</li><li>runtime metrics</li><li>Redis/database accounting</li><li>degraded mode</li><li>tracing boundaries</li></ul><p>while LangGraph handles the agent workflow.</p><p>Inside the execution callback, the graph is invoked:</p><pre>result, langsmith_trace_id = await invoke_graph_with_tracing(<br>    state,<br>    trace_id,<br>    user_identifier,<br>    input_message=message,<br>    trace_graph_internally=False,<br>)</pre><p>And invoke_graph_with_tracing() ultimately calls:</p><pre>result = await graph.ainvoke(state)</pre><p>This gives us an important architectural separation:</p><pre>Channel Runtime<br>      ↓<br>Agent Graph Runtime<br>      ↓<br>LangGraph Nodes<br>      ↓<br>Capability Execution<br>      ↓<br>Tools / External Systems</pre><p>That is a much more realistic implementation boundary than putting the entire agent into one handle() method.</p><h4>27. The Generic Capability Implementation</h4><p>A generic Capability factory can be kept small and configuration-driven:</p><pre>def create_capability(<br>    name: str,<br>    topic: str,<br>    entity_type: str,<br>    *,<br>    grounding_tool: str | None = None,<br>):<br>    return CapabilityModule(<br>        name=name,<br>        topic=topic,<br>        entity_type=entity_type,<br>        grounding_tool=grounding_tool,<br>    )<br> <br> <br>recommendations = create_capability(<br>    name=&quot;recommendations&quot;,<br>    topic=&quot;product_recommendation&quot;,<br>    entity_type=&quot;product&quot;,<br>    grounding_tool=&quot;search_products&quot;,<br>)</pre><p>The important idea is that the graph does not need to know the internal mechanics of every skill.</p><p>It registers a configured executable node.</p><p>The generic node then:</p><pre>Agent configuration<br>       ↓<br>Prompt / context loading<br>       ↓<br>Tool loading<br>       ↓<br>LLM invocation<br>       ↓<br>Tool loop<br>       ↓<br>Entity extraction<br>       ↓<br>Conversation context update<br>       ↓<br>Structured result</pre><p>A production implementation can also support native tool-calling loops and fallback behavior.</p><p>For example, the generic skill implementation binds the available tools to the model:</p><pre>tool_map = {<br>    t.name: t<br>    for t in tools<br>    if hasattr(t, &quot;name&quot;)<br>}<br> <br>bound_llm = llm.bind_tools(tools)</pre><p>And for skills that must be grounded before answering, it can force a first tool call:</p><pre>forced_first_llm = llm.bind_tools(<br>    tools,<br>    tool_choice=force_first_tool,<br>)</pre><p>This is a concrete example of the architectural principle from Part 1:</p><blockquote><strong><em>The model can reason inside a capability, but the capability controls the execution boundary.</em></strong></blockquote><h4>28. The LLM’s Role Becomes Much Clearer</h4><p>The LLM can help with:</p><pre>Intent interpretation<br>Query understanding<br>Ambiguous language<br>Reference interpretation<br>Natural-language response generation<br>Reasoning over retrieved candidates<br>Structured extraction</pre><p>The LLM should not be the authority for:</p><pre>Product existence<br>Inventory truth<br>Order status<br>Stable entity IDs<br>Cart mutation<br>Pricing truth<br>Permission checks<br>Business constraints</pre><p>A useful rule is:</p><blockquote><strong><em>Let the model interpret. Let the system verify and execute.</em></strong></blockquote><h4>29. Codebase Reality vs Tutorial Code</h4><p>There is an important lesson in exposing an AI Agent Engine publicly.</p><p>Tutorial code is useful for explaining an idea, but it can hide the engineering decisions that make the system production-ready.</p><p>Our actual implementation already contains things such as:</p><ul><li>Redis-backed conversation state</li><li>PostgreSQL graph checkpointing</li><li>WebSocket connection handling</li><li>message-size limits</li><li>timeout handling</li><li>LangSmith tracing</li><li>trace IDs</li><li>runtime metrics</li><li>tool fallback paths</li><li>LLM failover</li><li>automatic grounding tools</li><li>entity extraction</li><li>focal-entity tracking</li><li>action tracking</li><li>configurable prompts</li><li>feature flags / kill switches</li><li>error reporting</li></ul><p>For example, the recommendation capability can automatically ground itself with search_products:</p><pre>auto_ground_tool=(<br>    &quot;search_products&quot;<br>    if get_bool(&quot;SEARCH_GROUNDING_ENABLED&quot;, True)<br>    else None<br>)</pre><p>And order status can similarly use:</p><pre>auto_ground_tool=(<br>    &quot;get_recent_orders&quot;<br>    if get_bool(&quot;ORDER_GROUNDING_ENABLED&quot;, True)<br>    else None<br>)</pre><p>These are not details we should hide from readers.</p><p>They are exactly the details that show how an abstract architecture becomes a production system.</p><p>The rest of this series will therefore follow a rule:</p><blockquote><strong><em>Explain the architecture first, then show realistic implementation patterns.</em></strong></blockquote><p>When a code sample is shortened for readability, it should be clear that it is a reduced example rather than pretending that every line is required by the architecture.</p><h4>30. What We Are Deliberately Not Building Yet</h4><p>This article does not deep-dive into:</p><ul><li>embedding models</li><li>vector database configuration</li><li>chunking strategies</li><li>taxonomy design</li><li>ingestion batching</li><li>search reranking algorithms</li><li>pagination implementation details</li><li>tool authentication</li><li>cart API integration</li><li>image understanding</li><li>production tracing</li></ul><p>Those are implementation layers.</p><p>First we need the complete map.</p><p>Now we have it.</p><h4>31. Implementation Roadmap</h4><pre>PART 1<br>Architecture<br>        ↓<br>PART 2<br>From Architecture to a Real AI Agent<br>        ↓<br>PART 3<br>Knowledge Layer<br>        ↓<br>PART 4<br>Production Ecommerce Capabilities<br>        ↓<br>PART 5<br>Image &amp; Media Knowledge<br>        ↓<br>PART 6<br>Conversational Retrieval + Pagination<br>        ↓<br>PART 7<br>Tools, Actions + Real-Time Operations<br>        ↓<br>PART 8<br>Observability + Production Lessons</pre><p>We first understand the system.</p><p>Then we build the information layer.</p><p>Then we build domain capabilities.</p><p>Then we solve the harder interaction and production problems.</p><h4>32. The Complete Architecture:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xoAzKhzfinHx8pdZf44Tw.png" /><figcaption>Complete Architecure of flow</figcaption></figure><p>This is the system we will implement.</p><h4>33. The Most Important Shift</h4><p>It is tempting to say:</p><blockquote><em>“We need to build an AI chatbot.”</em></blockquote><p>That framing is too small.</p><p>What we are actually building is:</p><blockquote><strong><em>A reusable AI Agent Engine that can be instantiated into domain-specific agents.</em></strong></blockquote><p>For our running example:</p><pre>Reusable Engine<br>      ↓<br>Ecommerce Configuration<br>      ↓<br>Ecommerce Capabilities<br>      ↓<br>Ecommerce Knowledge<br>      ↓<br>Ecommerce Tools + Actions<br>      ↓<br>Real-Time Ecommerce Agent</pre><p>The chat interface is only one way users interact with it.</p><p>The same runtime could later expose an API, voice interface, messaging channel, or another application.</p><p>That is why the architecture comes first.</p><h4>Conclusion</h4><p>In Part 1, we designed the architecture.</p><p>In Part 2, we turned that architecture into a concrete engineering target.</p><p>We started with real user interactions:</p><blockquote><em>“Find me a black casual shirt under ₹2,500.”</em></blockquote><blockquote><em>“Show me more.”</em></blockquote><blockquote><em>“Does the second one have an M?”</em></blockquote><blockquote><em>“Add it to my cart.”</em></blockquote><blockquote><em>“Where is my order?”</em></blockquote><p>And mapped them to:</p><pre>Chat / API<br>    ↓<br>Router<br>    ↓<br>Capability Modules<br>    ↓<br>Knowledge / Retrieval<br>    ↓<br>Conversation State<br>    ↓<br>Entity Resolution<br>    ↓<br>Tools<br>    ↓<br>Actions<br>    ↓<br>Rendering<br>    ↓<br>Observability</pre><p>Now we know what needs to exist.</p><p>More importantly, we know <strong>where each responsibility belongs</strong>.</p><p>The next question is:</p><blockquote><strong><em>How do we turn raw application data into agent-ready knowledge?</em></strong></blockquote><p>That is where normalization, canonical models, metadata enrichment, embeddings, hybrid search, indexing, filtering, ranking, and change detection come in.</p><h4>Where This Series Goes Next</h4><p><strong>Part 1 — Building a Domain-Agnostic AI Agent Engine: Start with the Architecture</strong></p><p>The reusable runtime: routing, Capability Modules, state, tools, retrieval, actions, resolution, rendering, and observability.</p><p><strong>Part 2 — From Architecture to a Real AI Agent</strong></p><p>This article: the concrete ecommerce running example, real-time interaction model, runtime boundaries, capabilities, knowledge, retrieval, state, tools, actions, and rendering.</p><p><strong>Part 3 — From Raw Data to Agent-Ready Knowledge</strong></p><p>How source adapters, normalization, canonical models, enrichment, search representations, indexing, hybrid retrieval, filtering, ranking, and change management create the knowledge layer.</p><p><strong>Part 4 — Building Production-Grade Ecommerce Capabilities</strong></p><p>How the runtime becomes a real domain agent with discovery, recommendations, order support, returns, and other workflows.</p><p><strong>Part 5 — Building a Reliable Image &amp; Media Pipeline for AI Agents</strong></p><p>How images, OCR, media metadata, and visual information become reliable inputs for the knowledge layer.</p><p><strong>Part 6 — Designing Conversational Retrieval</strong></p><p>How stateful retrieval handles “show me more”, pagination, references, and follow-up questions deterministically.</p><p><strong>Part 7 — Tools, Actions and Real-Time Operations</strong></p><p>How agents safely read and mutate external systems such as orders, carts, returns, and other operational APIs.</p><p><strong>Part 8 — Observability and Production Lessons</strong></p><p>How tracing, attribution, failures, latency, evaluation, and production constraints shape the final system.</p><blockquote><strong><em>Next: From Raw Data to Agent-Ready Knowledge</em></strong></blockquote><p>The architecture tells us how the agent operates.</p><p>The next article builds the information layer that gives it something reliable to operate on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b6d7d810ef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Domain-Agnostic AI Agent Engine: Start with the Architecture]]></title>
            <link>https://medium.com/@shivamcode21/building-a-domain-agnostic-ai-agent-engine-start-with-the-architecture-c25e37bf2b23?source=rss-bf867c4752cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c25e37bf2b23</guid>
            <category><![CDATA[technology-agnostic]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[shivam]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 04:12:57 GMT</pubDate>
            <atom:updated>2026-10-06T04:12:57.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vM91YKdlQNWxs-PTdyD_oA.png" /></figure><p>Why production AI agents need routing, capabilities, state, retrieval, tools, and deterministic boundaries — not just an LLM and a prompt.</p><p>Most AI agent tutorials start with a model.</p><p>Connect an LLM.</p><p>Give it a few tools.</p><p>Write a prompt.</p><p>Add a chat interface.</p><p>And you have an AI chatbot.</p><p>But that is not the same thing as building an <strong>AI Agent Engine</strong>.</p><p>A production-grade agent needs to operate across capabilities, domains, data sources, tools, actions, and interaction channels. It needs to remember context, retrieve reliable information, execute deterministic operations, and prevent the model from becoming the source of truth for things it should not control.</p><p>So the architecture is much larger than:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3BS0rnpC6l_SzSTDB3lxw.png" /></figure><p>A more realistic architecture looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wjj3hE-KRfdUO3R8jNWARg.png" /></figure><h4>The LLM sits inside that system,<strong> It is not the entire system.</strong></h4><h3>What are we actually building?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jKJgKednW948Jsl-chE4A.png" /></figure><p>We are building an <strong>AI Agent Engine</strong> — a reusable runtime for building domain-specific AI applications.</p><p>The engine provides common infrastructure for:</p><ul><li>reasoning<br>• capability execution<br>• orchestration<br>• <strong>conversation state</strong><br>• tools<br>• retrieval<br>• actions<br>• interaction with external systems</li></ul><p>This distinction is important: <strong>The AI Agent Engine is not the chatbot.</strong></p><p>A chatbot is simply one application or delivery interface built on top of an agent.</p><p>The same engine could power:</p><ul><li>a web chatbot<br>• an API-based application<br>• a voice assistant<br>• a messaging assistant<br>• an internal enterprise assistant<br>• an embedded AI experience</li></ul><p>The engine provides the reusable runtime.</p><p>The application provides the domain.</p><p>That is the architecture we want to explore.</p><h3>1. Start With Architecture, Not Technology</h3><p>When people describe an agent implementation, they often start with technology names:</p><p>LangGraph + LangChain + FastAPI + Redis + a vector database + an LLM.</p><p>That is backwards.</p><p>Before choosing technologies, define what the runtime actually needs to do.</p><p>A reusable <strong>AI Agent Engine</strong> needs to answer questions such as:</p><ul><li>How is a request routed?<br>• How are different capabilities represented?<br>• How does a capability access tools?<br>• Where does <strong>conversation state</strong> live?<br>• How does the agent retrieve grounded information?<br>• How are actions separated from read-only operations?<br>• How does the system prevent the model from inventing authoritative data?<br>• How are results converted into channel-specific responses?<br>• How can a new domain be added without rewriting the runtime?</li></ul><p>Once these boundaries are clear, technology choices become implementation decisions rather than architecture decisions.</p><p>A useful mental model is: <strong>LLMs decide. Tools execute. State remembers. Search retrieves. Code enforces. The capability runtime orchestrates.</strong></p><p>This one sentence captures much of the architecture.</p><h3>2. What Is a Capability Module?</h3><p>A <strong>Capability Module</strong> is a reusable unit of agent behavior that gives an AI assistant one specific ability.</p><p>It is an architectural concept, not a framework-specific component.</p><p>For example, an agent might have capabilities such as:</p><ul><li>Product Discovery — understand what the user wants, retrieve relevant items, apply constraints, and present results.<br>• Order Support — identify an order, retrieve its status, and explain the result.<br>• Returns — determine eligibility, retrieve available options, and initiate a return when authorized.<br>• Appointment Booking — find available slots, confirm the selected slot, and create the booking.<br>• Incident Support — find a support incident, retrieve relevant knowledge, and guide the user toward resolution.</li></ul><p>The important property is that a capability can be reused, tested, composed, and replaced independently.</p><p>That makes the same runtime useful across commerce, travel, IT support, recruiting, finance, and many other domains.</p><p><strong>Capability Module</strong> vs. Implementation Technology</p><p><strong>Capability Module</strong> is the architectural concept.</p><p>In a particular implementation, that capability could be represented by:</p><ul><li>a workflow node<br>• a Python module<br>• a service<br>• a workflow component<br>• another runtime construct</li></ul><p>For example, LangGraph can be used to implement a runtime that executes capabilities.</p><p>But LangGraph does not define what a capability is.</p><p>Keeping these concepts separate makes the architecture portable.</p><h3>3. The Agent Is a Stateful Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cguSJqsKVHq3LO3fAK_gwA.png" /></figure><p>An agent conversation is rarely a single operation.</p><p>A request may require:</p><p>1. understanding the user’s intent<br>2. selecting a capability<br>3. retrieving information<br>4. calling one or more tools<br>5. reasoning over tool results<br>6. performing an action<br>7. updating <strong>conversation state</strong><br>8. resolving authoritative entities<br>9. rendering a response</p><p>That is a workflow.</p><p>The important idea is that the agent is not one giant prompt.</p><p>It is a stateful execution system.</p><h3>4. Why Model the Runtime as a Graph?</h3><p>A useful agent runtime contains branches.</p><p>For example:</p><p>Individual capabilities can also contain loops:</p><p>Representing these transitions explicitly makes the system easier to reason about.</p><p>It also gives the runtime clear places to handle:</p><ul><li>state transitions<br>• conditional routing<br>• retries<br>• tool failures<br>• tracing<br>• persistence<br>• testing<br>• human escalation</li></ul><p>A graph runtime is therefore one implementation of a broader architectural requirement:</p><p>An agent needs an explicit <strong>stateful workflow</strong> in which reasoning and deterministic operations can interact.</p><h3>5. Separate Routing From Capability Execution</h3><p>One common mistake is to put everything into one agent.</p><p>Instead, separate routing from execution.</p><p>The router answers:</p><p>“Which capability should handle this request?”</p><p>The <strong>capability module</strong> answers:</p><p>“How should this capability be executed?”</p><p>The router decides where the request goes.</p><p>The capability decides how that request is handled.</p><h3>6. A Capability Module Is an Execution Boundary</h3><p>A <strong>capability module</strong> is more than a prompt.</p><p>It coordinates several concerns:</p><p>A <strong>capability module</strong> may therefore be responsible for:</p><ul><li>loading its configuration<br>• obtaining the tools it needs<br>• building context from <strong>conversation state</strong><br>• invoking the model<br>• executing tool calls<br>• handling tool failures<br>• extracting structured updates<br>• tracking actions<br>• updating topics and entities<br>• producing resulting state</li></ul><p>The key architectural boundary is: <strong>The runtime owns orchestration. The capability module owns capability execution.</strong></p><h3>7. Tools Are the Boundary Between Reasoning and the Real World</h3><p>An LLM can reason about an operation.</p><p>It should not directly perform the operation.</p><p>Instead, tools provide an explicit boundary between reasoning and external systems.</p><p>A read tool might:</p><ul><li>search records<br>• retrieve an order<br>• fetch a policy<br>• look up availability<br>• query a knowledge base</li></ul><p>An action tool might:</p><ul><li>create a booking<br>• cancel an order<br>• initiate a return<br>• update a record<br>• schedule a task</li></ul><p>The distinction matters because actions have side effects.</p><p>They need stronger controls around:</p><ul><li>authorization<br>• validation<br>• confirmation<br>• idempotency<br>• auditing<br>• error handling</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2NjTsbyYj6IXVC4myHhcA.png" /></figure><h3>8. Factories and Registries Keep the Runtime Generic</h3><p>As the number of capabilities grows, hard-coding tools into the runtime becomes difficult to maintain.</p><p>A registry provides a mapping between a capability and its implementation.</p><p>The registry can provide:</p><ul><li>capability metadata<br>• tool factories<br>• prompts<br>• topics<br>• entity types<br>• other configuration</li></ul><p>The runtime does not need to know how every capability is implemented.</p><p>This is where the Factory Pattern and Registry Pattern become useful architectural techniques rather than just implementation details.</p><h3>9. Conversation State Is Part of the Architecture</h3><p>A stateless chatbot can answer one message.</p><p>An agent needs to understand what happened before.</p><p><strong>Conversation state</strong> may contain:</p><p>The exact state model will vary by application.</p><p>The architectural principle does not:</p><p><strong>Conversation state</strong> should be explicit and structured rather than hidden inside prompts.</p><p>This becomes particularly important for requests such as:</p><ul><li>“show me more”<br>• “what about the second one?”<br>• “cancel that”<br>• “use the same address”<br>• “book the next available slot”<br>• “compare those two”</li></ul><p>The model can interpret these requests.</p><p>But the application needs structured state to know what “that,” “those,” or “more” actually refers to.</p><h3>10. Retrieval Is a Separate Architectural Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6hzRteKg-LkjCDsfIToZA.png" /></figure><p>An LLM should not be treated as the source of truth for domain data.</p><p>If a user asks:</p><p>“Which options are available tomorrow?”</p><p>the model should not invent the answer.</p><p>The architecture should instead look like:</p><p>Retrieval answers:</p><p>“What could be relevant?”</p><p>Reranking answers:</p><p>“What should we show first?”</p><p>This distinction is useful across domains.</p><p>The <strong>retrieval layer</strong> could be implemented with:</p><p>•vector search<br>• full-text search<br>• hybrid search<br>• database-backed retrieval<br>• a domain-specific search service<br>• a combination of these</p><p>A simple provider-independent interface might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdTLSlDmZfx6zX4Zninz5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SmDJHuAkYh3M_nzqlLFug.png" /></figure><p>This is one of the most important boundaries in a production agent.</p><p>Suppose search returns:</p><p>entity_123 -&gt; Candidate A<br>entity_456 -&gt; Candidate B<br>entity_789 -&gt; Candidate C</p><p>The model can select:</p><p>[entity_123, entity_456]</p><p>But it should not be responsible for reconstructing the authoritative records.</p><p>Instead:</p><p>This is the Resolver Pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JWOcLFHpzbtVSPSX0LhxQ.png" /></figure><p>That separation is extremely valuable.</p><h3>13. Why Stable Entity References Matter</h3><p>It is tempting to ask the model to return an entire record.</p><p>But that creates unnecessary opportunities for hallucination and inconsistency.</p><p>Instead:</p><p>A stable reference provides a boundary between reasoning and authoritative application data.</p><p>It gives you:</p><ul><li>smaller model output<br>• easier validation<br>• less hallucination<br>• deterministic deduplication<br>• better analytics<br>• safer rendering<br>• provider independence</li></ul><p>The model only needs to identify the result it wants to use.</p><p>The application remains responsible for deciding what that result actually contains.</p><h3>14. Resolution and Rendering Are Separate From Reasoning</h3><p>A result is not necessarily a piece of text.</p><p>Depending on the domain and channel, it might become:</p><ul><li>text<br>• structured JSON<br>• a card<br>• a table<br>• a carousel<br>• a link<br>• a map location<br>• a custom UI component</li></ul><p>The architecture should therefore separate:</p><p>The key rule is:</p><p>The LLM decides what known result is relevant. The application decides what data represents that result and how it should be delivered.</p><p>This prevents the model from inventing URLs, entity identifiers, image locations, prices, availability, booking links, database records, action IDs, and other system-owned metadata.</p><h3>15. Actions Need Their Own Boundary</h3><p>Reading information and changing information are different operations.</p><p>A read might be:</p><p>Get order status</p><p>An action might be:</p><p>Cancel order</p><p>The architecture should make that distinction explicit:</p><p>Actions should produce structured records that can be traced.</p><p>The architectural principle is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2HQHxjBCj5yHSHqLXK2Ww.png" /></figure><h3>16. Keep Deterministic Work Out of the LLM</h3><p>A production agent should be deliberate about which responsibilities are probabilistic and which are deterministic.</p><p>Good uses of an LLM:</p><ul><li>intent interpretation<br>• language understanding<br>• query rewriting<br>• tool selection<br>• reasoning<br>• response generation<br>• selecting among known results</li></ul><p>Good uses of <strong>deterministic code</strong>:</p><ul><li>authentication<br>• authorization<br>• database operations<br>• state transitions<br>• action execution<br>• ID validation<br>• URL resolution<br>• deduplication<br>• filtering<br>• business invariants<br>• safety constraints<br>• audit records</li></ul><p>A useful rule is:</p><p><strong>LLM</strong> = reasoning</p><p><strong>Code</strong> = truth + invariants + side effects</p><p>This is one of the strongest architectural principles for reliable agent systems.</p><h3>17. One Model Call Should Not Do Everything</h3><p>Another useful design principle is to give model calls distinct responsibilities.</p><p>For example:</p><p><strong>Intent</strong><br>Which capability should handle this request?</p><p><strong>Query Understanding</strong><br>What does the user’s search request mean?</p><p><strong>Capability Reasoning</strong><br>Given the available tools and observations, what should happen next?</p><p><strong>Response Generation</strong><br>How should the result be communicated?</p><p>These responsibilities can sometimes be combined.</p><p>But they should not be combined merely because one giant prompt is easier to write.</p><p>Separating responsibilities can make:</p><ul><li>prompts smaller<br>• testing easier<br>• failures easier to diagnose<br>• outputs easier to validate<br>• model selection more flexible</li></ul><p>The architecture should determine where reasoning is required.</p><p>One giant agent prompt should not become the architecture.</p><h3>18. The Domain Boundary</h3><p>The most useful test of an <strong>AI Agent Engine</strong> is:</p><p>Can the domain change without rewriting the runtime?</p><p>Imagine using the same engine for IT support.</p><p>Instead of commerce capabilities, the registry might contain:</p><p><strong>CAPABILITIES</strong> = {<br>“<strong>incident_lookup</strong>”: {<br>“factory”: “incident_tools_factory”,<br>“topic”: “incident”,<br>“entity_type”: “incident”,<br>},<br>“<strong>knowledge_search</strong>”: {<br>“factory”: “knowledge_tools_factory”,<br>“topic”: “knowledge”,<br>“entity_type”: “article”,<br>},<br>“<strong>password_reset</strong>”: {<br>“factory”: “identity_tools_factory”,<br>“topic”: “identity”,<br>“entity_type”: “user”,<br>},<br>}</p><p>The runtime does not fundamentally change.</p><p>The domain supplies:</p><ul><li>prompts<br>• tools<br>• adapters<br>• schemas<br>• search data<br>• actions<br>• renderers</li></ul><p>The engine supplies:</p><ul><li>routing<br>• state<br>• capability execution<br>• tool execution<br>• action tracking<br>• retrieval orchestration<br>• resolution<br>• LLM lifecycle</li></ul><p>That is the real abstraction.</p><h3>19. A Domain-Independent Reference Architecture</h3><p>A clean implementation might have boundaries such as:</p><p>The exact folder structure is not important.</p><p>The separation of responsibilities is.</p><p>A different codebase might organize the same architecture differently.</p><p>What matters is that the runtime does not become tightly coupled to one domain or one external provider.</p><h3>20. Think of the Agent as a Compiler Pipeline</h3><p>There is another useful way to think about the entire system.</p><p>An agent behaves somewhat like a compiler.</p><p>Natural language is the input language.</p><p>The runtime transforms it through structured intermediate representations.</p><p>Retrieval follows a similar pipeline:</p><p>This framing is useful because every intermediate representation can be validated.</p><p>Instead of asking:</p><p>“Did the agent hallucinate?”</p><p>you can ask:</p><ul><li>Was the intent correct?<br>• Was the capability correct?<br>• Was the query correct?<br>• Were the candidates correct?<br>• Was the selected entity valid?<br>• Was the action authorized?<br>• Was the final rendering based on canonical data?</li></ul><p>Now debugging becomes an engineering problem rather than purely a prompt-writing problem.</p><h3>21. The Design Patterns Behind the Architecture</h3><p>The architecture uses several classic software patterns.</p><p><strong>Factory Pattern</strong></p><p>Used for capability creation, tool creation, model creation, and service or adapter creation.</p><p><strong>Registry Pattern</strong></p><p>Maps:</p><p>capability → configuration → factory → implementation</p><p><strong>Adapter Pattern</strong></p><p>Normalizes different external providers behind common interfaces.</p><p><strong>Strategy Pattern</strong></p><p>Allows interchangeable retrieval strategies, reranking strategies, model providers, and external integrations.</p><p><strong>Command / Action Pattern</strong></p><p>Represents state-changing operations.</p><p><strong>State Pattern</strong></p><p>Tracks conversation context and progression.</p><p><strong>Pipeline Pattern</strong></p><p>Represents multi-stage processing:</p><p><strong>Resolver Pattern</strong></p><p>Turns model-selected references into authoritative application entities.</p><p>These patterns are not the architecture by themselves.</p><p>They are implementation techniques that help preserve the architectural boundaries.</p><h3>22. Technology Comes After the Boundaries</h3><p>Once the architecture is clear, concrete technologies can be mapped onto it.</p><p>Architectural responsibility → Possible implementation</p><p>The important distinction is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzWJML8P3dGbiuQOJtR9bw.png" /></figure><p>You can replace the workflow framework, search provider, database, model provider, or API framework without changing the fundamental design.</p><p>That is a sign of a healthy architecture.</p><h3>23. The Final Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYGXGlu3JD24uJrolBWQZA.png" /><figcaption>Reference architecture for a domain-agnostic AI Agent Engine.</figcaption></figure><p>This is the architecture worth preserving.</p><p>The individual technologies can change.</p><p>The domain can change.</p><p>The capabilities can change.</p><p>The channels can change.</p><p>The underlying data providers can change.</p><p>The boundaries remain.</p><h3>24. The Most Important Lesson</h3><p>The biggest mistake when building AI agents is to think the architecture is:</p><p><strong>Prompt + LLM + Tools</strong></p><p>A production agent is closer to:</p><p><strong>Router<br>+<br>Capability Modules<br>+<br>Tool Registry<br>+<br>Factories<br>+<br>State<br>+<br>Context<br>+<br>Deterministic Actions<br>+<br>Retrieval<br>+<br>Reranking<br>+<br>Resolution<br>+<br>Rendering<br>+<br>Observability</strong></p><p>The LLM sits in the middle of that system.</p><p><strong>It is not the system.</strong></p><p>That distinction is what allows an agent engine to move from one domain to another without rebuilding the entire runtime.</p><p>A domain-specific application becomes a set of capabilities, tools, data sources, and business rules plugged into a more general execution model.</p><h3>Conclusion</h3><p>The goal should not be to build another chatbot that happens to call an LLM.</p><p>The goal is to build a runtime for capabilities.</p><p>A capability receives <strong>conversation state</strong>, structured context, a prompt, and a set of tools.</p><p>The LLM reasons over those tools.</p><p>Retrieval provides grounded information.</p><p>Tools interact with external systems.</p><p>Actions create explicit state changes.</p><p>Resolvers turn model-selected references into authoritative entities.</p><p>Renderers turn those entities into channel-specific responses.</p><p><strong>Deterministic code</strong> protects the system’s invariants.</p><p>And the orchestration layer remains reusable because it is not coupled to one domain.</p><p>The architecture can be summarized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkDiahODh5JU2LUp7b6aqA.png" /></figure><p>That is the foundation for a domain-agnostic <strong>AI Agent Engine</strong>.</p><h3>What Comes Next?</h3><p>Architecture is only the first layer.</p><p>The next engineering problem is data.</p><p>An agent can have excellent orchestration and still fail if the information it retrieves is poorly structured, difficult to search, or disconnected from business constraints.</p><p>The next article will explore how raw domain data becomes agent-ready knowledge through:</p><ul><li>data normalization<br>• structured metadata<br>• semantic search<br>• keyword search<br>• hybrid retrieval<br>• filtering<br>• business-aware reranking</li></ul><p>The goal is to move from:</p><p>Raw Domain Data<br>↓<br>Searchable Knowledge<br>↓<br>Agent-Ready Information</p><p>to a <strong>retrieval layer</strong> that an AI agent can reliably reason over.</p><h3>Where This Series Goes Next</h3><p>Building the architecture is only the beginning.</p><p>A production-grade <strong>AI Agent Engine</strong> has several layers, and each layer introduces its own engineering challenges. The rest of this series will explore those layers one by one, moving from architecture to data, implementation, and production lessons.</p><h3>The Series</h3><p><strong>1. Building a Domain-Agnostic AI Agent Engine: Start with the Architecture</strong><br> How to design a reusable runtime around routing, Capability Modules, state, tools, retrieval, actions, resolution, and rendering.</p><p><strong>2. From Raw Data to Agent-Ready Knowledge</strong><br> How raw application data becomes structured, searchable, filterable, and retrievable knowledge that an AI agent can reliably use.</p><p><strong>3. Building a Production-Grade Ecommerce AI Agent</strong><br> Putting the architecture into practice by building domain-specific capabilities for product discovery, order support, recommendations, returns, and other ecommerce workflows.</p><p><strong>4. Building a Reliable Image &amp; Media Pipeline for AI Agents</strong><br> How agents should discover, validate, resolve, and render images and other media without relying on the LLM to invent media metadata.</p><p><strong>5. Designing Conversational Retrieval: Deterministic “Show More” and Pagination</strong><br> How to build retrieval experiences that understand follow-up requests such as “show me more,” “the next five,” or “what about the second one?” without losing conversation context.</p><p><strong>6. Building Trustworthy Attribution and Observability into AI Agents</strong><br> How to make agent responses traceable by connecting retrieved knowledge, entities, tools, actions, and final responses.</p><p><strong>7. Production Lessons from Building an AI Agent Engine</strong><br> The engineering lessons that emerge when the architecture meets real data, real users, external systems, failures, latency, and production constraints.</p><p>The goal is not to build a collection of disconnected AI features.</p><p>The goal is to progressively understand <strong>how a reusable AI Agent Engine can become a reliable foundation for domain-specific AI applications.</strong></p><h3>Next: From Raw Data to Agent-Ready Knowledge</h3><p>An agent can have excellent orchestration and still fail if the information it retrieves is poorly structured, difficult to search, or disconnected from business constraints.</p><p>The next article looks at the layer underneath the agent:</p><p><strong>How does raw application data become agent-ready knowledge?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c25e37bf2b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>