<?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 Benjamin Chu (周明祥) on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Chu (周明祥) on Medium]]></description>
        <link>https://medium.com/@bensabenteuer?source=rss-731f7b65e8c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GY5w7lJeTtktpCmmKSBG_A@2x.jpeg</url>
            <title>Stories by Benjamin Chu (周明祥) on Medium</title>
            <link>https://medium.com/@bensabenteuer?source=rss-731f7b65e8c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:53:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bensabenteuer/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[Search Smarter and Not Harder: Redefining Retrieval Augmented Generation]]></title>
            <link>https://pub.towardsai.net/search-smarter-and-not-harder-redefining-retrieval-augmented-generation-108dff0f1f89?source=rss-731f7b65e8c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/108dff0f1f89</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Benjamin Chu (周明祥)]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:02:01 GMT</pubDate>
            <atom:updated>2024-11-12T22:02:01.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*7F1U3DrZDI9d3gCkLE84jQ.jpeg" /><figcaption>Lost in a maze: Generated by Benjamin Chu using DeepAI</figcaption></figure><h3>1. Introduction</h3><p>In today’s information-saturated world, finding the right knowledge can often feel like searching for a needle in a haystack. With the exponential growth of data, the challenge of effective information retrieval has never been more critical. Improving search results through better strategies helps to provide more contextually rich and relevant information. This in turn will guide language models to generate more accurate, coherent responses and also reduces the likelihood of hallucinations. However, to truly harness the power of RAG, we must consider how we set boundaries and curate our knowledge bases, ensuring that we search smart, not harder.</p><p><strong>1.1 Setting the Boundaries: The Importance of Curation</strong></p><p>Successful knowledge management begins with well-defined boundaries. Instead of taking a shot in the dark and dumping vast amounts of data into a knowledge base, organizations should focus on curation. This means carefully selecting which data to include, based on relevance and utility.</p><p>Testing backward is an essential strategy in this process. Organizations can refine their knowledge bases incrementally, ensuring that the information remains relevant and useful over time. This versioning approach is vital; it allows teams to track changes and understand the evolving landscape of knowledge.</p><p><strong>1.2 The Power of Metadata</strong></p><p>One excellent example of effective knowledge curation is AWS Bedrock’s knowledge base. AWS simplifies the process of linking data sources using raw files and metadata in JSON format. This capability is crucial for hybrid searches, where combining structured and unstructured data can lead to more refined results.</p><p>Metadata serves as the backbone of this process, enhancing the search experience by providing context and relevance. By attaching meaningful metadata to data entries, organizations can facilitate more precise searches, leading to better outcomes.</p><p><strong>1.3 The Milvus Strategy: Partitioning for Precision</strong></p><p>Milvus, a leading vector database, exemplifies how modern technology can enhance information retrieval. One of its standout features is the ability to create multiple partitions within a single collection. This functionality allows organizations to categorize data effectively, landing queries in the right partition based on the identified topics or subjects.</p><p>By leveraging partitioning strategies, Milvus enables more precise searches, reducing the noise and focusing on relevant information. This proactive approach to data organization empowers users to retrieve the insights they need quickly and efficiently.</p><p><strong>1.4 Vector Embeddings: Not a Silver Bullet</strong></p><p>Vector embeddings are a crucial component in retrieval-augmented generation (RAG) systems, serving as the mechanism for representing text in a way that facilitates meaningful comparisons. The MTEB (Massive Text Embedding Benchmark) leaderboard showcases various embedding models, such as BGE and OpenAI’s text-embedding-3 in both large and small models. As the trend shifts toward larger dimensions and multi-modal embeddings, there’s a growing belief that more parameters will yield better performance. However, larger dimensions do not always guarantee improved results.</p><p>While vector embeddings are a crucial component in RAG systems, <em>they are not a panacea for information retrieval challenges</em>.</p><p>The noise introduced by embeddings can obscure the truly valuable information, often resulting in missed relevant data that resides beyond the top K results. This highlights the need for reshuffling and reranking processes, ensuring that the most pertinent information surfaces, rather than relying solely on the initial output of the search.</p><p>The practice of using distinct embedding models, with one better suited for document representation and another for reranking in RAG systems do not only defeats the purpose of leveraging embeddings effectively but also leads to suboptimal performance in retrieval.</p><p><strong><em>Context is paramount. The challenge remains: even the most sophisticated embeddings can struggle to deliver relevant search results without effective curation and clearly defined boundaries. In such cases, the search can still resemble searching for a needle in a haystack, often resulting in irrelevant pieces of information surfacing amidst the relevant ones.</em></strong></p><p>It’s crucial to remember that embeddings are just one piece of the puzzle; they must be integrated thoughtfully with other strategies to unlock their full potential.</p><h3>2. Redefining Search with Newer Strategies</h3><p><strong>2.1 Hierarchical Navigable Small World of Graphs (HNSW)</strong></p><p>Let’s take a closer look at HNSW. Imagine navigating through a complex city without a map — frustrating, right? That’s essentially what traditional search algorithms face when dealing with high-dimensional data spaces.</p><p><strong><em>HNSW changes this game by creating an efficient indexing structure that allows for lightning-fast similarity searches. It works by organizing data points into hierarchical layers, each representing a different scale of proximity.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MMMeE4yg3aWjR_X3.png" /><figcaption>Left: Illustration of a search through an HNSW. We are searching for the vector nearest the target X. Long-range connections and hubs are green; short-range connections are grey. Arrows show the search path. Starting at the entry point E1, we perform a greedy search among the long-range connections, reaching E2, which is the nearest long-range hub to X. From there we continue the greedy search among the short-range connections, ending at Y, the nearest vector to X. Right: Visualising the HNSW as a stack of three layers. Dotted lines indicate the location of the same vector in the layer below. Image source: <a href="https://towardsdatascience.com/whats-the-story-with-hnsw-d1402c37a44e">https://towardsdatascience.com/whats-the-story-with-hnsw-d1402c37a44e</a></figcaption></figure><p>Building on probability skip lists and navigable small world (NSW) graphs, HNSW creates a hierarchical structure with layers of decreasing link lengths. An NSW graph itself is a fascinating construct, where each vector in the dataset becomes a node, connected to others via short-, medium-, and long-range links. These links are determined by the similarity between vectors, with closer vectors forming stronger connections. When performing a search, the algorithm begins at a predefined entry point and uses a greedy strategy to traverse the graph, jumping to the nearest neighbor at each step. This process continues until the desired nearest neighbor is found. HNSW extends this concept by layering multiple NSW graphs, each with progressively shorter links. During the search, queries enter at the topmost layer and traverse downwards, shifting between layers when reaching local minima. This efficient navigation mechanism allows for logarithmic complexity nearest neighbour searches, even in large datasets. This clever arrangement enables systems to quickly zoom in on the most similar items, much like how you might navigate a city using both a regional map and street-level directions. As a result, HNSW dramatically speeds up retrieval processes, ensuring that queries hit the bullseye every time.</p><p>Further read:</p><p><a href="https://towardsdatascience.com/similarity-search-part-4-hierarchical-navigable-small-world-hnsw-2aad4fe87d37">Similarity Search, Part 4: Hierarchical Navigable Small World (HNSW)</a></p><p><strong>2.2 Hybrid Search</strong></p><p>Now, let’s talk about hybrid search — the next frontier in information retrieval. We’re moving beyond simple keyword filtering, which was the first state of hybrid search. Enter SPLADE (Sparse Lexical and Dense Embeddings), a game-changer in the world of vector-based searching. SPLADE combines sparse lexical embeddings with dense semantic embeddings, creating a powerful hybrid approach. This allows us to capture both precise keyword matches and nuanced semantic relationships simultaneously. But here’s where it gets really exciting: Milvus, a cutting-edge vector database, takes this concept to the next level with stacked multi-vector searches. Imagine being able to query your data using multiple vectors at once — it’s like having multiple super-smart librarians searching for you in parallel!</p><p><strong>2.3 Matryoshka: Nested Embeddings</strong></p><p>Matryoshka embeddings have a unique hierarchical structure, reminiscent of Russian nesting dolls. Specifically, this type of embedding works similarly — it stores information in layers, with the most essential information on the outside (in larger layers) and increasingly detailed data within. This layering allows us to use only a portion of the full embedding to perform tasks, much like how we might only open one or two layers of the nesting doll to get a general idea of what’s inside.</p><p>For those who build AI systems, finding similar items — like retrieving matching documents, images, or recommendations — is a common challenge. Traditional embeddings (data representations used in similarity searches) are often large, with hundreds or thousands of dimensions. While this level of detail is valuable, it requires considerable storage space and computing power, which can slow down processing and increase costs.</p><p>Here’s the problem in simple terms:</p><ul><li><strong>Storage</strong>: High-dimensional embeddings take up lots of space.</li><li><strong>Latency</strong>: Searching across these large embeddings can be slow.</li><li><strong>Re-ranking</strong>: Often, traditional embeddings need re-ranking and shuffling to get accurate results, which further increases processing time.</li></ul><p><strong><em>Nested embeddings tackle these issues by building on the ability to truncate dimensions without losing the big picture.</em></strong></p><p>This lets us speed up the search, reducing storage needs and lowering latency — all without compromising on accuracy. The nested embeddings introduce a novel approach to dimensionality management:</p><ul><li>Hierarchical Compression: By strategically compressing dimensions at different levels of the embedding hierarchy, Matryoshka embeddings allow for efficient truncation without sacrificing the overall structure and relationships within the data.</li><li>Flexible Retrieval: This hierarchical structure enables retrieval of relevant information using partial embeddings, significantly reducing the computational load required for similarity searches.</li><li>Balanced Accuracy &lt;&gt; Efficiency: By leveraging the nested nature of the embeddings, AI systems can now achieve a delicate balance between accuracy and efficiency, addressing the long-standing trade-offs inherent in traditional embedding methods.</li></ul><p>Further read:</p><p><a href="https://towardsdatascience.com/how-to-reduce-embedding-size-and-increase-rag-retrieval-speed-7f903d3cecf7">How to Reduce Embedding Size and Increase RAG Retrieval Speed</a></p><h3>3. Search Implementation</h3><pre># Author: Benjamin Chu<br># Description: Leverage UnstructuredLoader for web documents parsing with custom merging parent-child elements<br># Created: 2024-11-10<br># Purpose: Merging context chunks by navigating parent-child elements<br><br>from typing import List, Dict, Any<br>from collections import defaultdict<br>from langchain.document_loaders import UnstructuredLoader<br>from langchain.schema import Document<br><br>async def get_web_docs(page_urls: List[str]) -&gt; List[Document]:<br>    &quot;&quot;&quot;<br>    Retrieves and aggregates document content from the provided URLs using the UnstructuredLoader.<br>    Each URL is processed asynchronously to generate a collection of documents.<br>    Parameters:<br>        page_urls (List[str]): List of URLs to retrieve content from.<br>    Returns:<br>        List[Document]: List of all document objects from the URLs.<br>    &quot;&quot;&quot;<br>    web_docs = []<br>    for url in page_urls:<br>        loader = UnstructuredLoader(web_url=url)<br>        docs = await _get_docs_from_loader(loader)<br>        web_docs.extend(docs)<br>    <br>    return web_docs<br><br>async def _get_docs_from_loader(loader: UnstructuredLoader) -&gt; List[Document]:<br>    &quot;&quot;&quot;<br>    Loads documents from an UnstructuredLoader instance asynchronously.<br>    Parameters:<br>        loader (UnstructuredLoader): The loader instance initialized with a web URL.<br>    Returns:<br>        List[Document]: List of Document objects retrieved from the loader.<br>    &quot;&quot;&quot;<br>    docs = []<br>    async for doc in loader.alazy_load():<br>        docs.append(doc)<br>    return docs<br><br>def merge_documents_by_parent(web_docs: List[Document]) -&gt; List[Document]:<br>    &quot;&quot;&quot;<br>    Merges document elements based on parent-child relationships.<br>    Combines content from child elements under a common parent, or retains standalone elements as individual entries.<br>    Parameters:<br>        web_docs (List[Document]): List of Document objects with metadata containing &#39;element_id&#39; and &#39;parent_id&#39;.<br>    Returns:<br>        List[Document]: List of merged Document objects.<br>    &quot;&quot;&quot;<br>    element_entries = {}  # Dictionary to store unique elements by their IDs<br>    parent_to_elements = defaultdict(list)  # Maps parent IDs to their child element IDs<br>    <br>    # Step 1: Organize documents by element and parent IDs<br>    for doc in web_docs:<br>        element_id = doc.metadata[&quot;element_id&quot;]<br>        parent_id = doc.metadata.get(&quot;parent_id&quot;)<br>        # Store document content by element_id<br>        if element_id not in element_entries:<br>            element_entries[element_id] = {<br>                &quot;metadata&quot;: doc.metadata,<br>                &quot;page_content&quot;: []<br>            }<br>        element_entries[element_id][&quot;page_content&quot;].append(doc.page_content)<br>        # Map element_id under its parent_id, if applicable<br>        if parent_id:<br>            parent_to_elements[parent_id].append(element_id)<br>    <br>    # Step 2: Merge content for elements with the same parent_id<br>    merged_docs = []<br>    for parent_id, element_ids in parent_to_elements.items():<br>        # Concatenate content from all child elements for a given parent<br>        merged_content = &#39; &#39;.join(<br>            &#39; &#39;.join(element_entries[element_id][&quot;page_content&quot;]) for element_id in element_ids<br>        )<br>        # Use the metadata from the first child element, setting the id to parent_id<br>        first_element = element_entries[element_ids[0]]<br>        merged_metadata = {**first_element[&quot;metadata&quot;], &quot;id&quot;: parent_id}<br>        merged_metadata.pop(&quot;element_id&quot;, None)<br>        # Create merged document for the parent<br>        merged_docs.append(Document(metadata=merged_metadata, page_content=merged_content))<br>    <br>    # Step 3: Include standalone elements (those without a parent)<br>    for element_id, entry in element_entries.items():<br>        if element_id not in parent_to_elements:<br>            standalone_content = &#39; &#39;.join(entry[&quot;page_content&quot;])<br>            standalone_metadata = {**entry[&quot;metadata&quot;], &quot;id&quot;: element_id}<br>            merged_docs.append(Document(metadata=standalone_metadata, page_content=standalone_content))<br>    return merged_docs</pre><p>I’ve created this code to retrieve content from a list of URLs and perform the chunking based on parent-child relationships between document elements. Here’s a breakdown of each step:</p><p><strong>a) Retrieving Documents</strong>:</p><ul><li>The get_web_docs function initializes a loader for each URL in page_urls and fetches document data using _get_docs_from_loader. This function leverages UnstructuredLoader from the LangChain library, which processes web content at a granular level.</li><li>Each element on a page (such as headers, paragraphs, lists, and etc.) is represented as a separate document, which allows for detailed control over content.</li></ul><p><strong>b) Organizing Elements by Parent-Child Relationships</strong>:</p><ul><li>The merge_documents_by_parent function processes the collected documents to group elements under their parent sections based on metadata fields element_id and parent_id.</li><li>This approach enables a hierarchical organization, in which content from child elements (like paragraphs) is merged under a parent (such as a section title).</li></ul><p><strong>c) Merging Content</strong>:</p><ul><li>The function combines the page content from all its child elements for each parent. This merged content is then used to create a single Document entry for that parent while preserving key metadata.</li><li>Standalone elements (those without a parent) are added as individual entries to maintain completeness.</li></ul><h3>3.1 Parent-Child Chunking</h3><p>This setup exemplifies a structured approach to content extraction using <strong>granular parsing and metadata</strong>. The UnstructuredLoader makes it possible to access individual elements of a webpage (e.g., titles, lists, paragraphs) and categorize them based on their content type, which is invaluable for <strong>creating rich, searchable documents</strong>. For instance, document elements like headers and figure captions can be isolated, enhancing search precision.</p><p>Incorporating <strong>metadata</strong> (such as element_id and parent_id) allows for content structuring. This method lays the groundwork for building a <strong>hierarchical document search</strong>, where users can target specific sections within documents. Although this example doesn’t utilize metadata or partitioning at full capacity, the approach demonstrates how further refinements—such as adding section-specific metadata—could enhance search accuracy by isolating only the most relevant sections.</p><p>This process illustrates that setting up an efficient search involves not just embedding vectors but curating, organizing, and structuring data. Tools like UnstructuredLoader enable <strong>fine-grained control</strong> over document elements, while logical grouping and metadata enhance search relevance, reinforcing the idea of &quot;search smarter, not harder.&quot;</p><h3>3.2 The Funnel Search</h3><p>When working with large embeddings, the goal is often to find the closest matches to a given query as quickly as possible. But with thousands of dimensions, each search becomes computationally heavy, and the latency increases. Here’s where Matryoshka embeddings stand out: they allow for a “funnel search.”</p><p><strong>How Funnel Search works?</strong></p><ol><li><strong>Start Small</strong>: Instead of using the full embedding, begin with a reduced version, like the first 1/32 of the dimensions. This smaller size gives a “good enough” picture for a broad similarity search.</li><li><strong>Iterative Reranking</strong>: Take the initial candidates and rerank them, this time using a slightly larger portion, like the first 1/16 of the embedding. This allows a more refined similarity measure.</li><li><strong>Repeat Until Done</strong>: Continue narrowing down the candidate list by progressively using larger portions of the embedding (e.g., 1/8, 1/4), until the best matches are found.</li></ol><p>This approach is much faster than starting with the full embedding dimensions, yet it still provides high accuracy. Since Matryoshka embeddings were designed to work this way, they eliminate the need for a separate re-ranking embedding pass, making the process more streamlined and efficient.</p><p>I’ve developed an interface to demonstrate everything I’ve described, comparing base search using vector similarity and funnel-search. Here, I utilize Claude 3.5 Sonnet to generate answers and Claude 3 Opus as the judge evaluator. The chunks (described earlier) are stored in the Milvus vector store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37smdOpbR4CIk6IMom6SLg.gif" /><figcaption><strong>ChatCritique: AI Response Checker with DeepEval</strong> — A chat interface for answering and analyzing AI responses using base and funnel search methodologies. DeepEval is used as the evaluation framework to evaluate responses generated by Claude 3.5 Sonnet and using Claude 3 Opus as the judge LM. Additionally, DeepEval provides the reasons for the scoring; the reasons can be used as explanability for further deep-dive analysis. Created by Benjamin Chu © 2024.</figcaption></figure><p>Further read:</p><p><a href="https://milvus.io/blog/matryoshka-embeddings-detail-at-multiple-scales">Matryoshka Embeddings: Detail at Multiple Scales - Milvus Blog</a></p><h3>4. Contextual Relevance Base Search vs Funnel Search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QuBQvdlhXk-W9hdh.png" /><figcaption><strong>Contextual Relevancy with DeepEval:</strong> Search Strategy Comparison — Analysis for all questions across the three main topics with a further breakdown of the subtopics. Generated by Benjamin Chu @2024.</figcaption></figure><p><strong>4.1 Results Summary</strong></p><p>The <strong>RAG Architecture</strong> category showed that funnel search with reranking significantly improved relevance for questions about graph databases and vector embeddings, achieving up to 87.1% relevance compared to base search’s 65%. However, for simpler comparisons, like “Graph vs. Vector RAG,” the improvement was minimal. This suggests that reranking is especially useful for complex, context-heavy queries within RAG architecture but offers limited gains for straightforward queries.</p><p>In the <strong>Agentic Workflows</strong> category, funnel search showed mixed results. It performed better in retrieving nuanced information on tools like LangChain and LlamaIndex, but the scores remained low overall, likely due to limited coverage of this niche topic in the dataset. Interestingly, base search outperformed funnel search for multi-document retrieval, indicating that reranking may not always be beneficial for straightforward retrieval tasks, where initial vector matching might already capture the most relevant results.</p><p>As for the<strong> LLM evaluation </strong>category<strong>, </strong>funnel search consistently outperformed base search, particularly for questions related to evaluation metrics (66.7%) and framework comparisons (86.7%). For these categories, funnel search achieved up to 92.9% and 73.3% in contextual relevance, respectively. This strong performance suggests that funnel search with reranking enhances results for in-depth evaluation topics. Overall, while funnel search with reranking generally improved relevance across various categories, it still faced challenges due to the limited scope of the dataset, which was selected specifically to demonstrate the search application and conduct initial evaluations. Additionally, the lack of support for non-textual content, such as images and tables, hindered its ability to fully address the needs of comprehensive technical analysis.</p><p><strong>4.2 Key Findings</strong></p><p>The funnel search with reranking generally outperformed base search across most question types, particularly for queries requiring contextual depth or comparative analysis. This setup highlights several findings:</p><ol><li><strong>Contextual Relevance with Reranking</strong>: Funnel search’s reranking capability significantly improved relevance scores for complex, context-heavy queries, as seen in the RAG Architecture and LLM Evaluation sections. This indicates that reranking can help prioritize nuanced information more effectively than base search.</li><li><strong>Challenges in Data Diversity</strong>: The limited dataset of 40 websites, predominantly from Medium articles with some others from technology blogs, restricted the quality of retrieval for highly specialized or diverse questions. For instance, agentic workflow queries showed low scores, indicating that the dataset may lack sufficient information on niche topics like LangChain versus LlamaIndex comparisons, LangGraph versus CrewAI, etc.</li><li><strong>Absence of Image and Table Support</strong>: Certain technical queries would benefit from visual aids like architectural diagrams or performance tables, which were not ingested in this text-only dataset. For instance, a question on “Graph Database” could have benefited from visual representations to compare structures or processes, which were absent here.</li><li><strong>Simple queries</strong>: The base search’s high performance on the query on multi-document retrieval suggests that simpler retrieval tasks might not benefit from reranking. Funnel search’s reranking process may overcomplicate straightforward queries, where the initial vector similarity retrieval alone is sufficient.</li></ol><p><strong>4.3 Current Limitations</strong></p><p>The current RAG setup ingests a limited dataset of around 40 websites, primarily consisting of technology-focused articles from platforms like Medium and various tech blogs. This relatively small and homogenous dataset can limit the scope of the retrieved information, especially for queries that demand specialized knowledge or side-by-side comparisons of frameworks. Furthermore, this ingestion process currently focuses on text-based content only, without incorporating images, tables, or other structured data types that could enrich the retrieval context. For instance, queries that would benefit from visual comparisons, such as architecture diagrams or performance metrics, may not achieve their full potential in the current setup.</p><p>An example query, “What are the key differences between LangChain and LlamaIndex for implementing agentic RAG systems?” With the base vector search, the results provided a relevancy score of only 0.18, largely because the information retrieved was broad and lacked specific insights into implementing agentic RAG. In contrast, the funnel search with reranking managed a higher score of 0.29 by pulling more contextually relevant information about the frameworks, though it still missed concrete comparisons. This difference highlights how a reranking strategy, even when marginal, can improve the specificity of responses, which is crucial for nuanced technical questions.</p><p>However, for some other more specific or technical queries, such as those seeking a comparison between graph-based RAG systems and traditional vector-based approaches, the funnel search fell short. While it managed to retrieve general information about the strengths of graph RAG systems, it lacked the depth needed to thoroughly discuss their pros and cons, likely due to the limited technical detail available in the ingested dataset.</p><h3>5. Conclusion</h3><p>In conclusion, this experiment highlights the need beyond simply using embeddings to optimize search results. Using Milvus as the vector store has enabled efficient storage and retrieval of embeddings, but there’s still room for improvement. While I didn’t implement partitioning or metadata enhancements in this demonstration, these steps could significantly boost the search system’s accuracy and relevance in future iterations.</p><p>Partitioning would allow for more precise topic segmentation, reducing irrelevant noise and focusing results on specific content areas (narrowing down the start points). Similarly, adding metadata to each data entry would enhance the reranking process by providing additional context, helping the system to interpret nuanced queries more effectively. Although these optimizations were not part of this initial setup, they are relatively straightforward to implement and would align well with the “test backward” approach I emphasized earlier. By iteratively refining the data ingestion process, I can build on this foundation to create a search system that is even more responsive to complex, multi-dimensional queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=108dff0f1f89" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/search-smarter-and-not-harder-redefining-retrieval-augmented-generation-108dff0f1f89">Search Smarter and Not Harder: Redefining Retrieval Augmented Generation</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents in Action: Interaction and Workflow Dynamics]]></title>
            <link>https://medium.com/towards-generative-ai/ai-agents-in-action-interaction-and-workflow-dynamics-f7bd588645a8?source=rss-731f7b65e8c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7bd588645a8</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Benjamin Chu (周明祥)]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 04:56:20 GMT</pubDate>
            <atom:updated>2024-11-10T03:38:13.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*vv1S7qZpxPJPnf8ucmRPww.jpeg" /><figcaption>Behind the Scenes: AI Agents Engaging in Conversational Dialogue. Generated by Benjamin Chu using DeepAI</figcaption></figure><h4><strong>Nature’s Blueprint for Collective Intelligence</strong></h4><p>Artificial intelligence doesn’t just process data — it learns, adapts, and evolves, much like the intricate mechanism of organisms in a thriving ecosystem. In my recent exploration of AI agents, I’ve observed a parallel: the promising path to true artificial intelligence might lie in mimicking nature’s time-tested blueprints and humanity’s capacity for adaptation and collaboration.</p><p>Picture a summer afternoon in your garden. An ant discovers a fallen cookie crumb. Within minutes, a precise line of its colony members forms, efficiently transporting fragments back to their nest. This isn’t random chance — it’s one of nature’s most sophisticated systems for coordinated teamwork. Through chemical signals called pheromones, ants create invisible highways of information that allow them to seamlessly work together on complex tasks.</p><p>Imagine if we could teach artificial intelligence to work with the same elegant efficiency. Nature has valuable lessons in collective intelligence that are highly relevant to advancing AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*P9VN9MnNU1HcR-_ksvmwow@2x.jpeg" /><figcaption><strong>Figure 1:</strong> How do agents work? Source: <a href="https://aiplanet.com/learn/rag-agents-bootcamp/module-1/2429/how-do-agents-work"><strong>AI Planet</strong></a></figcaption></figure><p>The parallels between ant colonies and modern AI systems are fascinating. Just as ants leave trails to guide their colony, today’s AI agents can use “digital breadcrumbs” to share critical information, enabling each agent to build on insights gathered by others. But AI systems are evolving well beyond this, moving toward dynamic cooperation that allows them to engage and adapt, even in unpredictable situations.</p><p>Take human teamwork as an example. When people collaborate on complex projects, they often divide tasks, assign specific roles, and share knowledge. Each person contributes unique expertise, from data gathering and trend analysis to decision-making and strategic planning. Similarly, today’s agentic AI systems are designed to perform autonomously within specialised roles, each with tailored tools and capabilities to contribute to a larger goal. This approach allows AI agents to operate in coordination, creating a seamless flow of information and action that mirrors human collaboration and adaptability.</p><h3><strong>Core Design: Building Blocks of Collective Intelligence</strong></h3><h3><strong>A. Modularity</strong></h3><p>In the world of agent-based AI, modularity is key to managing the growing complexity of real-world tasks. Inspired by both human and natural collaborative structures, a modular approach divides large objectives into manageable, specialised components. By assigning distinct roles to individual agents, AI systems can better coordinate and complete diverse and intricate challenges.</p><p>For instance, in a modular AI framework:</p><ul><li><strong>Data-Gathering Agents</strong> are akin to researchers, collecting and analyzing raw data.</li><li><strong>Synthesis Agents</strong> combine and make sense of this information, identifying patterns and deriving insights.</li><li><strong>Strategic Decision Agents</strong> apply logic and execute actions based on processed data.</li></ul><p>This approach brings many benefits. By establishing clear, purpose-driven roles, modular design enables agents to perform complex tasks independently yet in concert, ensuring both adaptability and efficiency. A standout example of this approach is <strong>CrewAI</strong>, where agents are organized into role-based teams resembling departments within a company. This structure allows agents to work autonomously while collectively tackling each part of a project. With defined, purposeful functions, agents can progress through tasks with precision, supporting efficient problem-solving in complex AI environments.</p><h3><strong>Design Patterns: The Architecture of Intelligence</strong></h3><p>Agentic AI systems draw from distinct “design patterns” to optimize task handling. Each pattern is uniquely structured, tailored to solve specific challenges by harnessing a unique interaction model that maximises each agent’s capabilities. These patterns, inspired by real-world collaboration models, provide a range of advantages:</p><p><strong>1. Pipeline (LlamaIndex Workflows)</strong></p><p>In the <strong>Pipeline Pattern</strong>, tasks follow a step-by-step flow where agents handle each stage sequentially. Like an assembly line, each agent knows precisely what to do and when, making it ideal for processes that need predictable and orderly execution. The Pipeline is best suited for scenarios where each step depends directly on the output of the previous one.</p><p><strong>2. Network (LangGraph)</strong></p><p>The <strong>Network Pattern</strong> supports tasks requiring interconnected processing, where agents work in parallel to explore multiple pathways and perspectives. With <strong>LangGraph</strong>, agents operate as interconnected nodes that can communicate in real time, dynamically responding to task complexities. This pattern is particularly valuable for scenarios that demand flexible, context-sensitive solutions and problem-solving.</p><p><strong>3. Forum (AutoGen)</strong></p><p>In the <strong>Forum Pattern</strong>, agents communicate in an open discussion format, resembling a group meeting or brainstorming session. This collaborative model allows agents to contribute diverse viewpoints, refine each other’s ideas, and generate creative solutions. The Forum Pattern suits tasks that benefit from multi-agent input and adaptability, making it highly effective for dynamic, exploratory projects.</p><p><strong>4. Team (CrewAI)</strong></p><p>The <strong>Team Pattern</strong> operates with a hybrid structure, allowing agents to work either hierarchically or in a sequence depending on the task’s needs. CrewAI organizes agents into distinct roles, enabling them to function as specialized team members working on a shared objective. Agents in this pattern can perform tasks both autonomously and collaboratively, supporting complex workflows that require flexibility in switching between structured sequences and adaptive roles. Unlike the Forum Pattern, which relies on open-ended discussion, the Team Pattern involves clear role assignments, coordination, and task ownership that can adapt to either sequential or parallel work structures.</p><h3><strong>B. Memory</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sg9ermbxRgPVXI7i6Kvj9Q.png" /><figcaption><strong>Figure 2:</strong> Human Memory Architecture: three stages of memory: sensory, short-term, and long-term, emphasizing the complexity of how humans process and retain information. Source: <a href="https://link.springer.com/chapter/10.1007/978-3-030-70650-0_7"><strong>A Formal Model for Emulating the Generation of Human Knowledge in Semantic Memory</strong></a>.</figcaption></figure><p><strong>From Sensory Impressions to Long-Term Storage</strong></p><p>Human memory is a marvelously complex system, enabling us to retain and recall an astounding amount of information throughout our lives. It’s not just about storing facts; memory is fundamental to how we interact, learn, and grow. Broadly, memory can be divided into <strong>sensory</strong>, <strong>short-term</strong>, and <strong>long-term</strong> stages, each playing a distinct role in transforming fleeting sensory impressions into lasting knowledge.</p><p><strong>Memory Stages</strong></p><ol><li><strong>Sensory Memory</strong>: This is where memory begins, capturing a brief record of sensory experiences — sights, sounds, smells — for just a few seconds. It’s like a quick snapshot or audio clip, and only the most relevant information makes it further. You might not remember every detail from a crowded street, but you’ll remember a loud car honking. This stage filters what’s worth keeping.</li><li><strong>Short-Term Memory (STM)</strong>: Often called our “mental scratchpad,” STM temporarily holds information we need immediately, like a phone number or an address. It can manage about 5 to 9 items for up to 30 seconds. We retain information here through <strong>rehearsal</strong> — repeating it over and over — or by linking it to things we already know, a method known as <strong>elaborative rehearsal</strong>.</li><li><strong>Long-Term Memory (LTM)</strong>: Long-term memory is our brain’s vast archive, storing knowledge, skills, and experiences for years or even decades. It contains both general information (like facts and concepts) and personal memories that make up our life story. Within LTM, two major types stand out:</li></ol><ul><li><strong>Semantic Memory</strong>: This is our mental encyclopedia, dealing with general facts and concepts, like knowing Paris is the capital of France.</li><li><strong>Episodic Memory</strong>: These are the memories tied to specific experiences and moments, like recalling your last vacation or a favorite birthday. Episodic memory gives life context, helping us build relationships and create meaningful connections over time.</li></ul><p><strong>Long-Term Memory: Explicit and Implicit</strong></p><p>Long-term memory isn’t just one big storage bin. It’s divided into <strong>explicit</strong> (conscious) and <strong>implicit</strong> (unconscious) memories:</p><ul><li><strong>Explicit Memory</strong>: These are memories we actively try to recall, such as facts or personal experiences. They include:</li><li><strong>Episodic Memory</strong> (personal experiences) and <strong>Semantic Memory</strong> (factual knowledge).</li><li><strong>Implicit Memory</strong>: These memories operate outside of conscious awareness, like “muscle memory” for tasks such as riding a bike or typing. They influence our behaviour and skills without requiring deliberate recall.</li></ul><p><strong>Blueprint #1 for Human-Like Memory in AI Agents</strong></p><p>In building AI agents that embody human-like memory, I created a comprehensive approach combining both short-term and long-term memory frameworks. This approach is inspired by principles of human memory discussed previously, specifically addressing the following:</p><ol><li><strong>Dynamic Memory Retrieval:</strong> Just as humans retrieve context-specific memories, the AI agent accesses relevant stored information based on contextual queries. This aligns with how people relate new inputs to past knowledge, allowing the agent to provide coherent, contextually informed responses across sessions.</li><li><strong>Adaptive Learning:</strong> The agent continuously updates its long-term memory with insights from each interaction. This persistent, cumulative storage is crucial for the agent to evolve and adapt, much like a human learning through experience.</li><li><strong>Entity:</strong> By recognising entities and saving metadata about key topics, the agent organizes memory at a granular level, capturing not only what was discussed but also the subject matter. This structured organization helps the agent recall details about specific topics and perform entity-based filtering when retrieving information.</li></ol><pre># Author: Benjamin Chu<br># Description: Custom memory tool for storing and indexing conversation entries for AI agents.<br># Created: 2024-11-02<br># Purpose: Supports both short-term (session-based) and long-term (vector-based) memory structures with topic and entity recognition.<br><br>@tool<br>def save_to_memory(collection, user_id: str, messages: List) -&gt; Dict[str, str]:<br>    all_data = []<br>    success = True<br>    <br>    for message in messages:<br>        role = &quot;user&quot; if &quot;HumanMessage&quot; in str(type(message)) else &quot;assistant&quot;<br>        entry_id = message.id<br>        content = message.content<br>        <br>        entry = {<br>            &quot;user_id&quot;: user_id,<br>            &quot;process_id&quot;: entry_id,<br>            &quot;role&quot;: role,<br>            &quot;text&quot;: None,<br>            &quot;topic&quot;: None,<br>            &quot;embeddings&quot;: None<br>        }<br><br>        # Format and save all assistant messages as conversation entries<br>        if role == &quot;assistant&quot; and &quot;answer&quot; in content:<br>            try:<br>                response_data = eval(content.strip(&quot;```&quot;))<br>                entry[&quot;text&quot;] = response_data.get(&quot;answer&quot;)<br>                entry[&quot;topic&quot;] = response_data.get(&quot;topic&quot;)<br>                <br>                if entry[&quot;text&quot;]:<br>                    embedding = list(embedding_model.embed(entry[&quot;text&quot;]))<br>                    entry[&quot;embeddings&quot;] = embedding[0]<br>                <br>                all_data.append(entry)<br>            except (SyntaxError, ValueError) as e:<br>                logger.error(f&quot;Failed to parse assistant message content: {e}&quot;)<br>                success = False<br>        elif role == &quot;user&quot;:<br>            entry[&quot;text&quot;] = content<br>    <br>    try:<br>        collection.insert(all_data)<br>    except Exception as e:<br>        logger.error(f&quot;Failed to insert data into the collection: {e}&quot;)<br>        success = False<br><br>    # Release or drop the existing collection index<br>    collection.release()<br>    collection.drop_index(index_name=&#39;memory_idx&#39;)<br><br>    # Create an index for the embedding field<br>    collection.create_index(<br>            field_name=&quot;embeddings&quot;,<br>            index_params={<br>                &quot;index_type&quot;: &quot;HNSW&quot;,<br>                &quot;metric_type&quot;: &quot;COSINE&quot;,<br>                &quot;params&quot;: {&quot;M&quot;: 64, &quot;efConstruction&quot;: 512},<br>            },<br>            index_name=&quot;memory_idx&quot;<br>    )<br><br>    # Reload collection<br>    collection.load()<br>    <br>    return {<br>        &quot;status&quot;: &quot;Success&quot; if success else &quot;Fail&quot;,<br>        &quot;message&quot;: &quot;Data loaded and indexed successfully&quot; if success else &quot;Data loading failed&quot;<br>    }</pre><p>Enabling <strong>memory=True</strong> activates a diverse array of memory types within the CrewAI framework, including Short-Term Memory, Long-Term Memory, Entity Memory, and Contextual Memory. Each of these components plays a crucial role in enhancing the agent’s ability to recall relevant information, learn from interactions, and maintain coherence throughout conversations. However, it’s important to note that currently, there is no straightforward method for inspecting or retrieving these memory types. Users would need to modify the original implementation by adding logging functionality to track memory interactions, which ultimately undermines the framework’s intention of seamless memory management.</p><p>Further read on CrewAI memory:</p><p><a href="https://docs.crewai.com/concepts/memory">Memory - CrewAI</a></p><p>To support short-term memory (thread-specific memory), I leveraged LangGraph’s checkpointer, allowing the agent to track conversation threads and recall relevant information within a single session.</p><p>Further read on LangGraph checkpointer:</p><p><a href="https://blog.langchain.dev/langgraph-v0-2/">LangGraph v0.2: Increased customization with new checkpointer libraries</a></p><p>Here, the <strong>short-term memory</strong> acts as a conversation buffer, managing ongoing context within a thread or interaction sequence, like email chains, and refreshing the agent’s state each time a thread is invoked or resumed.</p><p>For <strong>long-term memory</strong>, I needed a more durable, flexible storage system than JSON-based InMemoryStore. LangGraph’s InMemoryStore can store memory documents under namespaces and keys, but it lacks semantic similarity search capabilities, making it limited when querying for approximate matches or retrieving contextually similar entries. JSON storage is simplistic and doesn’t inherently support vector-based similarity searching, which is critical for recognizing contextually similar inputs.</p><p>In my approach to long-term memory management, I initially considered a graph-based structure for memory retrieval. Using a graph would allow for time-travel traversal, enabling queries based on timestamps and node similarity. This approach could retrieve context by starting at the most relevant node (the one with the highest similarity score) and then traversing connected neighbours. Filtering by both time and similarity (via node embeddings) would yield a focused subgraph that represents the memory context.</p><p>A graph-based system offers intricate control over relationships and proximity-based filtering, it lacks simplicity and scalability when dealing with high-dimensional similarity queries. Managing and scaling a graph for this purpose would require substantial overhead, particularly for handling node embeddings and maintaining relationships as new data is added over time.</p><p>While handling high-dimensional similarity presents challenges, graphs excel at capturing the precise semantic connections and hierarchical structures that often prove valuable in memory systems. A notable example is AriGraph, a novel approach that integrates knowledge graphs with semantic and episodic memory to create continual learning for agents to enhance their ability to reason, plan, and navigate complex tasks by emulating principles from neuroscience.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiPNMVZtYmVo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiPNMVZtYmVo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiPNMVZtYmVo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffc148ed249ec1f19e232f0310a1ddbe/href">https://medium.com/media/ffc148ed249ec1f19e232f0310a1ddbe/href</a></iframe><p>Instead, I used Milvus, a high-performance vector database designed for similarity search. Milvus inherently supports vector similarity operations, enabling efficient, scalable querying of contextually similar entries. This database provides built-in support for embeddings and approximate nearest neighbor (ANN) searches, simplifying querying for relevant information without requiring extensive graph traversal or custom filtering mechanisms.</p><p>With Milvus, I can maintain a highly performant system that easily handles contextually similar memory entries. The vector-based approach not only reduces the complexity of maintaining memory but also ensures that similarity-based queries are executed efficiently, giving me confidence in its robustness to manage and retrieve memory flexibly.</p><pre># Example current query for memory search based on agentic workflow discussions<br>query = &quot;how do agents work together to collaborate?&quot;<br>query_embedding = embedding_model.embed(query)[0]<br><br>...<br><br># Configure search parameters for vector similarity retrieval<br>search_params = {<br>    &quot;metric_type&quot;: &quot;COSINE&quot;,<br>    &quot;params&quot;: {&quot;M&quot;: 64, &quot;efConstruction&quot;: 512}<br>}<br><br># Perform a vector search on the collection to find relevant memories<br>results = collection.search(<br>    data=[query_embedding],<br>    anns_field=&quot;embeddings&quot;,<br>    param=search_params,<br>    limit=3,<br>    expr=&quot;topic == &#39;agentic_workflow&#39;&quot;,<br>    output_fields=[&#39;text&#39;],<br>    consistency_level=&quot;Strong&quot;<br>)</pre><p>Suppose the current conversation is focused on exploring how multiple agents can collaborate within a workflow to enhance decision-making. The query, <strong>“how do agents work together to collaborate?”</strong>, reflects this topic and is embedded into a dense vector using <strong>FastEmbeddings</strong>, which helps capture the semantic context of the query.</p><p>Using Milvus for vector-based search, this embedding identifies the top three most relevant memories based on cosine similarity. A filter expression narrows the search to memories associated with the topic “agentic_workflow,” focusing on information pertinent to agent collaboration and workflows. The language model, in this case Llama 3.2 is used, determines this topic in the initial step when the agent receives user input.</p><p>The retrieved results, containing only the <strong>‘text’</strong> field, are fed into the agent as memory context. This method allows the agent to incorporate relevant past interactions on agentic workflows, enhancing its ability to provide well-informed and coherent responses based on prior related discussions. The approach strengthens the agent’s ability to support complex workflows by grounding its responses in prior contextual knowledge.</p><p>I designed this interface to showcase how users engage in multi-turn interactions with the AI agent, demonstrating conversation flow and context-aware responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-KHyasU-gdW5eYJaQhIww.png" /><figcaption><strong>Figure 3:</strong> The user interface I created, illustrating multi-turn interactions with the AI agent. The design highlights conversational flow and the agent’s ability to respond with contextual awareness.</figcaption></figure><h3><strong>Final Thoughts</strong></h3><p>In conclusion, this dual memory design — integrating both short- and long-term systems — enables the agent to effectively manage memory-related challenges. Short-term memory proves especially useful for resolving references in conversation, maintaining relevance and accuracy in multi-turn interactions. By combining vector similarity search, topic-based filtering, and session-specific memory within a cohesive memory architecture, the agent delivers dynamic, contextually grounded responses that maintain continuity across conversations.</p><p>This concludes our discussion on memory management in AI agents. In the next part, I will outline how to build effective workflows by leveraging function calling to integrate tools. The tools can be external APIs or your own custom functions. Similarly, I will summarize my key learnings as blueprints and recipes.</p><p>Follow <a href="https://medium.com/towards-generative-ai">Towards Generative AI</a> for more content related to latest in AI advancement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7bd588645a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-generative-ai/ai-agents-in-action-interaction-and-workflow-dynamics-f7bd588645a8">AI Agents in Action: Interaction and Workflow Dynamics</a> was originally published in <a href="https://medium.com/towards-generative-ai">Towards Generative AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>