<?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 Anvesha Mishra on Medium]]></title>
        <description><![CDATA[Stories by Anvesha Mishra on Medium]]></description>
        <link>https://medium.com/@anvesha6496?source=rss-593ede154029------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uNcYbO3aCw3f7BE--Fia5Q.png</url>
            <title>Stories by Anvesha Mishra on Medium</title>
            <link>https://medium.com/@anvesha6496?source=rss-593ede154029------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:27:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anvesha6496/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[Agentic Context Engineering (ACE): Building Self-Correcting AI Workflows]]></title>
            <link>https://medium.com/@anvesha6496/agentic-context-engineering-ace-building-self-correcting-ai-workflows-942ea406f9db?source=rss-593ede154029------2</link>
            <guid isPermaLink="false">https://medium.com/p/942ea406f9db</guid>
            <category><![CDATA[agenticcontextengineering]]></category>
            <dc:creator><![CDATA[Anvesha Mishra]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 22:54:10 GMT</pubDate>
            <atom:updated>2026-02-08T22:54:10.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: Why Context Engineering?</h3><p>In the rapidly evolving landscape of Large Language Models (LLMs), static system prompts are becoming a bottleneck. <strong>Agentic Context Engineering (ACE)</strong> is a paradigm shift where an AI agent doesn’t just follow instructions — it evolves them.</p><p>Based on the research paper <strong>“Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models” (arXiv:2510.04618)</strong>, the effectiveness of the ACE method stems from its ability to treat context as a persistent, evolving “playbook” rather than a static or repeatedly summarized prompt.</p><p>The paper highlights that traditional methods suffer from <strong>“Brevity Bias”</strong> (discarding useful details for the sake of conciseness) and <strong>“Context Collapse”</strong> (iterative rewriting eroding detailed knowledge). ACE solves this through structured, incremental “delta” updates.</p><h3>📈 Key Benchmarking Data</h3><p>The paper evaluates ACE across agent-based and domain-specific (finance) benchmarks, comparing it against strong baselines like GEPA, Dynamic Cheatsheet, and few-shot ICL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWyY5aR93Wmb0kwFDBvQKA.png" /></figure><h3>🚀 Improved Latency &amp; Efficiency</h3><p>The paper identifies ACE as a significantly lower-overhead alternative to both fine-tuning and traditional prompt optimization.</p><ul><li><strong>86.9% Lower Adaptation Latency:</strong> On average, ACE adapts to new information nearly 90% faster than existing methods. This is because ACE performs <strong>incremental delta updates</strong> (adding or modifying small “bullets”) rather than regenerating or rewriting the entire context from scratch.</li><li><strong>Reduced Rollout Costs:</strong> ACE requires significantly fewer “rollouts” (task attempts) to reach peak accuracy.</li><li><strong>Offline (AppWorld):</strong> Reduced latency by <strong>82.3%</strong> and rollouts by <strong>75.1%</strong> compared to GEPA.</li><li><strong>Online (Finance):</strong> Reduced latency by <strong>91.5%</strong> and token costs by <strong>83.6%</strong> compared to Dynamic Cheatsheet.</li></ul><h3>🧠 Why This Method is Effective</h3><ol><li><strong>Avoids Context Collapse:</strong> In the study, a traditional agent at Step 60 had a context of ~18,000 tokens with 66.7% accuracy. By Step 61, a standard rewrite “collapsed” it to 122 tokens, causing accuracy to plummet to 57.1%. <strong>ACE prevents this</strong> by only modifying what is necessary.</li><li><strong>Self-Supervision via Natural Signals:</strong> ACE doesn’t always need human-labeled data. It can learn from “natural execution feedback” — such as whether code successfully ran or if a financial API returned an error — making it highly scalable for autonomous agents.</li><li><strong>Grow-and-Refine Principle:</strong> The system purposefully “grows” the playbook to capture detail and then “refines” (deduplicates and prunes) it only when necessary. This preserves the “domain-specific insights” that models usually throw away when asked to be concise.</li><li><strong>Interpretable Learning:</strong> Unlike fine-tuning (where knowledge is buried in weights), ACE’s learning is visible in the JSON playbook. You can literally read what the agent has “learned” and even manually edit or “unlearn” incorrect strategies.</li></ol><h3>1. The Architecture of ACE</h3><p>The ACE framework consists of a closed-loop system where execution, audit, and memory work in harmony.</p><h3>The Core Components of the ACE Framework</h3><p>The architecture is built on a continuous feedback loop divided into execution, evaluation, and memory management.</p><ul><li><strong>The Generator (The Worker):</strong> This is the primary intelligence responsible for interacting with the user and performing tasks. It functions by reading a “Playbook” of strategic instructions. Its goal is to provide the best possible response based on the current set of rules it has been given.</li><li><strong>The Reflector (The Auditor):</strong> This component acts as the system’s “internal critic.” After the Generator produces an answer, the Reflector compares that answer against a <strong>Ground Truth</strong> — such as real-time data from an API or a set of compliance standards. If the answer is incorrect or suboptimal, the Reflector doesn’t just flag it; it identifies the specific strategic failure that led to the mistake.</li><li><strong>The Curator (The Knowledge Filter):</strong> Not every piece of feedback is worth remembering forever. The Curator acts as a logic gate. It reviews the Reflector’s findings and determines if a new “Delta Rule” (a strategic update) needs to be created. It ensures that the system only learns high-value, repeatable strategies while ignoring one-off noise or duplicate information.</li><li><strong>The Playbook (Persistent Memory):</strong> This is the “Long-term Memory” of the agent. Unlike a model’s fixed training, the Playbook is a dynamic repository of all the rules and corrections learned over time. It serves as the evolving context that is fed back into the Generator for every subsequent task.</li><li><strong>The Pruner (The Knowledge Distiller):</strong> As an agent learns more, its Playbook can become bloated with redundant or conflicting instructions, leading to “context collapse.” The Pruner periodically steps in to synthesize and compress these rules. It merges overlapping strategies into concise “Master Rules,” ensuring the agent remains sharp and efficient without exceeding its “cognitive” limits.</li></ul><h3>Why this is a “Brain” for AI</h3><p>This architecture mimics human learning: we try a task (<strong>Generator</strong>), realize we made a mistake by checking a reference (<strong>Reflector</strong>), decide what we need to do differently next time (<strong>Curator</strong>), remember that lesson (<strong>Playbook</strong>), and eventually simplify our complex lessons into easy-to-follow habits (<strong>Pruner</strong>).</p><blockquote><strong><em>Note:</em></strong><em> </em>The implementation below is a simplified, lightweight demonstration designed to educate readers on the ACE architecture. It serves as a starting point for those curious about how self-correcting memory can be enabled in agents using open-source models like Llama 3 and Mistral.</blockquote><h3>2. Implementation: A Quick Try at Self-Learning</h3><p>To see this architecture in action, we built a basic finance agent. The goal is simple: ensure the agent uses the correct, real-time exchange rate.</p><h3>Setup Instructions</h3><p>To run this code, ensure you have the following environment ready:</p><ol><li><strong>Install Ollama:</strong> Download from <a href="https://ollama.com/">ollama.com</a>.</li><li><strong>Pull Models:</strong></li></ol><pre>ollama pull llama3.2<br>ollama pull mistral</pre><p>3. <strong>Install Python Libraries</strong>:</p><pre>pip install requests ollama</pre><p><strong>The ACE Python Script</strong></p><p>This code demonstrates the “Grow-and-Refine” logic mentioned in the paper, using a live API for grounding.</p><pre>import ollama<br>import uuid<br>import json<br>import os<br>import requests<br><br>PLAYBOOK_FILE = &quot;finance_playbook.json&quot;<br><br># --- 1. THE PLAYBOOK (Memory Management) ---<br>def load_playbook():<br>    if os.path.exists(PLAYBOOK_FILE):<br>        with open(PLAYBOOK_FILE, &quot;r&quot;) as f:<br>            return json.load(f)<br>    return [{&quot;id&quot;: &quot;base_001&quot;, &quot;content&quot;: &quot;You are a Finance Agent. Always convert EUR to USD before summing.&quot;}]<br><br>playbook = load_playbook()<br><br>def save_playbook():<br>    with open(PLAYBOOK_FILE, &quot;w&quot;) as f:<br>        json.dump(playbook, f, indent=4)<br><br>def get_current_instructions():<br>    # Flattens the playbook into a single system string<br>    deltas = &quot;\n&quot;.join([f&quot;- {d[&#39;content&#39;]}&quot; for d in playbook])<br>    return f&quot;STRATEGIC PLAYBOOK:\n{deltas}\n\nTask: Be mathematically precise.&quot;<br><br># --- 1. LIVE GROUND TRUTH ---<br>def get_live_rate(base=&quot;EUR&quot;, target=&quot;USD&quot;):<br>    try:<br>        response = requests.get(f&quot;https://api.frankfurter.app/latest?from={base}&amp;to={target}&quot;)<br>        data = response.json()<br>        return data[&#39;rates&#39;][target]<br>    except Exception as e:<br>        print(f&quot;⚠️ API Error: {e} &quot;)<br>        return 1.18<br><br># --- 2. UPDATED REFLECTOR ---<br>def run_reflector(user_query, agent_output):<br>    # Fetch real-time ground truth<br>    real_rate = get_live_rate()<br>    <br>    reflect_prompt = f&quot;&quot;&quot;<br>    AUDIT REPORT:<br>    Query: {user_query}<br>    Agent Answer: {agent_output}<br>    Correct Rate: 1 EUR = {real_rate} USD.<br><br>    CHECKLIST:<br>    1. Did the agent use the EXACT rate {real_rate}? <br>    2. Did the agent sum the values correctly?<br><br>    If the answer is mathematically and strategically correct, output &#39;PASS&#39;.<br>    If not, output ONE general strategy (RULE:) to prevent this error.<br>    &quot;&quot;&quot;<br>    <br>    response = ollama.chat(model=&#39;mistral&#39;, messages=[{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: reflect_prompt}])<br>    return response[&#39;message&#39;][&#39;content&#39;].strip()<br><br># --- 3. UPDATED PRUNER (Knowledge Consolidation) ---<br>def prune_playbook():<br>    global playbook<br>    if len(playbook) &lt;= 3:<br>        return <br><br>    print(&quot;\n[Pruner] 🧹 Knowledge limit reached. Distilling Master Rules...&quot;)<br>    all_rules = &quot;\n&quot;.join([f&quot;- {item[&#39;content&#39;]}&quot; for item in playbook])<br>    <br>    prune_prompt = f&quot;&quot;&quot;<br>    Analyze these learned behaviors:<br>    {all_rules}<br><br>    Consolidate them into exactly 3 Master Rules. <br>    Ensure the most recent exchange rate requirements are preserved.<br>    &quot;&quot;&quot;<br>    <br>    response = ollama.chat(model=&#39;mistral&#39;, messages=[{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: prune_prompt}])<br>    summary = response[&#39;message&#39;][&#39;content&#39;].strip()<br><br>    playbook = [{&quot;id&quot;: f&quot;master_{uuid.uuid4().hex[:4]}&quot;, &quot;content&quot;: summary}]<br>    save_playbook()<br>    print(&quot;✅ [Pruner] Knowledge distilled.&quot;)<br><br># --- 4. THE CURATOR (The Filter) ---<br>def run_curator(reflection):<br>    if &quot;PASS&quot; in reflection.upper()[:10]:<br>        print(&quot;❌ [Curator] Success. No bloat added.&quot;)<br>        return<br><br>    # Extract rule and avoid duplication<br>    new_rule = reflection.split(&quot;RULE:&quot;)[-1].strip()<br>    if not any(new_rule[:30] in item[&#39;content&#39;] for item in playbook):<br>        delta_id = f&quot;delta_{uuid.uuid4().hex[:4]}&quot;<br>        playbook.append({&quot;id&quot;: delta_id, &quot;content&quot;: new_rule})<br>        print(f&quot;✅ [Curator] NEW STRATEGY ADDED: {new_rule}&quot;)<br>        save_playbook()<br>        prune_playbook() # Maintain efficiency<br><br># --- 5. EXECUTION ---<br>def run_task(query):<br>    print(f&quot;\n--- TASK: {query} ---&quot;)<br>    instructions = get_current_instructions()<br>    <br>    # Generator Call<br>    response = ollama.chat(model=&#39;llama3.2&#39;, messages=[<br>        {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: instructions},<br>        {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: query}<br>    ])<br>    output = response[&#39;message&#39;][&#39;content&#39;]<br>    print(f&quot;AGENT OUTPUT: {output}&quot;)<br>    <br>    # Reflection &amp; Learning<br>    reflection = run_reflector(query, output)<br>    print(f&quot;[Reflector Decision]: {reflection}&quot;)<br>    run_curator(reflection)<br><br># Example usage<br>run_task(&quot;Portfolio: 500 EUR and 1000 USD. Total in USD?&quot;)<br>run_task(&quot;Separate account: 100 EUR. Total in USD?&quot;)</pre><h3>3. Real-World Trace Analysis</h3><p>In a quick test run, the agent initially used a generic rate of <strong>1.10</strong>. The <strong>Reflector</strong> caught this, fetched the live rate (<strong>1.08</strong>), and generated a rule: <em>“Always verify the current rate from the API.”</em> By the second task, the <strong>Generator</strong> read the updated Playbook and corrected its behavior automatically. This mimics the “Self-Improving” loop described in the research paper — learning from execution feedback without human intervention.</p><p>The Curator successfully injected this into the finance_playbook.json. In subsequent tasks, this playbook gets loaded:</p><pre>[<br>    {<br>        &quot;id&quot;: &quot;base_001&quot;,<br>        &quot;content&quot;: &quot;You are a Finance Agent. Always convert EUR to USD before summing.&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;delta_aafd&quot;,<br>        &quot;content&quot;: &quot;RULE: Always use the rate 1.1794 for EUR/USD conversions as per latest financial audits.&quot;<br>    }<br>]</pre><h3>4. Key Takeaways</h3><ol><li><strong>Context Efficiency:</strong> Instead of training a new model, we simply update a small JSON file that “guides” the existing model.</li><li><strong>Deterministic Auditing:</strong> By using the Reflector (Mistral) to audit the Generator (Llama), we create a “Checks and Balances” system.</li><li><strong>Knowledge Distillation:</strong> The Pruner ensures the agent doesn’t get bogged down by thousands of rules, keeping the most relevant logic at the top.</li></ol><h3>5. Summary Breakdown of the Logic:</h3><p>The following diagram illustrates the lifecycle of a query within the ACE ecosystem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBQyZVLZ5w3FeSj8wbbeGA.png" /><figcaption>ace architecture example</figcaption></figure><ol><li><strong>Injection:</strong> The get_current_instructions() function reads the JSON Playbook and injects it into the <strong>Generator&#39;s</strong> system prompt.</li><li><strong>Audit:</strong> The <strong>Reflector</strong> doesn’t just guess; it calls get_live_rate() to fetch the real-world value from the <strong>Frankfurter API</strong>.</li><li><strong>Reinforcement:</strong> If the Reflector identifies a discrepancy (like the 1.10 vs 1.1794 difference in your output), the <strong>Curator</strong> writes that specific correction back to the finance_playbook.json.</li><li><strong>Optimization:</strong> Once the playbook grows too large, the <strong>Pruner</strong> uses Mistral to “crunch” the rules down into a high-density summary so the Llama 3.2 model doesn’t get overwhelmed by a long system prompt.</li></ol><h3>📚 Resources for Further Reading</h3><p>To dive deeper into the concepts of Agentic Context Engineering and self-evolving AI systems, refer to these foundational resources:</p><ul><li><strong>Core Research Paper:</strong> <a href="https://arxiv.org/abs/2510.04618">ACE: Agentic Context Engineering (arXiv:2510.04618)</a> — The official paper detailing the theory and performance metrics.</li><li><strong>Official Framework:</strong> <a href="https://github.com/ace-agent/ace">ACE GitHub Repository</a> — Access the source code, implementation guides, and latest updates from the developers.</li><li><strong>Prompt Engineering Guide:</strong> <a href="https://www.promptingguide.ai/">DARE (Distillation and Refinement)</a> — Learn more about how instructions can be compressed without losing semantic meaning.</li><li><strong>Infrastructure:</strong> <a href="https://ollama.com/library">Ollama Documentation</a> — Learn how to swap models (e.g., using Llama 3.3 or DeepSeek) to see how they handle the Reflection cycle differently.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=942ea406f9db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Metadata RAG — Using LLMs for Metadata Generation]]></title>
            <link>https://medium.com/@anvesha6496/dynamic-metadata-rag-using-llms-for-metadata-generation-939c3e0fa05b?source=rss-593ede154029------2</link>
            <guid isPermaLink="false">https://medium.com/p/939c3e0fa05b</guid>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[qdrant]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[structured-output]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Anvesha Mishra]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 15:59:25 GMT</pubDate>
            <atom:updated>2024-10-01T15:59:25.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Metadata RAG — Using LLMs for Metadata Generation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ii10gL9_fN6bF94nIX5kEw.png" /><figcaption>AI generated image for metadata extraction from query</figcaption></figure><p><strong>Why Metadata Matters for Semantic Search</strong></p><p>Metadata boosts search by providing context, improving relevance, and speeding up results through filters like tags, categories, or dates. It helps AI make connections, personalize responses, and support deeper knowledge graphs.</p><p><strong>Example:<br></strong>In a search for “apple,” metadata helps distinguish between “Apple” the company and “apple” the fruit by tagging them with categories like “technology” or “food.”</p><p>LLMs are great at generating natural language but can struggle with specific or recent information. Retrieval-Augmented Generation (RAG) solves this by letting LLMs pull in real-time data from external sources, combining generation and retrieval for more accurate, up-to-date answers.</p><p>RAG accuracy improves with dynamic metadata by allowing more precise filtering of information during retrieval. Metadata like topics or categories helps narrow down search results, making responses faster, more relevant, and contextually accurate.</p><h3>Technology Stack Overview</h3><p><strong>Dataset: Unstructured Text with Rich Metadata</strong></p><p>The <strong>Yelp dataset</strong> comprises unstructured text, such as customer reviews and business descriptions, enriched by structured metadata like business categories, locations, and ratings. Using the <strong>Structured Output API</strong>, we extract and organize this metadata from the unstructured text, making it easier to refine search results and provide personalized outputs.</p><p><strong>LLMs: OpenAI GPT-4<br></strong>For natural language processing tasks, we’re leveraging OpenAI’s GPT-4.In this setup, it’s used to extract metadata and respond to queries from the Yelp dataset, which contains diverse, unstructured customer feedback.</p><p><strong>Vector Database: Qdrant<br></strong>To efficiently manage and search through the Yelp dataset, we use <strong>Qdrant</strong> as the vector database. Qdrant stores the vector embeddings in a format optimized for rapid semantic search. This allows the system to retrieve the most relevant Yelp reviews based on user queries.</p><p>By integrating <a href="https://qdrant.tech/">Qdrant</a> with LLMs, we enhance the search experience, offering deeper semantic insights into customer reviews while leveraging the structured metadata obtained through the <strong>Structured Output API</strong> (e.g., OpenAI).</p><p>Let’s go through the process step by step.</p><h4>Step 1 — Extracting Metadata Using LLMs</h4><h4>Explanation of the Process: Using JSON Structured Outputs from LLMs</h4><p>The first step in leveraging Large Language Models (LLMs) for metadata extraction involves using their ability to process unstructured text and output structured data. By providing the LLM with a specific prompt or instruction, you can extract important details from raw text and return them in a <strong>JSON format</strong>. This structured output is essential for organizing key information — like categories, dates, or ratings — from unstructured text, such as customer reviews or product descriptions.</p><p>For instance, if you’re working with a dataset like <strong>Yelp reviews</strong>, an LLM can analyze a review and extract relevant metadata such as the business name, type of service, customer sentiment, and review date. The output would be in a predefined JSON structure, ensuring that all relevant metadata fields are captured in an organized fashion, ready to be processed further or stored in a database.</p><h4>How to Leverage the Structured Output API (e.g., OpenAI) to Extract and Structure Metadata from Unstructured Text</h4><p>The <strong>Structured Output API</strong>, provided by platforms like OpenAI, allows developers to interact with LLMs and request <strong>structured outputs</strong> such as JSON. To extract metadata from unstructured text, the process generally works as follows:</p><ol><li><strong>Define a Prompt</strong>: Start by crafting a prompt that instructs the LLM to extract specific metadata fields. For example, for a Yelp review, the prompt might be: “Extract the business name, review date, star rating, and review sentiment from the following review.”</li><li><strong>Request Structured Output in JSON Format</strong>: You can explicitly ask the model to return the data in <strong>JSON</strong>. A typical request could look like this:<br><em>Input</em>:<br>“Extract the following information and return it in JSON format:</li></ol><ul><li>Business Name</li><li>Date of Review</li><li>Star Rating</li><li>Sentiment</li><li>Categories”</li></ul><p>The API will then generate the output in a structured JSON format, organizing the extracted data as requested.</p><blockquote><strong>Example -</strong></blockquote><blockquote>Review: ‘I had an amazing experience at Sushi Zen in San Francisco on September 10, 2023. The sushi was fresh, the ambiance was delightful, and the staff was incredibly friendly. I would definitely recommend this place to anyone who loves sushi! 5 stars from me!’”</blockquote><blockquote>Extracted metadata :<br>{<br> “business_name”: “Sushi Zen”,<br> “date_of_review”: “September 10, 2023”,<br> “star_rating”: 5,<br> “sentiment”: “positive”,<br> “categories”: [“Sushi”, “Restaurant”]<br>}</blockquote><p><strong>Handle Complex or Nested Data</strong>: For more complex data, you can nest fields within the JSON structure, such as associating specific tags with categories or providing detailed breakdowns of user sentiment (e.g., “positive,” “neutral,” or “negative”) within different sections of the review.</p><p>By using this approach, you streamline the process of organizing unstructured data into well-defined, structured outputs. The <strong>Structured Output API</strong> takes care of the heavy lifting, parsing natural language input and transforming it into a machine-readable format.</p><h3>Step 2 — Storing Metadata in a Vector Database</h3><p>Once metadata is extracted using LLMs, the next step is to store it effectively alongside vector embeddings in a vector database like <strong>Qdrant</strong>. This process allows for efficient and scalable search operations that combine both semantic similarity from embeddings and structured filtering from metadata.</p><h4>Using Vector Embeddings and Metadata Insertion into Qdrant</h4><p>Qdrant stores vector embeddings alongside structured metadata like categories, timestamps, or ratings, enriching the search and retrieval process.</p><p>By combining these two elements, Qdrant can store both the semantic information (embeddings) and the structured context (metadata) for each data point, enabling more powerful search capabilities.</p><h4>How Metadata Complements Embeddings in Vector Search</h4><p>Okay, let us now see the code in action.</p><h4>Example: Inserting Vector Points with Both Embeddings and Metadata Fields</h4><p>In practice, inserting data into Qdrant with both embeddings and metadata fields works as follows:</p><pre>import uuid<br>from qdrant_client import QdrantClient<br>from qdrant_client.http import models<br>from sentence_transformers import SentenceTransformer<br><br># Initialize the SentenceTransformer model<br>embedder = SentenceTransformer(&quot;sentence-transformers/multi-qa-MiniLM-L6-cos-v1&quot;)<br><br># Initialize the Qdrant client<br>client = QdrantClient(host=&#39;localhost&#39;, port=6333)<br><br># Collection name<br>collection_name = &quot;yelp_reviews&quot;<br><br># Step 1: Create the collection if it doesn&#39;t exist<br>try:<br>    client.create_collection(<br>        collection_name=collection_name,<br>        vectors_config=models.VectorParams(<br>            size=384,  # The correct output dimension of the embedding model<br>            distance=models.Distance.COSINE  # Use cosine similarity for vector search<br>        )<br>    )<br>except Exception as e:<br>    print(f&quot;Collection might already exist or another error occurred: {e}&quot;)<br><br># Example Yelp reviews<br>reviews = [<br>    {<br>        &quot;text&quot;: &quot;The sushi here is fresh and the service is excellent.&quot;,<br>        &quot;business_name&quot;: &quot;Sushi Delight&quot;,<br>        &quot;category&quot;: &quot;sushi&quot;,<br>        &quot;city&quot;: &quot;San Francisco&quot;,<br>        &quot;rating&quot;: 4.8,<br>        &quot;date&quot;: &quot;2023-09-05&quot;,<br>        &quot;review_sentiment&quot;: &quot;positive&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Great pizza but the crust was a little too thick for my taste.&quot;,<br>        &quot;business_name&quot;: &quot;Pizza Palace&quot;,<br>        &quot;category&quot;: &quot;pizza&quot;,<br>        &quot;city&quot;: &quot;New York&quot;,<br>        &quot;rating&quot;: 4.0,<br>        &quot;date&quot;: &quot;2023-09-05&quot;,<br>        &quot;review_sentiment&quot;: &quot;neutral&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Amazing sushi, quick service, and friendly staff!&quot;,<br>        &quot;business_name&quot;: &quot;Sushi Express&quot;,<br>        &quot;category&quot;: &quot;sushi&quot;,<br>        &quot;city&quot;: &quot;Los Angeles&quot;,<br>        &quot;rating&quot;: 4.5,<br>        &quot;date&quot;: &quot;2023-09-05&quot;,<br>        &quot;review_sentiment&quot;: &quot;positive&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Fantastic sushi and nice atmosphere!&quot;,<br>        &quot;business_name&quot;: &quot;Sushi Heaven&quot;,<br>        &quot;category&quot;: &quot;sushi&quot;,<br>        &quot;city&quot;: &quot;San Francisco&quot;,<br>        &quot;rating&quot;: 4.6,<br>        &quot;date&quot;: &quot;2023-09-05&quot;,<br>        &quot;review_sentiment&quot;: &quot;positive&quot;<br>    }<br>]<br><br># Step 2: Prepare data for insertion<br>points = []<br>for review in reviews:<br>    # Generate vector embedding using SentenceTransformer<br>    embedding = embedder.encode(review[&quot;text&quot;]).tolist()  # Convert the embedding to a list of floats<br><br>    # Generate a valid UUID for the point ID<br>    point_id = str(uuid.uuid4())<br><br>    # Prepare metadata extracted from the review<br>    metadata = {<br>        &quot;business_name&quot;: review[&quot;business_name&quot;],<br>        &quot;category&quot;: review[&quot;category&quot;],<br>        &quot;city&quot;: review[&quot;city&quot;],<br>        &quot;rating&quot;: review[&quot;rating&quot;],<br>        &quot;date&quot;: review[&quot;date&quot;],<br>        &quot;review_sentiment&quot;: review[&quot;review_sentiment&quot;]<br>    }<br><br>    # Append to points list<br>    points.append(models.Batch(<br>        ids=[point_id],  # Generate UUID for the ID<br>        vectors=[embedding],  # List of vectors (embeddings)<br>        payloads=[metadata]  # List of metadata payloads<br>    ))<br><br># Step 3: Insert data into Qdrant with embeddings and metadata<br>try:<br>    # Flatten the list of points for upsert<br>    for point in points:<br>        client.upsert(<br>            collection_name=collection_name,<br>            points=point  # Insert each point one at a time<br>        )<br>    print(&quot;All reviews inserted successfully.&quot;)<br>except Exception as e:<br>    print(f&quot;Error during upsert: {e}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qJ5NFSs0KozPWQOx" /><figcaption>Snapshot of Qdrant after inserting data points</figcaption></figure><p>In this example, both the vector representation of the review (capturing its semantic meaning) and the metadata (business name, category, city, and rating) are stored in Qdrant. When performing search queries, both the vector similarity and metadata fields can be utilized to refine and enhance retrieval accuracy.</p><h3>Step 3 — Performing Filtered Similarity Search</h3><p>Once data is stored with both embeddings and metadata in Qdrant, the next step is to perform <strong>filtered similarity searches</strong>. This allows for highly relevant, context-aware retrieval by combining vector-based semantic search with metadata-based filters.</p><h4>How to Perform Filtered Similarity Searches in Qdrant Using Metadata</h4><p>Qdrant enables <strong>filtered similarity searches</strong> by allowing users to define filters based on metadata fields. During a search query, in addition to retrieving the most semantically similar vectors (based on cosine or other distance metrics), you can specify conditions that limit the search space based on specific metadata values.</p><p>For example, if a user searches for “best coffee shop in New York,” Qdrant can retrieve vector embeddings that match the query semantically, while filtering for reviews with metadata where the “category” is “coffee shop” and the “city” is “New York.”</p><p>Here’s how you might perform a filtered similarity search in Qdrant:</p><pre># Now perform a filtered scrolling operation to retrieve all data that matches the specified conditions<br># Initialize scrolling<br>scroll_limit = 100  # Number of results to retrieve in one scroll<br>print(&quot;\nScrolling through entries matching specified conditions…&quot;)<br><br>scroll_results, next_page_offset = client.scroll(<br>    collection_name=collection_name,<br>    scroll_filter=models.Filter(<br>        must=[<br>            models.FieldCondition(key=&quot;category&quot;, match=models.MatchValue(value=&quot;sushi&quot;)),<br>            models.FieldCondition(key=&quot;city&quot;, match=models.MatchValue(value=&quot;San Francisco&quot;)),<br>            models.FieldCondition(key=&quot;rating&quot;, range=models.Range(gte=4.4)),  # Filter for highly-rated restaurants<br>            models.FieldCondition(key=&quot;review_sentiment&quot;, match=models.MatchValue(value=&quot;positive&quot;))<br>        ]<br>    ),<br>    limit=scroll_limit,<br>    with_payload=True,<br>    with_vectors=True,<br>)<br><br># Check if scroll_results is not None and contains data<br>if scroll_results and isinstance(scroll_results, list) and len(scroll_results) &gt; 0:<br>    print(&quot;Results found:&quot;)<br>    for result in scroll_results:<br>        if result:  # Check if result is not None<br>            business_name = result.payload.get(&quot;business_name&quot;, &quot;Unknown&quot;)<br>            category = result.payload.get(&quot;category&quot;, &quot;N/A&quot;)<br>            city = result.payload.get(&quot;city&quot;, &quot;N/A&quot;)<br>            rating = result.payload.get(&quot;rating&quot;, &quot;N/A&quot;)<br>            print(f&quot;Business: {business_name}, Category: {category}, City: {city}, Rating: {rating}&quot;)<br>else:<br>    print(&quot;No results found for the specified conditions.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i1rPmvOY0Oc7Jq5E" /><figcaption>Output using filtered search</figcaption></figure><p>In this query, the <strong>filter</strong> narrows down the results to only include reviews with the relevant metadata fields, significantly improving the relevance and accuracy of the results.</p><h4>Extracting Metadata from Queries to Enhance Search Relevance</h4><p>Filtered searches are helpful, but we won’t know exactly what the matching conditions are without knowing what the user has been looking for! To solve this, we can extract metadata from the query to use it for filtered search using an LLM.</p><p>Here’s how this process works:</p><ol><li><strong>Extract Metadata</strong>: Use an LLM to parse the query and extract relevant metadata fields like category, city, and rating.</li><li><strong>Combine Metadata with Embeddings</strong>: Generate a vector embedding from the query for semantic similarity search, while using the extracted metadata fields to filter the results.</li></ol><pre><br>from openai import OpenAI<br>from qdrant_client import QdrantClient<br>from qdrant_client.http import models<br>from sentence_transformers import SentenceTransformer<br>from pydantic import BaseModel<br>import openai<br>import json<br><br># Initialize the SentenceTransformer model for generating embeddings<br>embedder = SentenceTransformer(&quot;sentence-transformers/multi-qa-MiniLM-L6-cos-v1&quot;)<br><br># Initialize the Qdrant client for vector search<br>qdrant_client = QdrantClient(host=&#39;localhost&#39;, port=6333)<br><br># Define the Pydantic model for structured metadata extraction (no default in the schema)<br>class Metadata(BaseModel):<br>    category: str<br>    city: str<br>    rating: float  # No default here in the schema<br><br># Initialize OpenAI API key (use your own key)<br>client = OpenAI(api_key=&quot;YOUR_OPENAI_API_KEY&quot;)<br><br># Sample query: &quot;Find me highly-rated sushi places in San Francisco&quot;<br>query_text = &quot;Find me highly-rated sushi places in San Francisco&quot;<br><br># Structure the schema for the LLM to adhere to:<br>schema = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;category&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;Type of restaurant or cuisine&quot;},<br>        &quot;city&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;City where the restaurant is located&quot;},<br>        &quot;rating&quot;: {&quot;type&quot;: &quot;number&quot;, &quot;description&quot;: &quot;Desired rating of the restaurant&quot;}<br>    },<br>    &quot;required&quot;: [&quot;category&quot;, &quot;city&quot;],<br>    &quot;additionalProperties&quot;: False<br>}<br><br># Convert the schema to JSON for clarity in the prompt<br>schema_json = json.dumps(schema, indent=2)<br><br>system_prompt = f&quot;&quot;&quot;<br>You are a highly skilled data analyst specializing in structured metadata extraction.<br>Your task is to extract metadata from a user&#39;s query and return it in a strictly formatted JSON structure.<br>Adhere **exactly** to the schema provided, and follow these rules:<br><br>1. Extract the relevant metadata based on the user&#39;s query, ensuring that the fields match the schema.<br>2. For the &quot;category&quot; field, extract the type of cuisine (e.g., Sushi, Italian, etc.).<br>3. For the &quot;city&quot; field, extract the name of the city.<br>4. For the &quot;rating&quot; field, extract the restaurant&#39;s rating, or if the rating is not explicitly mentioned in the query, infer the value based on the query context (e.g., &quot;highly-rated&quot; means a rating of 4.5 or higher). Use a rating of **4.0** as a sensible default if unsure.<br>5. Do not omit any required fields in the JSON structure. If some information is not directly available, guess the best value or use sensible defaults.<br>6. Always return the output in **valid JSON format** as per the schema below. Do not include additional fields not defined in the schema.<br><br>Schema:<br>{schema_json}<br>&quot;&quot;&quot;<br><br><br>user_prompt = f&quot;This is the query: {query_text}&quot;<br><br># Define the tool using pydantic_function_tool<br>metadata_tool = openai.pydantic_function_tool(Metadata)<br><br># Make a call to OpenAI GPT-4o using the tool<br>completion = client.beta.chat.completions.parse(<br>    model=&quot;gpt-4o-2024-08-06&quot;,  # Use the correct GPT-4o model<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: system_prompt<br>        },<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: user_prompt<br>        }<br>    ],<br>    tools=[metadata_tool]  # Pass the metadata extraction tool<br>)<br><br># DEBUG: Check the full completion object to see if tool_calls exist<br>print(&quot;Full completion response:&quot;, completion)<br><br># Extract the parsed arguments<br>if completion.choices and completion.choices[0].message.tool_calls:<br>    parsed_metadata = completion.choices[0].message.tool_calls[0].function.parsed_arguments<br>    metadata = Metadata.parse_obj(parsed_metadata)<br>else:<br>    print(&quot;No tool calls found in the completion response.&quot;)<br>    metadata = Metadata(category=&quot;unknown&quot;, city=&quot;unknown&quot;, rating=4.0)<br><br># Apply default rating logic if not provided in the extracted metadata<br>if not hasattr(metadata, &#39;rating&#39;) or metadata.rating is None:<br>    metadata.rating = 4.0  # Set default rating<br><br># Print the extracted metadata<br>print(f&quot;Extracted Metadata: {metadata.dict()}&quot;)<br>if completion.choices:<br>    print(&quot;Tool Calls:&quot;, completion.choices[0].message.tool_calls)<br><br># Generate embedding for the query text<br>query_embedding = embedder.encode(query_text).tolist()<br><br># Create metadata filters based on the extracted metadata<br>filters = []<br><br>if metadata.category:<br>    filters.append(models.FieldCondition(key=&quot;category&quot;, match=models.MatchValue(value=metadata.category.lower())))<br>if metadata.city:<br>    filters.append(models.FieldCondition(key=&quot;city&quot;, match=models.MatchValue(value=metadata.city)))<br>if metadata.rating:<br>    filters.append(models.FieldCondition(key=&quot;rating&quot;, range=models.Range(gte=metadata.rating)))<br>print(&quot;Filters applied to Qdrant:&quot;, filters)<br><br># Perform the filtered search with Qdrant<br>scroll_limit = 100<br>search_results, next_page_offset = qdrant_client.scroll(<br>    collection_name=&quot;yelp_reviews&quot;,<br>    scroll_filter=models.Filter(must=filters),<br>    limit=scroll_limit,<br>    with_payload=True,<br>    with_vectors=False<br>)<br><br># Output the results<br>if search_results and isinstance(search_results, list) and len(search_results) &gt; 0:<br>    print(&quot;Results found using metadata and vector similarity:&quot;)<br>    for result in search_results:<br>        if result:  # Check if result is not None<br>            business_name = result.payload.get(&quot;business_name&quot;, &quot;Unknown&quot;)<br>            category = result.payload.get(&quot;category&quot;, &quot;N/A&quot;)<br>            city = result.payload.get(&quot;city&quot;, &quot;N/A&quot;)<br>            rating = result.payload.get(&quot;rating&quot;, &quot;N/A&quot;)<br>            print(f&quot;Business: {business_name}, Category: {category}, City: {city}, Rating: {rating}&quot;)<br>else:<br>    print(&quot;No results found for the specified conditions.&quot;)</pre><p>By combining both the vector embedding and the metadata filter extracted from the query, this approach ensures the results are semantically relevant (matching the intent behind “pizza places”) while being contextually accurate (showing only highly-rated options in Chicago). Note how the structured output api has been used to directly access the metadata from the queries for search.</p><h3>Difference in Output:</h3><p>So for the query —</p><p>“Find me highly-rated sushi places in San Francisco”</p><ul><li><strong>Filtered Search Output:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W1hVk0Fhqlb4GPL5" /><figcaption>Output using StructuredOutput API for extracting metadata from queries followed by filtering</figcaption></figure><p>This only returns results that match the specified metadata (i.e., restaurants with category: sushi, city: San Francisco, and rating &gt;= 4.4).</p><ul><li><strong>Non-filtered Search Output:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6R-fMGUXRl-ZjKqp" /><figcaption>Output without metadata extraction from queries</figcaption></figure><p>Returns results based solely on vector similarity to the query, which might include irrelevant entries such as <strong>Pizza Palace</strong>, because there are no metadata restrictions.</p><h3>Conclusion</h3><p>In this article, we explored how dynamic metadata can enhance Retrieval-Augmented Generation (RAG) workflows, making search smarter and more accurate. By using LLMs to extract metadata from unstructured text, we can filter search results more effectively — ensuring relevance by narrowing down results based on specific criteria like location, ratings, and categories. Combining this metadata with vector embeddings stored in a database like Qdrant adds both context and precision to searches.</p><p>Dynamic metadata helps refine the retrieval process, allowing for more personalized and relevant results. It complements the semantic capabilities of LLMs, making RAG systems faster and more useful, especially for large datasets like Yelp reviews.</p><p>Looking ahead, the role of LLMs in metadata generation will continue to grow, impacting industries from e-commerce to personalized content. By bridging the gap between unstructured text and structured data, LLMs can help build more efficient, context-aware AI systems that better serve users’ needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939c3e0fa05b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing the Power of Corrective RAG (CRAG): Building High-Precision Recommendation Systems with…]]></title>
            <link>https://medium.com/@anvesha6496/harnessing-the-power-of-corrective-rag-crag-building-high-precision-recommendation-systems-with-e9afaa3199ed?source=rss-593ede154029------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9afaa3199ed</guid>
            <category><![CDATA[corrective-rag]]></category>
            <category><![CDATA[qdrant]]></category>
            <category><![CDATA[llama-3]]></category>
            <dc:creator><![CDATA[Anvesha Mishra]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 18:22:02 GMT</pubDate>
            <atom:updated>2024-08-25T18:22:02.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Harnessing the Power of Corrective RAG (CRAG): Building High-Precision Recommendation Systems with Qdrant &amp; Llama 3</h3><h3>What are recommendation systems?</h3><p>Scrolling through your favourite social media app and seeing content tailored to your preferences, or picking a movie to watch that appeared on your Netflix home screen, are all examples of recommendation systems. In the simplest of terms, a recommendation system is a technology that helps users find items or content that might interest them. Not only do they play a huge role in enhancing user experience, they also provide tons of benefits to business owners. From “you might also like” nudges to sharing “what other customers are buying”, these systems can bump up sales by a whopping 10–50%!</p><p><strong>Types of Recommendation Systems:</strong></p><ul><li><strong>Collaborative Filtering</strong>: This type suggests items based on what similar users liked. Imagine it as a buddy system — if people with tastes like yours loved a certain book or movie, it’s likely you’ll enjoy it too!</li><li><strong>Content-Based Filtering</strong>: This approach recommends items similar to the ones you’ve shown an interest in before.</li></ul><p>If you only know which interactions happened in the past, collaborative filtering is your go-to method. However, if you have additional data about users and items, you can enhance your predictions by using content and context filtering to gauge the likelihood of new interactions. A hybrid approach is often used, depending on the type of data you have access to.</p><h3>What Is Corrective RAG?</h3><p>RAG boosts language models by using retrieved documents, but it can falter if those documents aren’t relevant. To tackle this, Corrective RAG (CRAG) was developed, which makes these systems more reliable. CRAG has a simple evaluator that checks the quality of the documents and decides the next steps based on confidence levels. To ensure we’re getting the best responses, CRAG also pulls data from the web, not just static databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/0*VpeGEuucvLmevQJy" /><figcaption>Diagrammatic outline for CRAG</figcaption></figure><p>We will understand CRAG in depth in the following sections but, before that, let us quickly define the scope and prerequisites for this tutorial.</p><p><strong>Purpose:</strong> This guide aims to demonstrate how to build high-precision recommendation systems by leveraging the Corrective RAG (CRAG) framework, using Qdrant for vector similarity search of stored data points and Llama 3 as LLM for generating responses.</p><p><strong>Prerequisites:</strong> To follow this guide, you should have a basic understanding of machine learning concepts, particularly in natural language processing (NLP) and recommendation systems. Familiarity with vector databases, Python programming, and a few tools like Qdrant, Llama 3 and Taviliy is also recommended.</p><h3>Understanding Corrective RAG</h3><p>Corrective Retrieval-Augmented Generation (CRAG) is a framework designed to enhance the robustness and accuracy of language model-generated responses. Unlike standard RAG systems, CRAG introduces a corrective layer to ensure the relevance and reliability of the retrieved information.</p><h4>Components Involved in Corrective RAG:</h4><h4>1. Retrieval</h4><p>The retrieval component involves fetching relevant documents from both static databases and large-scale web searches. This stage aims to gather a broad range of potential information sources that may answer the input query. It leverages existing retrieval mechanisms and also rewrites queries to perform web searches, thereby extending the scope and diversity of the retrieved content.</p><h4>2. Knowledge Correction</h4><p>This component refines and verifies the relevance and accuracy of the retrieved documents. It comprises three sub-components:</p><p><strong>2.a. Retrieval Evaluator</strong></p><p>The retrieval evaluator assesses the relevance of each document or knowledge strip against the input query. Using a fine-tuned model, it assigns confidence scores to determine if the content is Correct, Incorrect, or Ambiguous. This scoring helps decide whether the documents should be used directly for response generation, discarded, or supplemented with additional data.</p><p><strong>2.b. Knowledge Refinement</strong></p><p>In the knowledge refinement step, each relevant document is broken down into fine-grained knowledge strips. These strips are individually evaluated for relevance, with irrelevant strips filtered out. The remaining relevant strips are then recomposed into coherent internal knowledge, which provides precise and concise information to the generator.</p><p><strong>2.c. Knowledge Searching (Web Search)</strong></p><p>When static sources fail to provide relevant information, the knowledge searching component comes into play. It uses web searches to find external knowledge. The process involves rewriting the query into keyword-rich prompts, retrieving relevant web pages, and extracting their content. This content is then refined similarly to the internal knowledge, ensuring only the most relevant information is retained.</p><h4>3. Generator</h4><p>The generator is the final stage, where an arbitrary generative model utilizes the refined knowledge (both internal and external) to produce the final response. It synthesizes the processed information into coherent, contextually appropriate outputs, ensuring that the responses are based on the most relevant and accurate data available.</p><p>Together, these components ensure that the CRAG system not only retrieves relevant information but also critically evaluates and refines it to enhance the overall quality and reliability of the generated responses.</p><p>Feel free to browse through the research paper on<a href="https://arxiv.org/pdf/2401.15884"> Corrective RAG (CRAG)</a> to study this in depth. The paper also demonstrates how CRAG can be seamlessly integrated with existing models, offering a lightweight yet powerful solution for improving language generation systems.</p><h4>Advantages of Corrective RAG Over Traditional Methods</h4><ol><li><strong>Higher Accuracy</strong>: The use of a retrieval evaluator and corrective actions lead to a more accurate selection and utilization of information. For instance, in evaluations, CRAG showed substantial improvements over standard RAG and other advanced methods like Self-RAG across various datasets, with accuracy improvements of up to 36.6% on certain tasks.</li><li><strong>Consistent Performance Across Tasks</strong>: CRAG’s ability to refine and correct information ensures that it performs well across different types of tasks, whether short-form or long-form content generation. This consistency is crucial for applications requiring precise and contextually accurate responses.</li><li><strong>Enhanced Adaptability</strong>: CRAG is designed to work with various underlying LLMs without needing specific instruction tuning for critic tokens, unlike some advanced methods. This adaptability allows it to maintain high precision even when switching between different models, providing a plug-and-play solution that can leverage the best available language models.</li></ol><h3>Let’s now go over the tools needed for this guide.</h3><h4>1. Qdrant: Vector Search Engine</h4><p><a href="https://qdrant.tech/">Qdrant </a>is a highly efficient vector search engine designed for high-dimensional vector searches, commonly used in applications such as recommendation systems, semantic search, and machine learning model retrievals. Key features of Qdrant include:</p><ul><li><strong>High-Speed Vector Searches</strong>: Qdrant excels in performing rapid and accurate searches across large datasets of high-dimensional vectors.</li><li><strong>Scalability</strong>: It can scale horizontally, handling growing datasets and increased query loads efficiently.</li><li><strong>Integration and API</strong>: Qdrant offers user-friendly APIs for seamless integration with various data pipelines and applications.</li><li><strong>Real-Time Updates</strong>: The engine supports real-time updates, ensuring that the search index remains current with the latest data.</li></ul><p>In the context of Corrective RAG, Qdrant plays a crucial role by:</p><ul><li><strong>Efficient Retrieval</strong>: Qdrant quickly retrieves relevant documents or knowledge strips based on vector similarity, ensuring that the most pertinent information is available for further evaluation.</li><li><strong>Enhanced Precision</strong>: By facilitating high-speed searches, Qdrant ensures that the retrieval process is not a bottleneck, allowing the system to handle large volumes of data and complex queries with ease.</li><li><strong>Support for Corrective Actions</strong>: The efficiency of Qdrant allows CRAG to rapidly perform corrective actions, such as discarding irrelevant documents and conducting supplementary web searches without significant delays. As it stores the similarity scores, we can directly access it to use it in our retrieval evaluation pipeline.</li></ul><h4>2. Llama 3: Advanced LLM</h4><p>Llama 3 is a state-of-the-art language model (LLM) known for its advanced natural language processing capabilities. Llama 3 has enhanced capabilities in understanding and maintaining context over long passages, making it highly effective for generating coherent and contextually accurate responses. The main reason to use it, however, is that it outperforms GPT 4 in grade-level reasoning.</p><h4>How Qdrant and Llama 3 Work Together to Create a Seamless Recommendation System</h4><p>You can use any vector database and LLM of your choice as CRAG is simply a framework to build pipelines, and any of the tools can be interchanged. However, there are a few advantages to using them. Efficient vector storage as well as very fast search of similar vectors land us in the sweet spot of retrieval evaluation for CRAG in just a few lines of codes. Llama 3 is fast, open source, and high-performing for content generation tasks. This works in our favour as recommendation systems do not require complex tasks like solving mathematical or coding problems. Groq allows us to use the language model with 70B parameters and no restrictions on the context window, free of cost.</p><p>The combined efficiency of these two tools ensures that the system can handle large-scale data and complex queries without compromising on speed or accuracy.</p><p>Now that we have discussed the key concepts a fair bit, let us go over the implementation.</p><h3>Setting Up the Environment</h3><p>Create a Python virtual environment.</p><pre>python -m venv env</pre><p>Activate the virtual environment.</p><pre>source env/bin/activate</pre><p>Check the Python version that is installed.</p><pre>python --version</pre><blockquote>Use the commands pip list and pip freeze &gt; requirements.txt to save all the packages and their versions in the environment.</blockquote><h4>Installing Qdrant</h4><p>This can be done locally or using the Qdrant Cloud. For development and testing, we will be deploying it locally.</p><p>Pull the image:</p><pre>docker pull qdrant/qdrant</pre><p>Also install qdrant-client using the following command, which would help us connect to the container where Qdrant is running :</p><pre>pip install qdrant-client</pre><p>In the following command, revise $(pwd)/path/to/data for your Docker configuration. Then use the updated command to run the container:</p><pre>docker run -p 6333:6333 \<br>    -v $(pwd)/path/to/data:/qdrant/storage \<br>    qdrant/qdrant</pre><p>With this command, you start a Qdrant instance with the default configuration. It stores all data in the ./path/to/data directory. Here I am creating qdrant_storage as the directory name to store all the data.</p><p>By default, Qdrant uses port 6333, so at <a href="http://localhost:6333/">localhost:6333</a> you should see the welcome message ensuring that you are connected to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dcgMmLizn2vBiPzo" /><figcaption>Qdrant welcome message</figcaption></figure><h4>Installing Llama 3</h4><p>Groq is a library for optimizing and deploying models. It requires a license key, which you can obtain from the<a href="https://groq.com/"> Groq website</a>.</p><pre>pip install groq</pre><p>First, sign up/sign in with your account, then go to GroqCloud -&gt; Create API Key which you can copy and save. Browse through the documentation to select from different Llama models available for use.</p><p>Test the connection with the API key by initiating Groq client and using ‘llama-3.1–8b-instant’ model to generate a response to your query.</p><pre>#Testing Groq API connection by running a simple test<br>import os<br>from groq import Groq<br>os.environ[&quot;GROQ_API_KEY&quot;] = &quot;API_KEY&quot;<br>client = Groq()<br>response = client.chat.completions.create(<br>    messages = [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Give me the names of the continents of the world&quot;}<br>    ],<br>    model = &quot;llama-3.1-8b-instant&quot;<br>)<br>print(response)</pre><h4>Other libraries and packages to be installed</h4><p>You would also need to install <em>tavily-python </em>to perform web searches. Fetch the API key by clicking on<a href="https://docs.tavily.com/docs/tavily-api/rest_api"> Get API Key</a> on the top right corner of the page.</p><p>I also used basic Python libraries and packages for data preprocessing, such as NumPy, pandas, and re. This step depends on the dataset you are working with.</p><h3>Building the Recommendation System</h3><h4>Data Preparation</h4><p>To build a recommendation system, I will use the<a href="https://www.kaggle.com/datasets/carrie1/ecommerce-data"> E Commerce dataset.</a> I will also create a user-item interaction file from it. Hence, to keep things simple, we will use Collaborative filtering to recommend articles to users.</p><p>Load the csv data file</p><pre># Load the CSV data into a pandas DataFrame<br>df = pd.read_csv(&#39;/Users/anveshamishra/Downloads/data.csv&#39;, encoding=&#39;ISO-8859–1&#39;)</pre><p>Perform data cleaning and handling of missing value.</p><pre># Convert CustomerID to integer, handling missing values if necessary<br>df = df.dropna()<br>df[&#39;CustomerID&#39;] = df[&#39;CustomerID&#39;].astype(int)</pre><p>Check the number of unique stock codes. As Stock Codes are alphanumeric, we map it to integers to allow us to search and retrieve items easily. I have also reduced the number of items to 250 to reduce the computational time but I do encourage you to try with the entire dataset.</p><pre># Create a unique list of StockCodes after filtering<br>unique_stock_codes = df[&#39;StockCode&#39;].unique()<br>print(f&quot;Unique Stock Codes: {unique_stock_codes}&quot;)<br># Create a positional mapping for each StockCode<br>stock_code_mapping = {code: idx+1 for idx, code in enumerate(unique_stock_codes)}<br># Replace StockCodes with positional mapping<br>df[&#39;StockCode&#39;] = df[&#39;StockCode&#39;].map(stock_code_mapping)<br># Drop rows where StockCode values are greater than 250<br>df = df[df[&#39;StockCode&#39;] &lt;= 250]</pre><p>We now have 3995 customers and 250 items. I have grouped the transaction records on the basis of customer id to later store the transaction history of each customer on the database. You can save the dictionary with key (customer id) and values (transactions) in a CSVfile or JSON file. I chose the latter.</p><pre># Group the data by CustomerID<br>grouped = df.groupby(&#39;CustomerID&#39;)<br># Initialize a dictionary to hold the grouped data with sampled readings<br>data_by_customer = {}<br># Set the random seed for reproducibility<br>np.random.seed(42)<br># Iterate over each group<br>for customer_id, group in grouped:<br> # Drop the &#39;CustomerID&#39; column and convert the rest of the group to a dictionary<br> data_by_customer[int(customer_id)] = group.drop(columns=[&#39;CustomerID&#39;]).to_dict(orient=&#39;records&#39;)<br># Convert the dictionary to a JSON string<br>json_data = json.dumps(data_by_customer, indent=4)</pre><p>Lastly, create a user interaction file to create a vector representation of the items which have been bought by each customer.</p><pre>df2 = df[[&#39;CustomerID&#39;,&#39;StockCode&#39;]]<br>df2 = df2.groupby([&#39;CustomerID&#39;])[&#39;StockCode&#39;].agg(list).reset_index()<br>df2[&#39;StockCode&#39;]= df2[&#39;StockCode&#39;].transform(lambda x : [0 if y+1 not in x else y+1 for y in range(num_items)])<br>filename = &#39;user_interaction_data.csv&#39;<br>df2.to_csv(filename,index = False)<br>print(f&quot;User Interactive CSV file saved successfully as {filename}.&quot;)</pre><h4>Converting Data into Vector Embeddings and Storing It in the Qdrant Database</h4><p>Load the two files created above and initialize the Qdrant Client.</p><pre>import json<br>from qdrant_client import QdrantClient<br>from qdrant_client import models<br>import pandas as pd<br>import ast<br><br># Load the JSON data<br>with open(&#39;/Users/anveshamishra/Documents/GitHub/crag_based_recommender_system/data_preprocessing/data_grouped_by_customer_reduced.json&#39;, &#39;r&#39;) as f:<br>    data_by_customer = json.load(f)<br><br>user_interaction = pd.read_csv(&#39;/Users/anveshamishra/Documents/GitHub/crag_based_recommender_system/user_interaction_data.csv&#39;)<br>index = user_interaction[&#39;CustomerID&#39;].tolist()<br><br><br># Initialize the Qdrant client (adjust host and port as needed)<br>client = QdrantClient(host=&#39;localhost&#39;, port=6333)</pre><p>Create a collection to store the vector embeddings and payload.</p><pre># Define the collection name<br>collection_name = &quot;customer_recommendations&quot;<br><br># Check if the collection exists, delete if it does, and create a new one<br>if client.collection_exists(collection_name):<br>    client.delete_collection(collection_name)<br><br><br># Create a collection<br><br>first_collection = client.create_collection(<br>    collection_name=collection_name,<br>    vectors_config=models.VectorParams(size=250, distance=models.Distance.COSINE)<br>)</pre><p>Insert the customer ids as index and the transactions as payload into the collection.</p><pre># Index the data into Qdrant<br>vector_insert = client.upsert(<br>    collection_name=collection_name,<br>    points=models.Batch(<br>        ids=index,<br>        vectors=user_interaction[&#39;StockCode&#39;].tolist()<br>    )<br>)<br>print(vector_insert)<br><br># Initialize an empty list to store aggregated payloads<br>payloads = []<br><br># Populate the payload list with aggregated data for each customer<br>for customer_id, transactions in data_by_customer.items():<br>    aggregated_payload = {<br>        &quot;CustomerID&quot;: customer_id,<br>        &quot;Transactions&quot;: transactions<br>    }<br>    payloads.append(aggregated_payload)<br><br># Ensure ids and payloads match in number<br>assert len(index) == len(payloads), &quot;Number of IDs and payloads must match.&quot;<br><br># Add payloads to the indexed data<br>payloads_insert = client.upsert(<br>    collection_name=collection_name,<br>    points=models.Batch(<br>        ids=index,<br>        vectors=user_interaction[&#39;StockCode&#39;].tolist(),<br>        payloads=payloads<br>    )<br>)<br><br>print(&quot;Data successfully indexed with payloads.&quot;)</pre><h4>Implementing the Retrieval Mechanism with Qdrant</h4><p>To search for similar vectors using a stored vector for a specific CustomerID (e.g., 12357), you can first retrieve the vector corresponding to that CustomerID from the Qdrant storage. Then, use this vector as the query vector for the search operation. Here’s how you can do it:</p><ol><li>Use the Qdrant client.scroll API to get the vector associated with the customer ID.</li></ol><pre>from qdrant_client import QdrantClient<br>from qdrant_client import models<br># Initialize the Qdrant client (adjust host and port as needed)<br>client = QdrantClient(host=&#39;localhost&#39;, port=6333)<br># Define the collection name<br>collection_name = &quot;customer_recommendations&quot;<br>target_customer_id = &quot;12357&quot;<br>result = client.scroll(<br>    collection_name=collection_name,<br>    scroll_filter=models.Filter(<br>        must=[<br>            models.FieldCondition(key=&quot;CustomerID&quot;, match=models.MatchValue(value=target_customer_id)),<br>        ]<br>    ),<br>    limit=1,<br>    with_payload=True,<br>    with_vectors=True,<br>)<br><br># Extract the vector from the result<br>if result and result[0][0].vector is not None:<br>    target_vector = result[0][0].vector<br>    #print(f&quot;Vector for CustomerID {target_customer_id}: {target_vector}&quot;)<br>else:<br>    #print(f&quot;No vector found for CustomerID {target_customer_id}&quot;)<br>    exit()</pre><p>2. Perform a search operation using the retrieved vector as the query vector to find similar vectors.</p><pre># Now you can use this vector to search for similar vectors<br>similar_customers = client.search(<br>    collection_name=collection_name,<br>    query_vector=target_vector,<br>    limit=2  # You can set the limit to any number you prefer<br>)<br><br># Print the results<br>for res in similar_customers:<br>    print(f&quot;CustomerID: {res.id}, Score: {res.score}&quot;)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PepHCLyyb_TIB3mz" /></figure><p>Notice that, out of the two similar customers, one is the query vector itself. Therefore, we need LLMs to create more user readable responses.</p><p>3. You can even get the payload information for all the vectors that were similar to the queried vector. This is important as this allows us to retrieve the transaction history of all the customers, giving us access to more information.</p><pre># Print the results and their payloads<br>for res in similar_customers:<br>    customer_id = res.id<br>    score = res.score<br>    payload = res.payload<br>    print(f&quot;CustomerID: {customer_id}, Score: {score}&quot;)<br>    print(&quot;Payload:&quot;)<br>    for transaction in payload.get(&#39;Transactions&#39;, []):<br>        print(f&quot;  - InvoiceNo: {transaction[&#39;InvoiceNo&#39;]}, &quot;<br>              f&quot;StockCode: {transaction[&#39;StockCode&#39;]}, &quot;<br>              f&quot;Description: {transaction[&#39;Description&#39;]}, &quot;<br>              f&quot;Quantity: {transaction[&#39;Quantity&#39;]}, &quot;<br>              f&quot;InvoiceDate: {transaction[&#39;InvoiceDate&#39;]}, &quot;<br>              f&quot;UnitPrice: {transaction[&#39;UnitPrice&#39;]}, &quot;<br>              f&quot;Country: {transaction[&#39;Country&#39;]}&quot;)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-n95zF-gmsm0Kvev" /><figcaption>Similar documents retrieved using Qdrant</figcaption></figure><p><strong>Enhancing Recommendations with Llama 3</strong></p><p>To do this through a prompt, the steps are pretty much the same as above but with an extra function that extracts the customer id from the prompt.</p><pre># Function to parse the query and extract customer ID<br>def extract_customer_id(query):<br>    # Define a pattern that looks for keywords associated with customer IDs followed by a number<br>    pattern = r&quot;(?:customer\s*id|customer\s*number|account\s*id)\s*[:#-]?\s*(\d+)&quot;<br><br>    # Search for the pattern in the query<br>    match = re.search(pattern, query, re.IGNORECASE)<br><br>    if match:<br>        return match.group(1)<br><br>    # As a fallback, check for any number without specific keywords<br>    # Avoid numbers that are unlikely to be customer IDs (e.g., very small numbers)<br>    fallback_match = re.search(r&quot;\b\d{5,}\b&quot;, query)  # Assuming IDs are at least 5digits long<br>    if fallback_match:<br>        return fallback_match.group(0)<br><br>    return None</pre><p>Once we have vectors similar to the query vector, we can access their payloads and use Llama to generate responses. I have defined a prompt template to give more personalized responses.</p><pre># Function to generate recommendations based on the customer ID<br>def get_customer_recommendations(query):<br>    customer_id = extract_customer_id(query)<br>    if not customer_id:<br>        print(&quot;Customer ID not found in the query.&quot;)<br>        return<br><br>    print(f&quot;Extracted Customer ID: {customer_id}&quot;)<br><br>    # Step 1: Find the vector for the target customer<br>    try:<br>        result = client.scroll(<br>            collection_name=collection_name,<br>            scroll_filter=models.Filter(<br>                must=[<br>                    models.FieldCondition(key=&quot;CustomerID&quot;, match=models.MatchValue(value=customer_id)),<br>                ]<br>            ),<br>            limit=1,<br>            with_payload=True,<br>            with_vectors=True,<br>        )<br>    except Exception as e:<br>        print(f&quot;Error retrieving customer data: {e}&quot;)<br>        return<br><br>    # Extract the vector for the target customer<br>    if result and result[0][0].vector is not None:<br>        target_vector = result[0][0].vector<br>        print(f&quot;Found vector for CustomerID {customer_id}&quot;)<br>    else:<br>        print(f&quot;No vector found for CustomerID {customer_id}&quot;)<br>        return<br><br>    # Step 2: Find similar customers<br>    try:<br>        similar_customers = client.search(<br>            collection_name=collection_name,<br>            query_vector=target_vector,<br>            limit=5<br>        )<br>        print(f&quot;Found {len(similar_customers)} similar customers.&quot;)<br>    except Exception as e:<br>        print(f&quot;Error searching for similar customers: {e}&quot;)<br>        return<br><br>    # Get articles already bought by the target customer<br>    target_customer_transactions = result[0][0].payload.get(&#39;Transactions&#39;, [])<br>    target_articles = {trans[&#39;StockCode&#39;] for trans in target_customer_transactions}<br><br>    # Collect articles from similar customers<br>    new_articles = []<br>    for res in similar_customers:<br>        payload = res.payload<br>        for transaction in payload.get(&#39;Transactions&#39;, []):<br>            stock_code = transaction[&#39;StockCode&#39;]<br>            if stock_code not in target_articles:<br>                new_articles.append(transaction)<br><br>    # Define a prompt template<br>    prompt_template = &quot;&quot;&quot;<br>    User {customer_id} has interacted with the following articles: {existing_articles}.<br>    Based on similar users, suggest 2 new articles that User {customer_id} has not interacted with yet.<br>    Also, provide a reason for each recommendation.<br><br>    Here are some articles that similar users have interacted with:<br>    {similar_user_articles}<br>    Please provide your recommendations and reasons.<br>    &quot;&quot;&quot;<br><br>    # Prepare data for the prompt<br>    existing_articles = &quot;, &quot;.join(f&quot;{trans[&#39;Description&#39;]} (StockCode: {trans[&#39;StockCode&#39;]})&quot; for trans in target_customer_transactions)<br>    similar_user_articles = &quot;\n&quot;.join(<br>        f&quot;Article: {article[&#39;Description&#39;]}, StockCode: {article[&#39;StockCode&#39;]}, Details: {article}&quot;<br>        for article in new_articles[:10]  # Limit to a subset for the prompt<br>    )<br><br>    # Fill the prompt template with data<br>    prompt = prompt_template.format(<br>        customer_id=customer_id,<br>        existing_articles=existing_articles,<br>        similar_user_articles=similar_user_articles<br>    )<br><br>    # Use Groq API to get chat completion<br>    try:<br>        response = groq_client.chat.completions.create(<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>            model=&quot;llama3-70b-8192&quot;<br>        )<br>        # Print the response<br>        print(response.choices[0].message.content)<br>    except Exception as e:<br>        print(f&quot;Error getting response from Groq: {e}&quot;)</pre><p>Sample output:</p><pre># Example usage<br>query = &quot;recommend me articles for customer id 12357&quot;<br>get_customer_recommendations(query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9in_OKmmwZCA1VH" /><figcaption>Output using LLM</figcaption></figure><p>It’s pretty brilliant how the LLM is also able to describe the personal style of the customer and offer recommendations based on that.</p><h4>Retrieval Evaluation</h4><p>Now up in the final leg of this code would be to implement a sort of retrieval evaluation system.</p><p>I implemented the CRAG pipeline by evaluating similarity scores of the retrievals. There could be three cases :<br>Case 1: If the retrieval score is more than 0.6,<br>Case 2: If the retrieval score is less than 0.6, <br>Case 3: If customer id is not present in the prompt or not in the database.</p><p>Code for implementing the retrieval evaluation:</p><pre># Function to generate recommendations based on the query<br>def get_customer_recommendations(query):<br>    customer_id = extract_customer_id(query)<br><br>    if not customer_id:<br>        print(&quot;No customer ID found in the query. Fetching general recommendations.&quot;)<br>        external_context = fetch_external_data(query)<br>        generate_final_response_from_external(query, external_context)<br>        return<br><br>    print(f&quot;Extracted Customer ID: {customer_id}&quot;)<br><br>    # Step 1: Find the vector for the target customer<br>    try:<br>        result = client.scroll(<br>            collection_name=collection_name,<br>            scroll_filter=models.Filter(<br>                must=[<br>                    models.FieldCondition(key=&quot;CustomerID&quot;, match=models.MatchValue(value=customer_id)),<br>                ]<br>            ),<br>            limit=1,<br>            with_payload=True,<br>            with_vectors=True,<br>        )<br>    except Exception as e:<br>        print(f&quot;Error retrieving customer data: {e}&quot;)<br>        return<br><br>    # Check if any results were found<br>    if result[0]:<br>        print(f&quot;Found vector and data for CustomerID {customer_id}&quot;)<br>    else:<br>        print(f&quot;No vector found for CustomerID {customer_id}. Using external data for recommendations.&quot;)<br>        external_context = fetch_external_data(query)<br>        generate_final_response_from_external(query, external_context)<br>        return<br><br>    # Step 2: Extract target customer transactions<br>    target_customer_transactions = result[0][0].payload.get(&#39;Transactions&#39;, [])<br><br>    # Step 3: Find similar customers<br>    try:<br>        similar_customers = client.search(<br>            collection_name=collection_name,<br>            query_vector=result[0][0].vector,<br>            limit=5<br>        )<br>        print(f&quot;Found {len(similar_customers)} similar customers.&quot;)<br>    except Exception as e:<br>        print(f&quot;Error searching for similar customers: {e}&quot;)<br>        return<br>    for res in similar_customers:<br>        print(res.score)<br>        # Check if similarity scores are below a threshold (e.g., 0.1%)<br>    low_similarity = all(res.score &lt; 0.6 for res in similar_customers[1:])<br>    print(low_similarity)<br><br>    if low_similarity:<br>        print(&quot;Low similarity scores found. Using external data to augment context.&quot;)<br>        external_context = fetch_external_data(query)<br>        generate_final_response(query, external_context, target_customer_transactions, similar_customers)<br>    else:<br>        generate_final_response(query, None, target_customer_transactions, similar_customers)</pre><p>The two functions generate_final_response as well as generate_final_response_from_external contain the prompt templates and chat completion requests using different contexts as specified above.</p><p>Case 1:</p><p>For Case 1, if the similarity score is high, a relevant document has been retrieved and we can use it to generate a response.</p><p>Sample Output:</p><pre># Example usage<br>query = &quot;recommend me articles for customer id 12535&quot;<br>get_customer_recommendations(query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*djVAgZHcpL53n2pn" /></figure><p>Case 2:</p><p>If it is Case 2, then we do a web search and add its result as additional context in the prompt before generating a response.</p><p>Sample Output:</p><pre># Example usage<br>query = &quot;recommend me articles for customer id 12556 if the customer is interested in home decor&quot;<br>get_customer_recommendations(query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bCgmmjHGcpPkN0gV" /></figure><p>Case 3:</p><p>Finally, for Case 3, we just use the search result as context and use Llama3 to generate the final response.</p><p>Define a function to collect data from the web as context.</p><pre># Function to fetch external data using Tavily API<br>def fetch_external_data(query):<br>    # Simulated external search result as an example<br>    # Step 1. Instantiating your TavilyClient<br>    tavily_client = TavilyClient(api_key=tavily_api_key)<br>    # Step 2. Executing a context search query<br>    external_context = tavily_client.get_search_context(query=query)<br>    return external_context</pre><p>Add it to your prompt template as context.</p><pre># Define a prompt template for external data<br>    prompt_template = &quot;&quot;&quot;<br>    Based on external data sources, suggest 2 top recommendations for the following query: &quot;{query}&quot;.<br>    Also, provide a reason for each recommendation.<br><br>    External data sources provide the following context:<br>    {external_context}<br>    Please provide your recommendations and reasons.<br>    &quot;&quot;&quot;<br>    #query_embedding = query_to_embedding(query)<br>    # Fill the prompt template with data<br>    prompt = prompt_template.format(<br>        query=query,<br>        external_context=external_context<br>    )</pre><p>Generate the final response using Llama 3:</p><pre># Use Groq API to get chat completion<br>    try:<br>        response = groq_client.chat.completions.create(<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>            model=&quot;llama3-70b-8192&quot;<br>        )<br>        # Print the response<br>        print(response.choices[0].message.content)<br>    except Exception as e:<br>        print(f&quot;Error getting response from Groq: {e}&quot;)</pre><p>Sample Output:</p><pre># Example usage<br>query = &quot;recommend me some items to buy if I have recently purchased a SET OF 3 BUTTERFLY COOKIE CUTTERS&quot;<br>get_customer_recommendations(query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t3SXiRRMqh5lJs8a" /><figcaption>External search results for recommendation</figcaption></figure><h3>Results</h3><ul><li>I used a simple Streamlit application to test the results:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X70-gN-nS6fiwC--" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kEjOUXq92PX1UtKR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c3sJExDXsh9bmfXi" /></figure><h3>Testing and Evaluation</h3><ul><li><strong>Evaluation Metrics — using Ragas</strong></li><li>Ragas is a tool designed to evaluate retrieval-augmented generation (RAG) pipelines. We will use this framework to evaluate our CRAG pipeline results. Here are the key metrics used by Ragas:</li><li><strong>Faithfulness: </strong>Faithful responses are crucial for maintaining the credibility and reliability of the system. Users must trust that the information provided by the system is based on actual data and not fabricated. It typically involves comparing the response against the source context to ensure all claims are supported and the response does not introduce hallucinations.</li><li><strong>Answer Relevancy</strong>: A response that is not relevant to the query is not useful to the user. Relevancy is key to user satisfaction and system effectiveness. It is measured using automated scoring against ground truth to determine how well the response answers the query.</li><li><strong>Context Recall</strong>: It measures the extent to which the relevant information from the retrieved context is used in the generated response. It involves comparing the content of the response with the relevant portions of the context to see how much of the pertinent information is included.</li><li><strong>Context Precision</strong>: High precision ensures that the response is not only using the context but doing so accurately, without introducing irrelevant information. It checks the response against the context to ensure that the information used is relevant and directly supports the response.</li></ul><p><strong>Combining Metrics for Holistic Evaluation</strong></p><p>These metrics collectively provide a comprehensive evaluation of a CRAG pipeline. Here’s how they interact:</p><ul><li><strong>Faithfulness</strong> ensures that the response is trustworthy.</li><li><strong>Answer Relevancy</strong> ensures that the response is useful.</li><li><strong>Context Recall</strong> ensures that the response is comprehensive.</li><li><strong>Context Precision</strong> ensures that the response is accurate.</li></ul><h4>Testing</h4><ul><li>Create a test set with queries and ground_truth</li></ul><pre># Example usage and evaluation<br>test_queries = [<br>    &quot;recommend me articles for customer id 12357 that it has not yet bought&quot;,<br>    &quot;recommend me similar articles for customer id 18228&quot;<br>]<br><br>ground_truth = [<br>    &quot;Based on the user&#39;s history and external data, I recommend the PIGGY BANK RETROSPOT (StockCode: 77). This item matches the user&#39;s interest in RetroSpot-themed products and fits their preference for decorative home decor. Additionally, similar users have shown interest in this item, making it a great choice for User 12357.&quot;,<br>&quot;Based on the user&#39;s history and external data, I recommend the JUMBO SHOPPER VINTAGE RED PAISLEY (StockCode: 70). This item suits the user&#39;s preference for home decor and novelty items, as evidenced by their interest in hot water bottles and metal signs. The bag&#39;s vintage and decorative style, along with its vibrant and whimsical design, aligns with the user&#39;s taste for quirky and humorous items, making it a likely favorite.&quot;<br>]<br><br>answers = []<br>contexts = []</pre><ul><li>Call the recommendation function on test queries and prepare a data dictionary to be converted into a Huggingface dataset</li></ul><pre>for query in test_queries:<br>    response, context = get_customer_recommendations(query)<br>    if response is not None:<br>        answers.append(clean_text(response))<br>        contexts.append([clean_text(context)])<br><br># Prepare data for evaluation<br>data = {<br>    &quot;question&quot;: test_queries,<br>    &quot;answer&quot;: answers,<br>    &quot;contexts&quot;: contexts,<br>    &quot;ground_truth&quot;: ground_truth<br>}<br><br># Convert dict to dataset<br>dataset = Dataset.from_dict(data)</pre><ul><li>Evaluate the test set recommendations</li></ul><pre># Evaluate the recommendations<br>result = evaluate(<br>    dataset=dataset,<br>    metrics=[<br>        context_precision,<br>        context_recall,<br>        faithfulness,<br>        answer_relevancy,<br>    ],<br>    llm=langchain_llm,<br>    embeddings=fast_embeddings,<br>    raise_exceptions=False,<br>    run_config=RunConfig(timeout=120.0)<br>)<br><br># Convert the result to a pandas DataFrame for easier analysis<br>df = result.to_pandas()<br>df.to_csv(&#39;results.csv&#39;)<br>print(df)</pre><ul><li>As we use the real world dataset, let us have a look at its performance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XGWbt1zHQnEKeE74" /><figcaption><strong>Summary of Ragas Results</strong></figcaption></figure><ul><li>By evaluating a CRAG pipeline against these metrics, Ragas can provide a nuanced assessment of its performance, highlighting strengths and identifying areas for improvement.</li></ul><p><strong>Overall Analysis</strong></p><ul><li><strong>High Precision and Recall for Query 2</strong>: Query 2 performs exceptionally well across all metrics, particularly in context recall, indicating that the response is both comprehensive and precise.</li><li><strong>Balanced Performance for Query 1</strong>: While Query 1 has high scores, it does slightly lower on context recall. This suggests that while the response is precise and relevant, it could be improved by including more of the relevant information from the context.</li><li><strong>Faithfulness and Relevancy</strong>: Both queries show strong performance in terms of faithfulness and relevancy, which are critical for user trust and satisfaction.</li></ul><p><strong>Areas for Improvement</strong></p><ul><li><strong>Improve Recall for Query 1</strong>: Efforts should be made to enhance the context recall for Query 1 to ensure all relevant information is captured in the response.</li><li><strong>Maintain High Precision</strong>: The high precision scores for both queries are commendable and should be maintained to ensure that the responses remain accurate.</li><li><strong>Overall High Performance</strong>: The scores suggest that the CRAG pipeline is performing well, particularly for Query 2, and similar strategies can be employed to improve performance where needed.</li></ul><h3>Conclusion</h3><h4>Summary of Key Points</h4><ul><li><strong>Recommender Systems</strong>: Systems that suggest items or content to users based on their preferences, improving user experience and boosting sales for businesses.</li><li><strong>Types of Recommender Systems</strong>:<br><br>- <strong>Collaborative Filtering</strong>: Recommends items liked by similar users.<br>- <strong>Content-Based Filtering</strong>: Recommends items similar to those a user has shown interest in.<br>- <strong>Corrective RAG (CRAG)</strong>: Enhances language model responses by evaluating and refining retrieved documents to ensure relevance and accuracy.</li><li><strong>Components of CRAG</strong>:<br><strong>Retrieval</strong>: Fetches relevant documents from static databases and web searches.<br><strong>Knowledge Correction</strong>: Evaluates and refines the relevance and accuracy of documents.<br><strong>Generator</strong>: Produces the final response using refined knowledge.</li><li>We used <strong>Qdrant </strong>which is a<strong> </strong>vector search engine for efficient retrieval. <br>For generating responses we used <strong>Llama3</strong>.</li><li><strong>Evaluation with Ragas</strong>: Metrics like faithfulness, answer relevancy, context recall, and context precision are used to assess the performance of the CRAG pipeline.</li></ul><h4>Recap of What’s Covered in the Tutorial</h4><p>In this tutorial, we started by exploring the magic behind recommender systems 🪄<br>- We then dived into Corrective RAG (CRAG), an advanced system that refines these recommendations, to be even more accurate. <br>- We set up the necessary tools, Qdrant and Llama3, and walked through building a recommendation system from scratch. This involved data preparation, retrieval with Qdrant, and using Llama3 for generating better recommendations. <br>- Finally, we evaluated our system with Ragas, discussed its performance, and highlighted areas for improvement.</p><h4>Final Thoughts on the Benefits of Using Corrective RAG with Qdrant and Llama 3</h4><p>Using Corrective RAG with Qdrant and Llama3 improves the performance of LLM-driven recommendation systems as they increase the precision of the output. Using the web search component would improve both user interaction and answer relevancy.</p><h4>Suggestions for Further Reading and Advanced Topics</h4><p><strong>📚</strong><a href="https://dt.athabascau.ca/jspui/bitstream/10791/324/5/MohammadBelghisZadehFinal_v3.pdf"><strong> Deep Dive into Recommender Systems</strong>:</a> Explore more advanced recommendation algorithms and hybrid approaches.</p><p><strong>📚</strong><a href="https://app.daily.dev/posts/advanced-rag-corrective-retrieval-augmented-generation-crag-with-langgraph-kmbx4h2jv"><strong> Advanced CRAG Techniques</strong></a>: Research on enhancing CRAG with LangGraph.</p><p><strong>📚</strong><a href="https://www.pingcap.com/article/vector-database-scalability-a-comparative-analysis-of-pgvector-and-tidb-serverless/#:~:text=With%20exploding%20data%20volumes%20and,in%20latency%20or%20resource%20consumption."><strong> Scaling Vector Databases</strong></a>: Learn about best practices for scaling vector databases to handle massive datasets.</p><p>Don’t hesitate to experiment with different datasets, configurations, and parameters to see how they impact the performance of your recommendation system.</p><ul><li><strong>Customization</strong>: Tailor the system to your specific use cases and requirements, leveraging the flexibility of CRAG, Qdrant, and Llama 3.</li><li><strong>Continuous Improvement</strong>: <br>- Right now only the preference of a customer is taken into account but a similar item catalogue vector would make the results more robust. <br>- Try to add more relevant context in the query to improve the performance.<br>- Regularly evaluate and refine your system based on feedback and performance metrics to ensure it meets user needs effectively.</li></ul><h3>Appendix</h3><ul><li><strong>Additional Resources</strong></li></ul><p>🔗 Qdrant documentation<a href="https://qdrant.tech/documentation/"> https://qdrant.tech/documentation/</a></p><p>🔗 Groq cloud for Llama3 documentation<a href="https://console.groq.com/docs/quickstart"> https://console.groq.com/docs/quickstart</a></p><p>🔗 Taviliy API<a href="https://docs.tavily.com/docs/tavily-api/introduction"> https://docs.tavily.com/docs/tavily-api/introduction</a></p><p>🔗<a href="https://blog.lancedb.com/implementing-corrective-rag-in-the-easiest-way-2/"> https://blog.lancedb.com/implementing-corrective-rag-in-the-easiest-way-2/</a></p><p>🔗<a href="https://www.pinecone.io/learn/advanced-rag-techniques/"> https://www.pinecone.io/learn/advanced-rag-techniques/</a></p><p>🔗<a href="https://arxiv.org/abs/2401.15884"> https://arxiv.org/abs/2401.15884</a></p><ul><li><strong>Code Repository</strong></li></ul><p>🔗<a href="https://github.com/AnveshaM/crag_based_recommender_system">https://github.com/AnveshaM/crag_based_recommender_system</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9afaa3199ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Object Tracking in Video Streams: Addressing Missing Object Detection]]></title>
            <link>https://medium.com/@anvesha6496/enhancing-object-tracking-in-video-streams-addressing-missing-object-detection-511126d74f9c?source=rss-593ede154029------2</link>
            <guid isPermaLink="false">https://medium.com/p/511126d74f9c</guid>
            <dc:creator><![CDATA[Anvesha Mishra]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 19:46:47 GMT</pubDate>
            <atom:updated>2024-03-20T19:47:43.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vUcErmfO88GXm_UW8FdUQ.jpeg" /></figure><p>One of the persistent challenges in real-time object tracking is when the tracking model fails to consistently detect an object across consecutive frames. Picture this: it’s detecting the object in one frame before the current frame, and it’s detected again one frame after.</p><p>So, what exactly went wrong?</p><p>This situation can arise due to a multitude of reasons. Challenging lighting conditions in the image, rapid movements or variations in speed within the video, and the dynamic movement of the camera itself all contribute to the complexity. Additionally, factors such as occlusion, object size, and cluttered backgrounds further compound the challenge by hindering accurate detection.</p><p>These diverse conditions can result in missed detections or inaccuracies in object localization, ultimately affecting the overall tracking performance, even with powerful trackers.</p><p>What I’ve observed increasingly is that most AI model performances can be significantly enhanced with a layer of coding on top of them. Building simple algorithms to ensure the model’s robustness often requires minimal time compared to the alternative of tweaking the model architecture or fine-tuning it for hours just to see a marginal increase in accuracy from, let’s say, 82% to 83%.</p><p>Of course, the gold standard solution is to revisit the data used to train the model. Increasing the dataset size and improving its quality by adding pictures of the same object taken from different angles and lighting settings is the most effective way to tackle this issue. However, it’s important to acknowledge that this approach demands hours of data annotation and retraining the model using substantial computational resources.</p><p>To tackle the aforementioned problem, I developed an algorithm that facilitates the best-fit warping of previous images into the current image, thereby enhancing tracking robustness. By assuming that the object moves along a line through the images, we achieve a robust best fit to that line. Consequently, when the object reappears, it’s more likely to be near the predicted projection of the line than not.</p><h3>1. Initialization and Setup</h3><p>This section initializes the video capture, loads the YOLOv8 model for object detection, and sets up the output video file for writing.</p><pre>import cv2<br>from ultralytics import YOLO<br><br># Load the YOLOv8 model<br>model = YOLO(&#39;yolov8s.pt&#39;)<br># Open the video file<br>video_path = &quot;testvideo.mp4&quot;<br>cap = cv2.VideoCapture(video_path)<br># Get the video frame width and height<br>frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br># Define the codec and create a VideoWriter object<br>output_video_path = &quot;tracked_video.mp4&quot;<br>fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br>out = cv2.VideoWriter(output_video_path, fourcc, 25, (frame_width, frame_height))</pre><h3>2. Object Tracking Loop</h3><p>This section contains the main loop where object tracking is performed on each frame of the video. It reads frames from the video, performs object detection using YOLOv8, checks if the class ID 2 (or any other desired class) is detected, and draws bounding boxes accordingly. It also implements logic to handle missing detections by using the previous bounding box coordinates for a limited number of frames.</p><pre># Initialize variables to store previous bounding box coordinates and counter<br>prev_bbox_coords = None<br>frame_counter = 0<br>max_frame_count = 2  # Maximum number of frames to use previous bounding box<br># Loop through the video frames<br>while cap.isOpened():<br>    # Read a frame from the video<br>    success, frame = cap.read()<br>    <br>    if success:<br>        # Run YOLOv8 tracking on the frame, persisting tracks between frames<br>        results = model.track(frame, persist=True, show=False, tracker=&quot;botsort.yaml&quot;, conf=0.25, iou=0.5)<br>        <br>        # Check if class ID 2 is detected in the current frame<br>        class_2_detected = False<br>        class_2_index = None<br>        for i, box in enumerate(results[0].boxes.xyxy):<br>            if int(results[0].boxes.cls[i]) == 2:<br>                class_2_detected = True<br>                class_2_index = i<br>                frame_counter = 0  # Reset the frame counter if class 2 is detected<br>                break<br>        <br>        # Draw bounding box based on detection in current frame or previous frame<br>        if class_2_detected:<br>            # Get bounding box coordinates if class 2 is detected<br>            bbox_coords = results[0].boxes[class_2_index].xyxy[0]  # Access the inner tensor<br>            prev_bbox_coords = bbox_coords<br>        elif prev_bbox_coords is not None and frame_counter &lt; max_frame_count:<br>            # Use previous bounding box coordinates if class 2 is not detected and frame counter threshold is not reached<br>            bbox_coords = prev_bbox_coords<br>            frame_counter += 1<br>        else:<br>            bbox_coords = None<br>        <br>        # Draw bounding box on the frame if it exists<br>        if bbox_coords is not None:<br>            x1, y1, x2, y2 = map(int, bbox_coords)<br>            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>        # Write the annotated frame to the output video<br>        out.write(frame)<br>        # Break the loop if &#39;q&#39; is pressed<br>        if cv2.waitKey(1) &amp; 0xFF == ord(&quot;q&quot;):<br>            break<br>    else:<br>        # Break the loop if the end of the video is reached<br>        break</pre><h3>3. Cleanup and Release</h3><p>This section releases the video capture and writer objects and closes any open windows, ensuring proper cleanup after processing the video.</p><pre># Release the video capture object, VideoWriter object, and close the display window<br>cap.release()<br>out.release()<br>cv2.destroyAllWindows()</pre><p>#ComputerVision #ObjectTracking #AI #MachineLearning #Python #DeepLearning #Tech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511126d74f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Knowledge Graph Completion using Transformers]]></title>
            <link>https://blog.gopenai.com/automating-knowledge-graph-completion-using-transformers-bad993d601c7?source=rss-593ede154029------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad993d601c7</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <dc:creator><![CDATA[Anvesha Mishra]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 15:55:19 GMT</pubDate>
            <atom:updated>2023-03-24T20:18:02.252Z</atom:updated>
            <content:encoded><![CDATA[<p>The article outlines a pipeline that uses Hugging face Transformers to improve the accuracy of a Knowledge Graph by predicting missing entities and relations while minimising incorrect triples.</p><p>Before we dive into heavy-duty NLP, it’s important to discuss what knowledge graphs are. Consider this as an exposition, or the establishing shot, before introducing the main character in a film.</p><blockquote><strong>What are Knowledge Graphs?</strong></blockquote><p>When I hear the term “graph,” I tend to associate it with visual displays of data. Knowledge Graphs take this a step further by not only representing data but also storing and organising knowledge in a way that enables sophisticated queries and analysis. By creating a rich, interconnected web of entities and their relationships, Knowledge Graphs offer a powerful tool for unlocking insights and understanding complex systems.</p><p>The most common application of Knowledge Graphs comes with textual data. A sentence is broken down in triple format represented by the head entity (h), relation (r) and tail entity (t). For example, the sentence “I love coffee” can be stored in the knowledge graph as depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*dQxfTCzo4sppkFboR2cQRg.png" /><figcaption>Triple representation in a knowledge graph</figcaption></figure><blockquote><strong>Knowledge Graph Completion</strong></blockquote><p>This is the task that the hero must perform to save the world from doomsday! A little overdramatic but I am sure by now you must have already deduced that I am a movie buff :)</p><p>So consider this scenario — You want to develop a Question Answering system on top of your Enterprise Knowledge Graph. You enter a question but you get a wrong answer. Why does this happen?</p><p>Well, an obvious answer is that your base Knowledge Graph has missing entities and relations. Consider the graph below. Just by looking at it, you can guess the missing relation between the entities Pedro Pascal and The Mandalorian. Hint — Pedro Pascal “starred in” The Mandalorian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrWXvJxubnCn033M1gqmOQ.png" /></figure><p>How do you make a model intelligent enough so that it can predict the missing relation using the existing knowledge base? This task is popularly known as “Knowledge Graph Completion” — which is further subdivided into the following tasks :</p><ol><li>Entity Prediction: Predicting missing entities</li><li>Relation Prediction: Predicting missing relations</li><li>Triple Classification: Classifying triples (h,r,t) if they belong to the Knowledge Graph or not. This task is important to remove noisy or incorrect triples from the Knowledge Graph to further increase its accuracy.</li></ol><p>There are various ways to perform Knowledge Graph Completion tasks. I used pre-trained transformer models as my goal was to minimise manual intervention as much as possible.</p><p>Even if you don’t know what transformers are, chances are that you may have already used the product built using it! The revolutionary product of OpenAI which we all know as Chat-GPT uses a variation of the Transformer architecture to generate text and responses.</p><p>Essentially, the Transformer model is like a black box that takes in textual data and learns the rules of grammar and sentence structure from it. Once it has a solid understanding of these basics, it can be fine-tuned to perform a wide range of other language-related tasks, from translation to summarisation and beyond. Lucky for us we know precisely what these three tasks are!</p><p>To train the transformers in the Knowledge Graph Completion tasks I followed the approach stated in the paper <a href="https://arxiv.org/pdf/1909.03193.pdf">KG-BERT — Bert for Knowledge Graph Completion.</a> The idea is to convert the triples (h,r,t) into a text classification problem for the first task, and then use a ranking algorithm to rank the predicted entities and relations in the most probable order.</p><blockquote>The pipeline</blockquote><p>Now, the transformer models are the big weapon in the hero’s toolkit. Think of the following section as a series of tasks that the hero must perform to become worthy of yielding the weapon.</p><p>First, the TSV file is read and the contents of every line are stored in a list containing the head entity value, the relation and the tail entity value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giJldJEdNX2rsT4yMR_UdA.png" /><figcaption>An example of train.tsv file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkI4ksvRlY5hKckOtlgWfQ.png" /><figcaption>Reading the contents of the tsv file</figcaption></figure><p>Second, the Head entity ID and Tail entity ID are replaced with their respective text. I used the Wikipedia python library to get longer definitions of single-word entities or relations. The reason for doing this is quite intuitive. In any language, knowing the meaning of words is required but rarely enough. To understand the context in which the word is used, it is essential that you look at the nearby words. You can achieve a better understanding if you read the entire sentence. An even better understanding of the context can be arrived at if you read the entire paragraph. Similarly, for a language model to make intelligent classification it is crucial that you replace the single words with long text sequences for better results.</p><p>Third, all the triples in the knowledge graph are labelled as 1 as they represent the ground truth. For every correct triple, an incorrect triple is created by replacing the head or tail entity with a different entity from the entity list and is labelled as 0.</p><p>Finally, the head entity, relation and tail entity are combined into a single sequence of text such that the three are separated using [SEP] tokens. Add the special token [CLS] as the classification head. These tokens allow the model to identify the different entities and relations as well as the label associated with the input text sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8SkM5tOWBB97AdhvveF3g.png" /><figcaption>Pipeline approach</figcaption></figure><p>Before giving the text sequence as input to the model there are a few more text transformation steps involved. I used a Tokeniser to split the textual sequence into words as well as to encode them into PyTorch tensors. These tensors can now be used as input to the model. I used transformer models which are pre-trained on sequence classification task as I wanted to classify the input text sequences into 2 classes — correct triples and incorrect triples.</p><p>This entire process is known as fine-tuning a transformer architecture where the parameters of a pre-trained transformer model are adjusted to improve its performance by training it on a different dataset than the one used before.</p><blockquote>Code</blockquote><pre>#Loading the Tokenizer<br>tokenizer = DebertaTokenizer.from_pretrained(&quot;microsoft/deberta-base&quot;, truncation=True, padding=&#39;max_length&#39;, max_length=115,return_tensors=&#39;pt&#39;)<br>#Encoding the words into PyTorch tensors<br>encoded_dataset = dataset.map(lambda x: tokenizer(x[&#39;triple_texts&#39;], truncation=True, padding=&#39;max_length&#39;, max_length=115,return_tensors=&#39;pt&#39;), remove_columns=[&#39;guid&#39;, &#39;triple_texts&#39;],batched=True)<br><br>#Loading the pretrained Transformer model for Sequence Classification Task<br>from transformers import DebertaForSequenceClassification<br>model = DebertaForSequenceClassification.from_pretrained(&#39;microsoft/deberta-base&#39;, num_labels=num_labels).to(device)from transformers import Trainer, TrainingArguments<br><br><br>#Defining the evaluation metrics<br><br>def compute_metrics(eval_pred):<br>  metric1 = evaluate.load(&quot;precision&quot;)<br>  metric2 = evaluate.load(&quot;recall&quot;)<br>  metric3 = evaluate.load(&quot;f1&quot;)<br>  metric4 = evaluate.load(&quot;accuracy&quot;)<br><br>  logits, labels = eval_pred<br>  predictions = np.argmax(logits, axis=-1)<br>  precision = metric1.compute(predictions=predictions, references=labels,average=&quot;weighted&quot;)[&quot;precision&quot;]<br>  recall = metric2.compute(predictions=predictions, references=labels, average=&quot;weighted&quot;)[&quot;recall&quot;]<br>  f1 = metric3.compute(predictions=predictions, references=labels, average=&quot;weighted&quot;)[&quot;f1&quot;]<br>  accuracy = metric4.compute(predictions=predictions, references=labels)[&quot;accuracy&quot;]<br><br>  return {&quot;precision&quot;: precision, &quot;recall&quot;: recall, &quot;f1&quot;: f1, &quot;accuracy&quot;: accuracy}<br><br>#Defining a custom loss function <br>class CustomTrainer(Trainer):<br>    def compute_loss(self, model, batch,return_outputs=False):<br>        num_labels = 2<br>        batch = batch.to(device) <br>        # forward pass<br>        outputs = model(**batch)<br>        logits = outputs.get(&quot;logits&quot;)<br>        # compute custom loss (suppose one has 3 labels with different weights)<br>        loss_fct = CrossEntropyLoss()<br>        loss = loss_fct(logits.view(-1, num_labels), batch[&#39;labels&#39;].view(-1))<br>        return (loss, outputs) if return_outputs else loss<br><br>#Using a custom trainer to train the model <br>from transformers.data.data_collator import default_data_collator<br>trainer = CustomTrainer(model = model,                  # model to be trained<br>    args = args,                    # training args<br>    train_dataset=encoded_dataset[&quot;train&quot;],<br>    eval_dataset=encoded_dataset[&quot;eval&quot;],<br>    tokenizer=tokenizer,            # for padding batched data<br>    data_collator=default_data_collator,<br>    compute_metrics=compute_metrics)<br><br>#Train!<br>trainer.train()</pre><blockquote>Results</blockquote><p>The pipeline resulted in 70% accuracy in classifying triples. Mean Rank value for Link Prediction task was 67 while for Relation Prediction task was 0.77. The approach used here outperforms the existing methods.</p><blockquote>Conclusion</blockquote><p>With LLMs becoming more advanced every day, they are finding unique applications across various industries. Combining LLMs with Knowledge Graphs allows us to leverage the vast vocabularies of the models to automate the completion of existing Knowledge Graphs. As we use more powerful hardware (advanced GPU architectures), we can achieve faster runtimes and optimised results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad993d601c7" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/automating-knowledge-graph-completion-using-transformers-bad993d601c7">Automating Knowledge Graph Completion using Transformers</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>