<?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 Vinod Krishnan on Medium]]></title>
        <description><![CDATA[Stories by Vinod Krishnan on Medium]]></description>
        <link>https://medium.com/@vinod.krishnan13?source=rss-83f97bb71364------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EyzkogGGnIuxP3km.jpg</url>
            <title>Stories by Vinod Krishnan on Medium</title>
            <link>https://medium.com/@vinod.krishnan13?source=rss-83f97bb71364------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:24:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinod.krishnan13/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[Your AI Agent has 847 tools. Here’s how to route to the right one in under 50ms.]]></title>
            <link>https://medium.com/@vinod.krishnan13/your-ai-agent-has-847-tools-heres-how-to-route-to-the-right-one-in-under-50ms-a848a14db87e?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/a848a14db87e</guid>
            <category><![CDATA[hybrid-search]]></category>
            <category><![CDATA[mongodb-atlas-search]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[atlasvectorsearch]]></category>
            <category><![CDATA[agent-tool-router]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 11:51:53 GMT</pubDate>
            <atom:updated>2026-04-19T11:51:53.662Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How MongoDB Atlas $rankFusion enables production-grade hybrid search for agentic AI tool registries</em></p><p>Most AI agent demos look impressive with 10 tools. Most AI agent failures happen when someone tries to scale that to 1,000.</p><p>The bottleneck is never the LLM. It’s the layer underneath — the tool routing layer. How does your agent know which tool to call? How does it know that tool is healthy, has the right permissions, isn’t deprecated, and will respond within your latency SLA?</p><p>In this post I’ll walk through a production-grade architecture for agent tool routing using MongoDB Atlas hybrid search — specifically the new $rankFusion aggregation stage — that combines semantic search, full-text search, and hard guardrails in a single pipeline.</p><h3>The Problem With How Most Teams Solve This</h3><p>The typical approach looks something like this:</p><ol><li>Store tool descriptions as vector embeddings in a vector database</li><li>At query time, embed the agent task and do a nearest-neighbour search</li><li>Filter the results with if/else logic for permissions and health</li><li>Return the top result and invoke it</li></ol><p>This works at small scale. It breaks in production for several reasons.</p><p><strong>Vector search alone isn’t enough.</strong> If an agent task says “post to the engineering Slack channel”, a pure semantic search might return tools that are conceptually related to communication but don’t match on the specific integration name. You need keyword matching to anchor on tool names, tags, and capability descriptors.</p><p><strong>Keyword search alone isn’t enough either.</strong> If the task says “summarise recent incidents and send a digest”, a keyword match on “summarise” and “digest” won’t find tools whose description says “aggregates and condenses incident reports for distribution” — even though that’s exactly the right tool.</p><p><strong>Filtering after search is expensive and incorrect.</strong> Post-filtering on permissions and health status after retrieving 100 candidates means you’re doing unnecessary work, and you might end up with zero valid results after filtering if the retrieval set was too small.</p><p><strong>Separate systems mean sync lag.</strong> If your tool registry lives in MongoDB and your vector index lives in Pinecone or Weaviate, you have two systems to keep in sync. When a tool is deprecated, updated, or goes unhealthy, that change needs to propagate to both — and until it does, your agent might invoke a tool that shouldn’t be invoked.</p><h3>The Better Architecture: One Pipeline, Four Signals</h3><p>MongoDB Atlas lets you collapse all of this into a single aggregation pipeline using $rankFusion — currently in Public Preview for MongoDB 8.0+.</p><p>The pipeline combines four distinct signals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXOXvXAaVuaFHk1BePn3Hg.png" /></figure><p>Your tool registry collection IS your search index. One system. No sync lag. No glue code.</p><h3>The Use Case: Agent Task Routing</h3><p>Let’s make this concrete with a realistic example.</p><p>An agent receives this task:</p><blockquote>“Summarise last week’s Jira tickets and post a digest to the engineering Slack channel”</blockquote><p>The agent has access to 10,000 tools in a registry collection called tool_registry. Each tool document looks like this:</p><pre>{<br>  &quot;_id&quot;: &quot;uuid&quot;,<br>  &quot;toolName&quot;: &quot;jira-summarise-v4&quot;,<br>  &quot;integration&quot;: &quot;Jira&quot;,<br>  &quot;version&quot;: 4,<br>  &quot;category&quot;: &quot;project-management&quot;,<br>  &quot;description&quot;: &quot;Agent-facing tool that summarises and returns Jira issues in structured format.&quot;,<br>  &quot;tags&quot;: [&quot;jira&quot;, &quot;summarise&quot;, &quot;agent-ready&quot;, &quot;paginated&quot;],<br>  &quot;agentPermissions&quot;: [&quot;read:jira&quot;, &quot;write:slack&quot;],<br>  &quot;healthStatus&quot;: &quot;healthy&quot;,<br>  &quot;p99LatencyMs&quot;: 38.2,<br>  &quot;isDeprecated&quot;: false,<br>  &quot;registeredAt&quot;: &quot;2026-03-15T08:22:00Z&quot;,<br>  &quot;endpoint&quot;: &quot;https://tools.internal/jira/summarise/4&quot;,<br>  &quot;inputSchema&quot;: { ... },<br>  &quot;capability_embedding&quot;: [0.21, 0.84, -0.37, ...]<br>}</pre><p>The capability_embedding field is a 128-dimensional vector generated by embedding the tool&#39;s description and tags. In production you&#39;d use a real embedding model — text-embedding-3-small from OpenAI, or Voyage AI&#39;s models which are available natively in Atlas.</p><h3>The Atlas Search Indexes</h3><p>Before running the pipeline you need two indexes on the tool_registry collection.</p><h3>Vector Search Index</h3><p>Create this in Atlas UI → Search → Create Search Index → JSON Editor, with index name tool_vector_idx:</p><pre>{<br>  &quot;fields&quot;: [<br>    {<br>      &quot;type&quot;: &quot;vector&quot;,<br>      &quot;path&quot;: &quot;capability_embedding&quot;,<br>      &quot;numDimensions&quot;: 128,<br>      &quot;similarity&quot;: &quot;cosine&quot;,<br>      &quot;quantization&quot;: &quot;scalar&quot;<br>    },<br>    { &quot;type&quot;: &quot;filter&quot;, &quot;path&quot;: &quot;healthStatus&quot; },<br>    { &quot;type&quot;: &quot;filter&quot;, &quot;path&quot;: &quot;isDeprecated&quot; },<br>    { &quot;type&quot;: &quot;filter&quot;, &quot;path&quot;: &quot;p99LatencyMs&quot; },<br>    { &quot;type&quot;: &quot;filter&quot;, &quot;path&quot;: &quot;agentPermissions&quot; }<br>  ]<br>}</pre><h3>Atlas Search Index</h3><p>Create this with index name tool_search_idx:</p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;dynamic&quot;: false,<br>    &quot;fields&quot;: {<br>      &quot;toolName&quot;:         { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.standard&quot; },<br>      &quot;description&quot;:      { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.standard&quot; },<br>      &quot;tags&quot;:             { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.standard&quot; },<br>      &quot;integration&quot;:      { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.keyword&quot; },<br>      &quot;category&quot;:         { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.keyword&quot; },<br>      &quot;healthStatus&quot;:     { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.keyword&quot; },<br>      &quot;isDeprecated&quot;:     { &quot;type&quot;: &quot;boolean&quot; },<br>      &quot;agentPermissions&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;analyzer&quot;: &quot;lucene.keyword&quot; },<br>      &quot;p99LatencyMs&quot;:     { &quot;type&quot;: &quot;number&quot; },<br>      &quot;version&quot;:          { &quot;type&quot;: &quot;number&quot; },<br>      &quot;registeredAt&quot;:     { &quot;type&quot;: &quot;date&quot; }<br>    }<br>  }<br>}</pre><h3>The Hybrid Search Pipeline</h3><p>Here is the full aggregation pipeline:</p><pre>db.tool_registry.aggregate([// Stage 1: $rankFusion - hybrid fusion of vector + text<br>  {<br>    $rankFusion: {<br>      input: {<br>        pipelines: {<br>          // Sub-pipeline A: semantic vector search<br>          vectorPipe: [<br>            {<br>              $vectorSearch: {<br>                index: &quot;tool_vector_idx&quot;,<br>                path: &quot;capability_embedding&quot;,<br>                queryVector: /* 128-dim embedding of agent task */,<br>                numCandidates: 300,<br>                limit: 60<br>              }<br>            },<br>            { $limit: 60 }<br>          ],<br>          // Sub-pipeline B: full-text + fuzzy search<br>          textPipe: [<br>            {<br>              $search: {<br>                index: &quot;tool_search_idx&quot;,<br>                compound: {<br>                  must: [<br>                    {<br>                      text: {<br>                        query: &quot;Jira Slack digest summary post&quot;,<br>                        path: [&quot;toolName&quot;, &quot;tags&quot;, &quot;description&quot;],<br>                        fuzzy: { maxEdits: 1, prefixLength: 3 }<br>                      }<br>                    }<br>                  ],<br>                  mustNot: [<br>                    { equals: { path: &quot;isDeprecated&quot;, value: true } }<br>                  ]<br>                }<br>              }<br>            },<br>            { $limit: 60 }<br>          ]<br>        }<br>      },<br>      combination: {<br>        weights: {<br>          vectorPipe: 0.6,  // semantic intent - primary signal<br>          textPipe:   0.4   // keyword precision - supporting signal<br>        }<br>      },<br>      scoreDetails: true<br>    }<br>  },<br>  // Stage 2: $match - hard guardrails<br>  {<br>    $match: {<br>      agentPermissions: { $in: [&quot;read:jira&quot;, &quot;write:slack&quot;] },<br>      healthStatus:     &quot;healthy&quot;,<br>      p99LatencyMs:     { $lte: 200 },<br>      isDeprecated:     false<br>    }<br>  },<br>  // Stage 3: shape output for agent consumption<br>  {<br>    $project: {<br>      _id:          0,<br>      toolName:     1,<br>      integration:  1,<br>      version:      1,<br>      endpoint:     1,<br>      inputSchema:  1,<br>      healthStatus: 1,<br>      p99LatencyMs: 1,<br>      score:        { $meta: &quot;score&quot; }<br>    }<br>  },<br>  // Stage 4: top-3 candidates back to agent<br>  { $limit: 3 }<br>])</pre><h3>Understanding Each Stage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYjaBPTUFZTzbEdoPSYfRw.png" /></figure><h3>$rankFusion — The Core</h3><p>$rankFusion is the wrapper that makes hybrid search native. It executes both sub-pipelines independently and then combines their results using <strong>Reciprocal Rank Fusion (RRF)</strong>.</p><p>RRF works by looking at where each document appears in each ranked list, not what its raw score was. A document that ranks #3 in the vector search and #5 in the text search will likely outrank a document that only appears in one list — even if that document has a slightly higher raw score in its list.</p><p>The weights parameter lets you tune how much each signal contributes. Here I&#39;ve set vectorPipe: 0.6 and textPipe: 0.4 because semantic intent should be the dominant signal for natural language agent tasks. You&#39;d tune this based on your specific tool registry and task distribution.</p><p>Setting scoreDetails: true gives you a breakdown of how each document&#39;s final score was computed — useful for debugging and tuning.</p><h3>$vectorSearch — Semantic Intent</h3><p>The vector sub-pipeline embeds the agent’s task description and finds tools whose capability embeddings are closest in semantic space.</p><p>The key insight here is that numCandidates: 300 and limit: 60 are separate parameters. numCandidates controls how many documents the ANN algorithm considers during its search — a higher value increases recall at the cost of latency. limit is how many results you pass to $rankFusion. Setting both appropriately is important: too few candidates and you miss relevant tools; too many and you slow down the pipeline.</p><h3>$search — Keyword Precision + Fuzzy Matching</h3><p>The text sub-pipeline uses Atlas Search’s compound query with must and mustNot clauses.</p><p>The must clause does full-text search across toolName, tags, and description with fuzzy matching (maxEdits: 1) — so &quot;Jira&quot; matches &quot;Jira&quot; exactly, but &quot;Slak&quot; also matches &quot;Slack&quot;. The prefixLength: 3 parameter means the first 3 characters must match exactly before fuzzy logic kicks in, which prevents false positives.</p><p>The mustNot clause explicitly excludes deprecated tools at the search level — before they even reach $rankFusion. This is more efficient than filtering after fusion.</p><h3>$match — Hard Guardrails</h3><p>This is the non-negotiable layer. After fusion, $match enforces:</p><ul><li><strong>agentPermissions</strong> — the agent must have all required permissions for the tool it invokes. Using $in checks that at least one of the agent&#39;s permissions matches the tool&#39;s requirements.</li><li><strong>healthStatus: &quot;healthy&quot;</strong> — never invoke a degraded or unhealthy tool.</li><li><strong>p99LatencyMs: { $lte: 200 }</strong> — enforce your latency SLA. A tool that responds in 800ms p99 is not a viable option for a real-time agent.</li><li><strong>isDeprecated: false</strong> — belt and braces — this is also handled in $search but the $match stage guarantees it regardless.</li></ul><h3>A Critical Design Decision: Date Filters Don’t Belong Here</h3><p>One thing that might seem natural is adding a date filter to the pipeline — filtering tools by registeredAt for &quot;last week&quot; to match the task&#39;s time scope.</p><p>Don’t do this.</p><p>registeredAt is when the <strong>tool itself was registered</strong>, not when the data it operates on was created. A jira-summarise-v4 tool registered 6 months ago is perfectly valid for summarising last week&#39;s Jira tickets. Filtering on registeredAt would exclude most of your best, battle-tested tools and only return tools registered recently — the opposite of what you want.</p><p>The date range &quot;last week&quot; belongs in the <strong>tool&#39;s input parameters</strong> when the agent invokes it — as part of the inputSchema call to the tool&#39;s endpoint. The pipeline&#39;s job is to find the right tool. The tool&#39;s job is to handle the task parameters.</p><p>This is a clean separation of concerns that matters at scale.</p><h3>Results</h3><p>For the task <em>“Summarise last week’s Jira tickets and post a digest to the Slack channel”</em>, the pipeline returns:</p><pre>[<br>  {<br>    &quot;toolName&quot;: &quot;jira-summarise-v4&quot;,<br>    &quot;integration&quot;: &quot;Jira&quot;,<br>    &quot;version&quot;: 4,<br>    &quot;endpoint&quot;: &quot;https://tools.internal/jira/summarise/4&quot;,<br>    &quot;healthStatus&quot;: &quot;healthy&quot;,<br>    &quot;p99LatencyMs&quot;: 38.2,<br>    &quot;score&quot;: 0.94<br>  },<br>  {<br>    &quot;toolName&quot;: &quot;slack-post-v3&quot;,<br>    &quot;integration&quot;: &quot;Slack&quot;,<br>    &quot;version&quot;: 3,<br>    &quot;endpoint&quot;: &quot;https://tools.internal/slack/post/3&quot;,<br>    &quot;healthStatus&quot;: &quot;healthy&quot;,<br>    &quot;p99LatencyMs&quot;: 51.4,<br>    &quot;score&quot;: 0.89<br>  },<br>  {<br>    &quot;toolName&quot;: &quot;confluence-export-v2&quot;,<br>    &quot;integration&quot;: &quot;Confluence&quot;,<br>    &quot;version&quot;: 2,<br>    &quot;endpoint&quot;: &quot;https://tools.internal/confluence/export/2&quot;,<br>    &quot;healthStatus&quot;: &quot;healthy&quot;,<br>    &quot;p99LatencyMs&quot;: 112.0,<br>    &quot;score&quot;: 0.74<br>  }<br>]</pre><p>The agent receives the top 3 candidates, picks the most relevant based on the task breakdown, and invokes them with task-specific parameters — including the date range for “last week”.</p><h3>Why This Matters at Scale</h3><p>The architecture decisions here compound as your tool registry grows.</p><p><strong>At 10 tools</strong> — any approach works. A simple list scan is fine.</p><p><strong>At 100 tools</strong> — vector search alone starts to miss. Keyword matching catches tools that semantically similar embeddings don’t rank highly.</p><p><strong>At 1,000 tools</strong> — post-filtering after retrieval becomes risky. If you retrieve 50 candidates and filter out all unhealthy or unauthorised tools, you might have 3 left — and they might not be the right 3. Pre-filtering inside $vectorSearch and mustNot inside $search ensures your candidate set is valid before fusion happens.</p><p><strong>At 10,000 tools</strong> — sync lag between your tool registry and a separate vector database becomes a reliability problem. A tool deprecated in your registry might still be indexed in Pinecone for minutes or hours. Using Atlas for both your operational data and your search index means deprecation is instant and consistent.</p><h3>$rankFusion vs $scoreFusion</h3><p>MongoDB Atlas offers two fusion stages, both in Public Preview:</p><p><strong>$rankFusion</strong> (MongoDB 8.0+) uses Reciprocal Rank Fusion — documents are ranked based on their <em>positions</em> in each input pipeline. It&#39;s simpler to reason about and a great starting point.</p><p><strong>$scoreFusion</strong> (MongoDB 8.2+) ranks based on the <em>actual scores</em> from each pipeline, normalised to a 0–1 range and combined via weighted average. It gives you more granular control when the magnitude of scores matters, not just the relative ordering.</p><p>For tool routing, $rankFusion is the right choice. What matters is relative ranking — is this tool more relevant than that one? — not the absolute score value.</p><h3>Conclusion</h3><p>Agent tool routing is a search problem. And like all search problems at scale, it requires multiple signals fused intelligently — not a single retrieval method applied naively.</p><p>MongoDB Atlas $rankFusion makes this native. Your tool registry is your search index. Semantic intent, keyword precision, and hard guardrails live in one pipeline. Deprecation and health changes propagate instantly. No glue code. No sync lag. No separate vector database to maintain.</p><p>The teams building reliable agentic AI at scale aren’t just building better agents. They’re building better infrastructure underneath them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a848a14db87e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Multi-Tenant Data with MongoDB’s ExpliClient-Side Field Level Encryption and FastAPI]]></title>
            <link>https://medium.com/@vinod.krishnan13/securing-multi-tenant-data-with-mongodbs-expliclient-side-field-level-encryption-and-fastapi-dc554ec478aa?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc554ec478aa</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[csfle]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 17:50:14 GMT</pubDate>
            <atom:updated>2025-06-30T18:00:46.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Securing Multi-Tenant Data with MongoDB’s Explicit Client-Side Field Level Encryption and FastAPI</h3><h3>A practical guide to implementing robust, tenant-specific encryption in your applications</h3><p>In the world of multi-tenant applications, ensuring data privacy and security is not just a feature; it’s a fundamental requirement. Each tenant’s data must be cryptographically isolated to prevent unauthorized access, even from database administrators. MongoDB’s <strong>Explicit</strong> <strong>Client-Side Field Level Encryption (CSFLE)</strong> provides a powerful solution to this challenge.</p><p>This article will walk you through building a secure REST API using FastAPI that implements CSFLE with multiple Customer Master Keys (CMKs) and Data Encryption Keys (DEKs). We’ll create a system where each tenant has their own set of keys, ensuring their data is encrypted with a key that only they (via the application) can access.</p><figure><img alt="Client-side Field Level Explicit Encryption" src="https://cdn-images-1.medium.com/max/1024/1*Ri4PhDpXhi8S5MflO4vysQ.png" /></figure><h3>What We’re Building</h3><p>We will develop a simple Healthcare API with the following features:</p><ul><li><strong>FastAPI backend:</strong> A modern, high-performance Python web framework.</li><li><strong>MongoDB Atlas Cluster :</strong> To store patient records.</li><li><strong>Multi-tenancy:</strong> The API will support multiple tenants, each with their own isolated data.</li><li><strong>Client-Side Field Level Encryption (CSFLE):</strong> Sensitive patient data (phone number and email) will be encrypted at the field level before being sent to the database.</li><li><strong>Tenant-specific keys:</strong> Each tenant will have their own Customer Master Key (CMK) and Data Encryption Key (DEK). CMKs will be stored locally, and DEKs will be managed in a dedicated MongoDB collection (the key vault).</li><li><strong>CRUD operations:</strong> The API will provide endpoints to create, read, update, and delete patient records.</li></ul><h3>Prerequisites</h3><ul><li>Python 3.7+</li><li>MongoDB Atlas account or a local MongoDB instance</li><li>Basic understanding of FastAPI and MongoDB</li></ul><h3>Project Setup</h3><p>First, let’s set up our project structure:</p><pre>/your-project-folder<br>|-- app.py<br>|-- tenant_1.txt<br>|-- tenant_2.txt<br>|-- requirements.txt</pre><h3>Install the necessary Python libraries:</h3><pre>pip install fastapi &quot;uvicorn[standard]&quot; pymongo pymongo-auth-aws pymongo-encryption faker</pre><h3>Understanding the Key Concepts</h3><p>Before we dive into the code, let’s clarify the key components of our encryption strategy:</p><ul><li><strong>Customer Master Key (CMK):</strong> This is a top-level key used to encrypt other keys. In our case, we’ll use local files as our CMKs. In a production environment, you would use a KMS like AWS KMS, Azure Key Vault, or Google Cloud KMS.</li><li><strong>Data Encryption Key (DEK):</strong> This key is used to encrypt the actual data. Each tenant will have their own DEK, which will be encrypted by their respective CMK and stored in a special MongoDB collection called the key vault.</li><li><strong>Key Vault:</strong> This is a dedicated MongoDB collection that stores the DEKs. By default, it’s named encryption.__keyVault.</li></ul><p>Of course, here is the complete content for a Medium article explaining your Python code.</p><h3>Securing Multi-Tenant Data with MongoDB Client-Side Field Level Encryption and FastAPI</h3><h3>A practical guide to implementing robust, tenant-specific encryption in your applications</h3><p>In the world of multi-tenant applications, ensuring data privacy and security is not just a feature; it’s a fundamental requirement. Each tenant’s data must be cryptographically isolated to prevent unauthorized access, even from database administrators. MongoDB’s Client-Side Field Level Encryption (CSFLE) provides a powerful solution to this challenge.</p><p>This article will walk you through building a secure REST API using FastAPI that implements CSFLE with multiple Customer Master Keys (CMKs) and Data Encryption Keys (DEKs). We’ll create a system where each tenant has their own set of keys, ensuring their data is encrypted with a key that only they (via the application) can access.</p><h3>What We’re Building</h3><p>We will develop a simple Healthcare API with the following features:</p><ul><li><strong>FastAPI backend:</strong> A modern, high-performance Python web framework.</li><li><strong>MongoDB database:</strong> To store patient records.</li><li><strong>Multi-tenancy:</strong> The API will support multiple tenants, each with their own isolated data.</li><li><strong>Client-Side Field Level Encryption (CSFLE):</strong> Sensitive patient data (phone number and email) will be encrypted at the field level before being sent to the database.</li><li><strong>Tenant-specific keys:</strong> Each tenant will have their own Customer Master Key (CMK) and Data Encryption Key (DEK). CMKs will be stored locally, and DEKs will be managed in a dedicated MongoDB collection (the key vault).</li><li><strong>CRUD operations:</strong> The API will provide endpoints to create, read, update, and delete patient records.</li></ul><h3>Prerequisites</h3><ul><li>Python 3.7+</li><li>MongoDB Atlas account or a local MongoDB instance</li><li>Basic understanding of FastAPI and MongoDB</li></ul><h3>Project Setup</h3><p>First, let’s set up our project structure:</p><pre>/your-project-folder<br>|-- main.py<br>|-- tenant_1.txt<br>|-- tenant_2.txt<br>|-- requirements.txt</pre><p>Install the necessary Python libraries:</p><p>Bash</p><pre>pip install fastapi &quot;uvicorn[standard]&quot; pymongo pymongo-auth-aws pymongo-encryption faker</pre><h3>Understanding the Key Concepts</h3><p>Before we dive into the code, let’s clarify the key components of our encryption strategy:</p><ul><li><strong>Customer Master Key (CMK):</strong> This is a top-level key used to encrypt other keys. In our case, we’ll use local files as our CMKs. In a production environment, you would use a KMS like AWS KMS, Azure Key Vault, or Google Cloud KMS.</li><li><strong>Data Encryption Key (DEK):</strong> This key is used to encrypt the actual data. Each tenant will have their own DEK, which will be encrypted by their respective CMK and stored in a special MongoDB collection called the key vault.</li><li><strong>Key Vault:</strong> This is a dedicated MongoDB collection that stores the DEKs. By default, it’s named encryption.__keyVault.</li></ul><h3>Let’s Get Coding!</h3><p>Here’s the complete code for our app.py file. We&#39;ll break it down section by section.</p><pre>from fastapi import FastAPI, HTTPException, Depends, Header<br>from pydantic import BaseModel<br>from typing import Dict, Optional, List, Any<br>from pymongo import MongoClient<br>from pymongo.encryption_options import AutoEncryptionOpts<br>from pymongo.encryption import Algorithm, ClientEncryption<br>import base64<br>import os<br>from bson.codec_options import CodecOptions<br>from bson.binary import STANDARD, UUID<br>from bson.objectid import ObjectId<br>from faker import Faker<br>from fastapi.middleware.cors import CORSMiddleware<br>import logging<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br># Initialize FastAPI app<br>app = FastAPI(<br>    title=&quot;Healthcare API with Tenant Encryption&quot;,<br>    description=&quot;API demonstrating MongoDB client-side field level encryption with tenant isolation&quot;<br>)<br><br># Initialize Faker for test data<br>fake = Faker(&#39;en_GB&#39;)<br><br># MongoDB configuration<br>connection_string = &quot;YOUR_MONGODB_CONNECTION_STRING&quot;<br>key_vault_namespace = &quot;encryption.__keyVault&quot;<br><br># Create a global MongoDB client to be used across the application<br>mongodb_client = MongoClient(connection_string, maxPoolSize=50)<br><br># Ensure we have a database and collections<br>healthcare_db = mongodb_client[&quot;healthcare_db&quot;]<br>patients_collection = healthcare_db[&quot;patients&quot;]<br>key_vault_db = mongodb_client[&quot;encryption&quot;]<br>key_vault_coll = key_vault_db[&quot;__keyVault&quot;]<br><br># Load tenant master keys<br>def load_tenant_keys():<br>    tenant_keys = {}<br>    tenant1_path = &quot;./tenant_1.txt&quot;<br>    tenant2_path = &quot;./tenant_2.txt&quot;<br>    <br>    try:<br>        with open(tenant1_path, &quot;rb&quot;) as f:<br>            tenant_keys[&quot;tenant1&quot;] = f.read()<br>        <br>        with open(tenant2_path, &quot;rb&quot;) as f:<br>            tenant_keys[&quot;tenant2&quot;] = f.read()<br>            <br>        logger.info(&quot;Successfully loaded tenant encryption keys&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;Failed to load tenant keys: {str(e)}&quot;)<br>        raise<br>    <br>    return tenant_keys<br><br># Initialize tenant keys<br>tenant_keys = load_tenant_keys()<br><br># Cache for tenant encryption clients<br>tenant_encryption_clients = {}<br><br># Pydantic models<br>class PatientBase(BaseModel):<br>    patient_id: str<br>    name: str<br>    phone_no: str<br>    email: str<br>    <br>class PatientCreate(PatientBase):<br>    pass<br><br>class PatientResponse(PatientBase):<br>    id: str<br>    tenant_id: str<br>    <br>    class Config:<br>        schema_extra = {<br>            &quot;example&quot;: {<br>                &quot;id&quot;: &quot;60d21b4967d0d8992e610c85&quot;,<br>                &quot;tenant_id&quot;: &quot;tenant1&quot;,<br>                &quot;patient_id&quot;: &quot;P12345&quot;,<br>                &quot;name&quot;: &quot;John Doe&quot;,<br>                &quot;phone_no&quot;: &quot;+44 7700 900077&quot;,<br>                &quot;email&quot;: &quot;patient@example.com&quot;<br>            }<br>        }<br><br># Get or create encryption client for a tenant<br>def get_client_encryption(tenant_id: str):<br>    if tenant_id in tenant_encryption_clients:<br>        return tenant_encryption_clients[tenant_id]<br>        <br>    if tenant_id not in tenant_keys:<br>        raise HTTPException(status_code=400, detail=f&quot;No encryption key found for tenant {tenant_id}&quot;)<br>    <br>    tenant_kms_providers = {<br>        &quot;local&quot;: {<br>            &quot;key&quot;: tenant_keys[tenant_id]<br>        }<br>    }<br>    <br>    key_exists = key_vault_coll.find_one({&quot;keyAltNames&quot;: f&quot;{tenant_id}_key&quot;})<br>    <br>    client_encryption = ClientEncryption(<br>        tenant_kms_providers,<br>        key_vault_namespace,<br>        mongodb_client,<br>        CodecOptions(uuid_representation=STANDARD)<br>    )<br>    <br>    if not key_exists:<br>        logger.info(f&quot;Creating new data key for tenant {tenant_id}&quot;)<br>        try:<br>            client_encryption.create_data_key(<br>                &quot;local&quot;, <br>                key_alt_names=[f&quot;{tenant_id}_key&quot;]<br>            )<br>        except Exception as e:<br>            logger.error(f&quot;Failed to create data key: {str(e)}&quot;)<br>    <br>    tenant_encryption_clients[tenant_id] = client_encryption<br>    return client_encryption<br><br># Dependency for tenant validation<br>async def validate_tenant(tenant_id: str = Header(..., description=&quot;Tenant identifier&quot;)):<br>    if tenant_id not in tenant_keys:<br>        raise HTTPException(status_code=400, detail=&quot;Invalid tenant ID&quot;)<br>    return tenant_id<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    logger.info(&quot;Starting up API server&quot;)<br>    for tenant_id in tenant_keys:<br>        get_client_encryption(tenant_id)<br>    logger.info(&quot;API server started successfully&quot;)<br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown_event():<br>    logger.info(&quot;Shutting down API server&quot;)<br>    mongodb_client.close()<br>    logger.info(&quot;MongoDB connection closed&quot;)<br><br>@app.post(&quot;/patients/&quot;, response_model=PatientResponse, summary=&quot;Create a new patient record&quot;)<br>async def create_patient(<br>    patient: PatientCreate, <br>    tenant_id: str = Depends(validate_tenant)<br>):<br>    client_encryption = get_client_encryption(tenant_id)<br>    <br>    try:<br>        encrypted_data = {<br>            &quot;tenant_id&quot;: tenant_id,<br>            &quot;patient_id&quot;: patient.patient_id,<br>            &quot;name&quot;: patient.name,<br>            &quot;phone_no&quot;: client_encryption.encrypt(<br>                patient.phone_no,<br>                Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,<br>                key_alt_name=f&quot;{tenant_id}_key&quot;<br>            ),<br>            &quot;email&quot;: client_encryption.encrypt(<br>                patient.email,<br>                Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic,<br>                key_alt_name=f&quot;{tenant_id}_key&quot;<br>            )<br>        }<br>        <br>        result = patients_collection.insert_one(encrypted_data)<br>        <br>        logger.info(f&quot;Created patient record for tenant {tenant_id}: {result.inserted_id}&quot;)<br>        <br>        return {<br>            &quot;id&quot;: str(result.inserted_id),<br>            &quot;tenant_id&quot;: tenant_id,<br>            &quot;patient_id&quot;: patient.patient_id,<br>            &quot;name&quot;: patient.name,<br>            &quot;phone_no&quot;: patient.phone_no,<br>            &quot;email&quot;: patient.email<br>        }<br>    except Exception as e:<br>        logger.error(f&quot;Error creating patient: {str(e)}&quot;)<br>        raise HTTPException(status_code=500, detail=f&quot;Failed to create patient: {str(e)}&quot;)<br><br>@app.get(&quot;/patients/{patient_id}&quot;, response_model=PatientResponse, summary=&quot;Get a patient record&quot;)<br>async def get_patient(<br>    patient_id: str,<br>    tenant_id: str = Depends(validate_tenant)<br>):<br>    try:<br>        patient = patients_collection.find_one({<br>            &quot;_id&quot;: ObjectId(patient_id), <br>            &quot;tenant_id&quot;: tenant_id<br>        })<br>        <br>        if not patient:<br>            logger.warning(f&quot;Patient {patient_id} not found for tenant {tenant_id}&quot;)<br>            raise HTTPException(status_code=404, detail=&quot;Patient not found&quot;)<br>        <br>        client_encryption = get_client_encryption(tenant_id)<br>        <br>        decrypted_phone = client_encryption.decrypt(patient[&quot;phone_no&quot;])<br>        decrypted_email = client_encryption.decrypt(patient[&quot;email&quot;])<br>        <br>        return {<br>            &quot;id&quot;: str(patient[&quot;_id&quot;]),<br>            &quot;tenant_id&quot;: patient[&quot;tenant_id&quot;],<br>            &quot;patient_id&quot;: patient[&quot;patient_id&quot;],<br>            &quot;name&quot;: patient[&quot;name&quot;],<br>            &quot;phone_no&quot;: decrypted_phone,<br>            &quot;email&quot;: decrypted_email<br>        }<br>    except Exception as e:<br>        logger.error(f&quot;Error retrieving patient {patient_id}: {str(e)}&quot;)<br>        raise HTTPException(status_code=500, detail=f&quot;Failed to retrieve patient: {str(e)}&quot;)<br></pre><h3>Code Breakdown</h3><h4>1. Initialization and Configuration</h4><ul><li>We import all the necessary libraries, including FastAPI for the web framework and pymongo for MongoDB interaction.</li><li>We set up basic logging to monitor the application’s behavior.</li><li>The FastAPI app is initialized with a title and description.</li><li>We define the MongoDB connection string and the key vault namespace.</li><li>A global MongoClient is created to interact with the database.</li></ul><h4>2. Loading Tenant Master Keys</h4><p>The load_tenant_keys function is responsible for loading the CMKs from local files. In a real-world scenario, you would fetch these from a secure key management service.</p><ul><li>We create two files, tenant_1.txt and tenant_2.txt, in the project directory.</li><li>Generate a 96-byte key for each tenant. You can use the following command to generate a key and save it to a file:</li></ul><pre>openssl rand 96 &gt; tenant_1.txt<br>openssl rand 96 &gt; tenant_2.txt</pre><h4>3. Generate the Data Encryption Keys</h4><pre>tenant1_path = &quot;./tenant_1.txt&quot;<br>tenant2_path = &quot;./tenant_2.txt&quot;<br><br>with open(tenant1_path, &quot;rb&quot;) as f:<br>    tenant1_master_key = f.read()<br><br>with open(tenant2_path, &quot;rb&quot;) as f:<br>    tenant2_master_key = f.read()<br><br># Customer master key<br>tenant1_kms_providers = {<br>    &quot;local&quot;: {<br>        &quot;key&quot;: tenant1_master_key<br>    },<br>}<br><br>tenant2_kms_providers = {<br>    &quot;local&quot;: {<br>        &quot;key&quot;: tenant2_master_key<br>    },<br>}<br>connection_string = &quot;YOUR MONGDOB SRV CONNECTION STRING&quot;<br><br><br># start-create-dek<br>key_vault_database = &quot;encryption&quot;<br>key_vault_collection = &quot;__keyVault&quot;<br>key_vault_namespace = f&quot;{key_vault_database}.{key_vault_collection}&quot;<br><br>client = MongoClient(connection_string)<br>tenant_db=client[&quot;healthcare_db&quot;]<br><br>tenant1_client_encryption = ClientEncryption(<br>    tenant1_kms_providers,  # pass in the kms_providers variable from the previous step<br>    key_vault_namespace,<br>    client,<br>    CodecOptions(uuid_representation=STANDARD),<br>)<br><br>tenant2_client_encryption = ClientEncryption(<br>    tenant2_kms_providers,  # pass in the kms_providers variable from the previous step<br>    key_vault_namespace,<br>    client,<br>    CodecOptions(uuid_representation=STANDARD),<br>)<br><br>tenant_1_data_key_id = tenant1_client_encryption.create_data_key(&quot;local&quot;,key_alt_names=[&quot;tenant1_key&quot;])<br>tenant_2_data_key_id = tenant2_client_encryption.create_data_key(&quot;local&quot;,key_alt_names=[&quot;tenant2_key&quot;])</pre><h4>4. Managing Encryption Clients</h4><p>The get_client_encryption function is the core of our encryption logic.</p><ul><li>It takes a tenant_id as input and returns a ClientEncryption object.</li><li><strong>Caching:</strong> To avoid re-creating the client for every request, we use a simple dictionary (tenant_encryption_clients) as a cache.</li><li><strong>KMS Provider:</strong> We configure a “local” KMS provider, passing the tenant’s CMK.</li><li><strong>DEK Creation:</strong> The function checks if a DEK already exists for the tenant in the key vault. If not, it creates a new one using client_encryption.create_data_key().</li></ul><h4>5. FastAPI Endpoints</h4><ul><li><strong>validate_tenant:</strong> This is a dependency that extracts the tenant_id from the request header and validates it against our known tenants.</li><li><strong>startup_event:</strong> When the application starts, we pre-initialize the encryption clients for all tenants to improve performance.</li><li><strong>create_patient: </strong>It receives the patient data and the tenant_id. It retrieves the appropriate ClientEncryption object. It explicitly encrypts the phone_no and email fields using client_encryption.encrypt(). It inserts the encrypted data into the patients collection.</li><li><strong>get_patient: </strong>It fetches the encrypted patient record from the database. It retrieves the ClientEncryption object for the tenant. It decrypts the phone_no and email fields using client_encryption.decrypt(). It returns the decrypted data to the client. The update_patient and delete_patient endpoints follow a similar pattern, ensuring that all interactions with sensitive data are done through the appropriate tenant&#39;s encryption client.</li></ul><h3>Running the Application</h3><ol><li>Make sure your MongoDB instance is running and you’ve updated the connection_string in app.py.</li><li>Create the tenant_1.txt and tenant_2.txt files with your generated keys.</li><li>Run the application using uvicorn:</li></ol><pre>uvicorn app:app --reload</pre><p>You can now access the API documentation at http://127.0.0.1:8000/docs and test the endpoints.</p><h3>Conclusion</h3><p>By implementing MongoDB’s CSFLE with a multi-tenant architecture, you can build highly secure applications that provide strong data isolation guarantees. This approach ensures that even if your database is compromised, sensitive data remains protected.</p><p>While this example uses local files for CMKs, you can easily adapt it to use a cloud-based KMS for enhanced security and manageability. The key is to ensure that your application has a robust system for managing and using tenant-specific encryption keys.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc554ec478aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ColPali-inspired Retrieval Augmented Generation with MongoDB Atlas and Voyage AI]]></title>
            <link>https://medium.com/@vinod.krishnan13/colpali-inspired-retrieval-augmented-generation-with-mongodb-atlas-and-voyage-ai-27c703a9061a?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c703a9061a</guid>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[claude-3-5-sonnet]]></category>
            <category><![CDATA[colpali]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 06:15:27 GMT</pubDate>
            <atom:updated>2025-01-22T01:09:04.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Retrieval Augmented Generation (RAG) has been a game-changer in natural language processing, allowing AI models to pull in external knowledge to generate better responses.</p><p>But let’s face it: traditional RAG can sometimes be as clueless as a goldfish trying to solve a Rubik’s Cube. There are many moving parts in traditional RAG mainly retrieval of relevant context.</p><p>When working with text, image, tables, caption rich PDF’s, this retrieval often gives poor context to the generative LLM. We implement chunking to improve relevancy and accuracy of RAG Solutions, However Chunking pdf might lose context in translation when it comes to image, caption, table rich PDF. In this case, Our chunking strategy cannot be “One size fits all” i.e. One Chunking strategy for all PDF’s wont work. An Example could be Quarterly performance reports of different companies, They will have different layouts when it comes to image, captions, tables etc.</p><p>Enter <strong>ColPali</strong>, a cutting-edge technique that leverages Visual Language Models (VLMs) to make retrieval-augmented generation smarter, more visually aware. In this article, we’ll understand</p><ul><li>What is a VLM</li><li>How ColPali leverages VLM</li><li>What is Voyage AI — voyage-multimodal-3</li><li>Implement RAG on top of a text/table/image rich PDF with</li></ul><blockquote><strong>Embedding Model </strong>— Voyage AI (multi modal embeddings)</blockquote><blockquote><strong>Vector Store for storage and retrieval </strong>— MongoDB Atlas</blockquote><blockquote><strong>Generation</strong> — AWS Bedrock hosted Claude-Sonet as generative LLM</blockquote><h3><strong>What is a VLM</strong></h3><p><strong>Vision</strong> <strong>Language Models</strong> are AI systems that can understand and generate content by combining visual and textual information. Unlike traditional language models that only process text, VLMs can analyze images, diagrams, and even the layout of documents like PDFs, making them perfect for tasks like:</p><ul><li>Extracting text from scanned PDFs (e.g., <em>“What does this handwritten note say?”</em>)</li><li>Understanding tables and charts in reports (e.g., <em>“What’s the revenue trend in Q3?”</em>)</li><li>Retrieving specific information from visually complex documents (e.g., <em>“Find the section about Cash Flow in this 50-page PDF”</em>)</li></ul><h3><strong>How ColPali leverages VLM</strong></h3><p>ColPali is a Paligemma-3B extension that is capable of generating ColBERT-style multi-vector representations of text and images.</p><p><strong>Offline Phase</strong></p><ul><li>Split documents into smaller pieces called patches processed by the vision encoder of VLM to generate Visual Embedding for each patch (Ed)</li><li>Visual embedding passed through a projection layer, projected into higher dimension space , incorporating all spatial information</li><li>Visual Embeddings are aligned with text embedding, ColPali uses late interaction method similar to Colbert to generate multi vector representation for both document patches in query</li><li>Colpali divides pages in 1024 multi vector — 32X32 grid — lot of multi vectors per page</li><li>Each image patch processed by a vision encoder, Fed into linear projection — preserving spatial layout within the document , understand relative position of patches between each other to have contextualised embedding</li><li>This is then fed into LLM for semantic understanding and projected into projection layer. This gives 128 dimension vector embedding for each patch, hence multi vector embedding for each page i.e. 1024 vectors per page</li></ul><p><strong>Online Phase</strong></p><ul><li>Tokenise query to get embeddings using an LLM for each token (Eq)</li><li>Use projection layer to align with patch embedding in the same space</li><li>Multi vector is generated for query</li><li>Late interaction mechanism — Patch level similarity score during query evaluation, makes sure we have precise ranking</li><li>This score is computed for each query token (of query) against each document vector (of each page of PDF)</li><li>Compute similarity score — ColPali uses maxsim</li><li>Final relevance score(LI) between a query and a document page is calculated by summing up (max score calculated between a query token vector and all document vectors of a page)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*6wiZlwlVM625xvVIoGQHrQ.png" /><figcaption>Source — <a href="https://arxiv.org/abs/2407.01449">ColPali White Paper</a></figcaption></figure><ul><li>i is a single vector out of multiple vector representation of query (separate vector for each token)</li><li>j is single vector out of multiple vector representation of a page of document</li><li>Max of dot product is taken for a given token vector against all vectors of a page of document</li><li>Sum is done at query level to calculate a relevance score , which identifies how relevant this page is to the query</li></ul><h3>What is Voyage AI — voyage-multimodal-3</h3><p>Voyage multimodal embedding models can directly vectorise inputs containing interleaved text + images.</p><p>Voyage AI provides a visual embedding API endpoint based on VLMs inspired by ColPali and DSE.</p><p>In the offline phase instead of getting multi vector representation for each page of the PDF, we get a single vector embedding for each page without losing any semantic context.</p><p>Similarly in online phase for each query there would be a single embedding instead of having separate vector embedding for each token in query.</p><h3><strong>Implement RAG on top of a text/table/image rich PDF</strong></h3><p><strong>Pre-requisites</strong></p><ul><li><a href="https://dash.voyageai.com/">Voyage AI</a> API Token — Free usage for 200 million token without adding credit card information (Rate limiter applicable) Register/Login to <a href="https://www.voyageai.com/">Voyage.ai</a> to create an API Token</li><li>Install python packages — voyageai, pandas, PyMuPDF, boto3, pymongo, matplotlib, streamlit</li><li>MongoDB Atlas Free Tier Cluster</li></ul><p><strong>Python Imports</strong></p><pre>import os<br>import numpy as np<br>from pymongo import MongoClient<br>from pymongo.operations import SearchIndexModel<br>import boto3<br>from PIL import Image<br>from io import BytesIO<br>import base64<br>from voyageai import Client<br>import fitz  # PyMuPDF<br>from PIL import Image</pre><p><strong>Voyage Configuration</strong></p><pre>MODEL_NAME = &quot;voyage-multimodal-3&quot;<br>VOYAGE_API_KEY = &quot;YOUR PERSONAL TOKEN FROM VOYAGE WEBSITE&quot;<br>vo = Client(api_key=VOYAGE_API_KEY)<br></pre><p><strong>PDF to Screenshot Converter</strong></p><pre>def pdf_to_screenshots(pdf_path: str, zoom: float = 1.0) -&gt; list[Image]:<br>    &quot;&quot;&quot;<br>    Convert a local PDF file to a list of PIL Images.<br>    <br>    Args:<br>        pdf_path (str): Path to the local PDF file<br>        zoom (float): Zoom factor for the output images (default: 1.0)<br>    <br>    Returns:<br>        list[Image]: List of PIL Images, one for each page<br>    &quot;&quot;&quot;<br>    # Ensure the file exists and has .pdf extension<br>    if not pdf_path.endswith(&quot;.pdf&quot;):<br>        raise ValueError(&quot;File must have .pdf extension&quot;)<br><br>    # Open the PDF directly from the file path<br>    pdf = fitz.open(pdf_path)<br>    images = []<br><br>    # Loop through each page, render as pixmap, and convert to PIL Image<br>    mat = fitz.Matrix(zoom, zoom)<br>    for n in range(pdf.page_count):<br>        pix = pdf[n].get_pixmap(matrix=mat)<br><br>        # Convert pixmap to PIL Image<br>        img = Image.frombytes(&quot;RGB&quot;, [pix.width, pix.height], pix.samples)<br>        images.append(img)<br><br>    # Close the document<br>    pdf.close()<br><br>    return images<br><br>docs = pdf_to_screenshots(&quot;YOUR PDF FILE PATH WITH PDF FILE NAME&quot;)</pre><p><strong>Image to base64 converter</strong></p><pre>def im_2_b64(image):<br>    buff = BytesIO()<br>    image.save(buff, format=&quot;JPEG&quot;)<br>    img_str = base64.b64encode(buff.getvalue())<br>    return img_str</pre><p><strong>Check PDF Content</strong></p><pre>import matplotlib.pyplot as plt<br>fig, axes = plt.subplots(1, len(docs), figsize=(66, 6))<br>for n, img in enumerate(docs):<br>    axes[n].imshow(img)<br>    axes[n].axis(&quot;off&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><p><strong>Generate Vector embedding using Voyage AI model</strong></p><pre>import time<br>import numpy as np<br>from typing import List<br><br>def batch_embed_documents(docs: List[str], vo, model_name: str, batch_size: int = 5, delay: float = 1.0):<br>    &quot;&quot;&quot;<br>    Embed documents in batches with delay to avoid rate limits.<br>    <br>    Args:<br>        docs: List of documents to embed<br>        vo: Vector object for embedding<br>        model_name: Name of the model to use<br>        batch_size: Number of documents to process in each batch<br>        delay: Delay in seconds between batches<br>    <br>    Returns:<br>        numpy.ndarray: Array of document embeddings<br>    &quot;&quot;&quot;<br>    all_embeddings = []<br>    <br>    # Process documents in batches<br>    for i in range(0, len(docs), batch_size):<br>        batch = docs[i:i + batch_size]<br>        <br>        try:<br>            # Create batch input format<br>            batch_input = [[page] for page in batch]<br>            <br>            # Get embeddings for current batch<br>            batch_embeddings = vo.multimodal_embed(<br>                inputs=batch_input,<br>                model=model_name,<br>                input_type=&quot;document&quot;<br>            )<br>            print(f&quot;Number of vectors generated: {len(batch_embeddings.embeddings)}&quot;)<br>            print(f&quot;Number of text tokens ingested: {batch_embeddings.text_tokens}&quot;)<br>            print(f&quot;Number of image pixels processed: {batch_embeddings.image_pixels}&quot;)<br>            print(f&quot;Total number of tokens (texts + images): {batch_embeddings.total_tokens}&quot;)<br>            print(f&quot;Total number of dimensions (texts + images): {len(batch_embeddings.embeddings[0])}&quot;)<br>            <br>            all_embeddings.extend(batch_embeddings.embeddings)<br>            <br>            # Add delay between batches if not the last batch<br>            if i + batch_size &lt; len(docs):<br>                time.sleep(delay)<br>                <br>        except Exception as e:<br>            print(f&quot;Error processing batch {i//batch_size + 1}: {str(e)}&quot;)<br>            # Increase delay and retry on error<br>            time.sleep(delay * 2)<br>            try:<br>                batch_embeddings = vo.multimodal_embed(<br>                    inputs=batch_input,<br>                    model=model_name,<br>                    input_type=&quot;document&quot;<br>                )<br>                print(f&quot;Number of vectors generated: {len(batch_embeddings.embeddings)}&quot;)<br>                print(f&quot;Number of text tokens ingested: {batch_embeddings.text_tokens}&quot;)<br>                print(f&quot;Number of image pixels processed: {batch_embeddings.image_pixels}&quot;)<br>                print(f&quot;Total number of tokens (texts + images): {batch_embeddings.total_tokens}&quot;)<br>                print(f&quot;Total number of dimensions (texts + images): {len(batch_embeddings.embeddings[0])}&quot;)<br>                all_embeddings.extend(batch_embeddings.embeddings)<br>            except Exception as e:<br>                print(f&quot;Retry failed for batch {i//batch_size + 1}: {str(e)}&quot;)<br>                raise<br>    <br>    return np.array(all_embeddings)<br><br># Usage:<br>document_vectors = batch_embed_documents(<br>    docs=docs,<br>    vo=vo,<br>    model_name=MODEL_NAME,<br>    batch_size=3,  # Adjust based on your rate limits<br>    delay=60      # Adjust based on your rate limits<br>)</pre><p><strong>Generate metadata for each vector and base64 representation of each PDF page</strong></p><pre>documents = []<br>for n, vec in enumerate(document_vectors):<br>    doc = {&quot;page_num&quot;:n+1, &quot;embedding&quot;:vec.tolist(), &quot;base64&quot;:im_2_b64(docs[n])}<br>    documents.append(doc)</pre><p><strong>MongoDB Atlas Configuration &amp; Offline Phase Embedding generation</strong></p><pre>mclient = MongoClient(&quot;YOUR CONNECTION STRING&quot;)<br>mcollection = mclient[&quot;YOUR DB NAME&quot;][&quot;YOUR COLLECTION NAME&quot;]<br><br># load data into mongodb collection<br>mcollection.insert_many(documents)<br><br>search_index_model = SearchIndexModel(<br>  definition={<br>    &quot;fields&quot;:<br>                    [{&quot;type&quot;: &quot;vector&quot;,<br>                      &quot;path&quot;: &quot;embedding&quot;,<br>                      &quot;numDimensions&quot;: 1024,<br>                      &quot;similarity&quot;: &quot;cosine&quot;<br>                      }<br>                     ]<br>  },<br>  name=&quot;vector_search&quot;,<br>  type=&quot;vectorSearch&quot;,<br>)<br><br>try:<br>  mcollection.create_search_index(model=search_index_model)<br>except Exception as e:<br>        print(f&quot;Error creating search index: {str(e)}&quot;)<br></pre><p>Online Phase Query Embeddings &amp; Run MongoDB Atlas Vector search query</p><pre><br><br>def run_vector_search(query_vector, col, index_name, path,num_candidates=10, limit=3):<br>  results = {}<br>  pipe = [{&#39;$vectorSearch&#39;: {<br>            &quot;index&quot;:  index_name,<br>            &quot;path&quot;: path,<br>            &quot;numCandidates&quot;: num_candidates,<br>            &quot;limit&quot;: limit,<br>            &quot;queryVector&quot;: query_vector,<br>          }<br>        },<br>        {<br>            &quot;$project&quot;: {<br>                &quot;_id&quot;: 1,<br>                &quot;page_num&quot;: 1,<br>                &quot;base64&quot;:1,<br>                &quot;score&quot;: { &quot;$meta&quot;: &quot;vectorSearchScore&quot; }<br>            }<br>        }<br>      ]<br>  cursor = col.aggregate(pipe)<br>  results = list(cursor)<br>  return results<br><br>query = &quot;what is the INR Rating given by ICRA to ATGL&quot;<br><br>query_vector = np.array(<br>    vo.multimodal_embed(<br>        inputs=[[query]],<br>        model=MODEL_NAME,<br>        input_type=&quot;query&quot;<br>    ).embeddings[0]<br>)<br>qvector=query_vector.tolist()<br><br>colpali_results = run_vector_search(qvector,mcollection,&quot;vector_search&quot;,&quot;embedding&quot;)<br><br>relevant_context=[]<br>for n, data in enumerate(colpali_results):<br>    relevant_context.append({&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Image &quot;+str(n+1)+&quot; :&quot;})<br>    relevant_context.append({<br>        &quot;type&quot;: &quot;image&quot;,<br>        &quot;source&quot;: {<br>            &quot;type&quot;: &quot;base64&quot;,<br>            &quot;media_type&quot;: &#39;image/jpeg&#39;,<br>            &quot;data&quot;: data[&#39;base64&#39;].decode(&quot;utf-8&quot;),<br>            }<br>        })<br>relevant_context.append({&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: query})<br></pre><p><strong>AWS Bedrock Configuration &amp; Retrieval Augmented Generation</strong></p><pre><br>import boto3<br>import base64<br>import json<br><br># Set up the Bedrock Runtime client<br># AWS Bedrock runtime configuration<br>bedrock_runtime = boto3.client(service_name=&#39;bedrock-runtime&#39;,<br>                       region_name=&#39;ap-south-1&#39;,<br>                       aws_access_key_id=&quot;YOUR ACCESS KEY ID&quot;,<br>                       aws_secret_access_key=&quot;YOUR SECRET ACCESS KEY&quot;,<br>                       aws_session_token=&quot;YOUR SESSION TOKEN&quot;)<br>request_payload = {<br>    &quot;anthropic_version&quot;: &quot;bedrock-2023-05-31&quot;,<br>    &quot;max_tokens&quot;: 1024,<br>    &quot;messages&quot;: [<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: relevant_context<br>        }<br>    ]<br>}<br><br># Invoke the model<br>response = bedrock_runtime.invoke_model(<br>    modelId=&#39;anthropic.claude-3-sonnet-20240229-v1:0&#39;,<br>    body=json.dumps(request_payload)<br>)<br><br># Process and display the response<br>response_body = json.loads(response[&#39;body&#39;].read())<br>print(response_body[&#39;content&#39;][0][&#39;text&#39;])</pre><blockquote><strong>RESPONSE GENERATED</strong></blockquote><blockquote><strong><em>According to the domestic credit ratings table shown in Image 1, the INR Rating given by ICRA (India Ratings and Credit Analysis) to ATGL (Adani Total Gas Limited) is AA-/Stable.</em></strong></blockquote><h3><strong>Conclusion</strong></h3><p>In this article, we saw <strong>VoyageAI’</strong>s latest multi modal embedding model (voyage-multimodal-3) can be leveraged for generating vector embeddings for complex PDF’s with interleaving text, table and images at page level, store it in <strong>MongoDB Atlas </strong>and then query the content of the pdf in natural language. AWS bedrock hosted <strong><em>anthropic.claude-3-sonnet-20240229-v1:0 </em></strong>is used as the Generative Vision Language Model. This approach improves retrievals relevance and hence generations accuracy when it comes to building RAG Solutions. Further optimisation can be achieved using Vector Quantisation supported on MongoDB Atlas. An Article can be found <a href="https://medium.com/@vinod.krishnan13/breaking-rag-quantisation-with-openai-and-mongodb-atlas-f908f3c3ee57">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c703a9061a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking RAG — Quantisation with OpenAI and MongoDB Atlas]]></title>
            <link>https://medium.com/@vinod.krishnan13/breaking-rag-quantisation-with-openai-and-mongodb-atlas-f908f3c3ee57?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/f908f3c3ee57</guid>
            <category><![CDATA[int8-quantization]]></category>
            <category><![CDATA[scalar-quantization]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 13:12:28 GMT</pubDate>
            <atom:updated>2024-11-03T23:51:36.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>Breaking RAG — Quantization with OpenAI and MongoDB Atlas</h3><p>Building a Cost-Efficient PDF Vector Search with Embedding Quantization and MongoDB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bg1NMXPngO03q261tVOVQ.png" /><figcaption><em>Source: </em><a href="https://huggingface.co/blog/embedding-quantization">https://huggingface.co/blog/embedding-quantization</a></figcaption></figure><h3>Introduction</h3><p>As data-driven applications grow in complexity and scale, so do the costs associated with data storage and search. Embedding-based vector search provides a powerful solution for finding similar content, but high-dimensional float32 embeddings can quickly become storage/RAM intensive proposition. In this article we will demonstrate a cost-saving innovation: <strong>quantizing embeddings from float32 to int8</strong> to reduce storage and memory requirements with minimal impact on search accuracy. Using OpenAI embeddings and MongoDB Atlas, we build a scalable, efficient PDF vector search pipeline that balances accuracy and cost-effectiveness.</p><h3>Pre-requisite</h3><ul><li>MongoDB Atlas Free Tier Cluster — Register <a href="http://cloud.mongodb.com/">here</a></li></ul><h3>Overview</h3><ul><li>All library imports</li><li>MongoDB Atlas connection setup</li><li>PDF Chunking</li><li>Embedding Generation &amp; Embedding Quantization</li><li>Persist with MongoDB Atlas</li><li>Create Atlas Vector search Index</li><li>Run Vectorsearch pipeline</li></ul><h3>All Library imports</h3><pre>import pandas as pd<br>from bson.binary import BinaryVectorDtype, Binary<br>from pymongo.operations import SearchIndexModel<br>from pymongo import MongoClient<br>from langchain_openai import OpenAIEmbeddings, OpenAI, ChatOpenAI<br>from langchain_core.documents import Document<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>import pdfplumber<br>import tqdm</pre><h3>MongoDB Atlas Connection</h3><pre>mclient = MongoClient(&quot;YOUR MONGODB ATLAS CONNECTION STRING&quot;)<br>mcollection = mclient[&quot;YOUR DB NAME&quot;][&quot;YOUR COLLECTION NAME&quot;]</pre><h3>PDF Chunking</h3><p>We will be using this article <a href="https://arxiv.org/abs/2410.20253"><strong>Application of an ANN and LSTM-based Ensemble Model for Stock Market Prediction</strong></a> as our PDF source. This PDF will be chunked using Recursive character text splitting.</p><pre>def orchestrateRAG(uploaded_file):<br>    file_name = uploaded_file<br>    if mcollection.find_one({&quot;file_name&quot;:file_name}):<br>            print(&quot;Chunks already loaded&quot;)<br>            return file_name<br>    else:<br>        ## Open the PDF with pdfplumber<br>        with pdfplumber.open(uploaded_file) as pdf:<br>            # Extract the title from the PDF metadata<br>            pdf_metadata = pdf.metadata<br>            #pdf_title = pdf_metadata.get(&#39;Title&#39;, &#39;Untitled Document&#39;)<br>            documents = []<br>            # Iterate through each page in the PDF<br>            for i, page in enumerate(pdf.pages):<br>                text = page.extract_text()<br>                metadata = {<br>                    &quot;page_number&quot;: i + 1,<br>                    &quot;file_name&quot;: file_name<br>                }<br>                # Create a Document object with metadata<br>                document = Document(page_content=text, metadata=metadata)<br>                documents.append(document)<br>        chunks = splitter.split_documents(documents)<br>        return chunks<br><br>chunks = orchestrateRAG(&quot;YOUR PDF FILE PATH WITH FILE NAME&quot;)</pre><h3>Embedding Generation &amp; Embedding Quantization</h3><p>Embedding is being generated by using OpenAI’s <strong>text-embedding-3-small</strong> model, The embedding generated is a 1536 dimension float32 vector. This vector is then quantized to a 1536 dimension int8 vector. This quantized vector is then converted into a binData Vector type.</p><p>MongoDB Atlas supports a new binData vector type — With this new dedicated BSON vector type, we can reduce the Database Storage requirements by up to 66%.</p><pre># Quantize a float32 vector to int8<br>def fp32_to_int8(fp32_vector):<br>    # Step 1: Normalize the float32 vector to the range -128 to 127<br>    # First, find the max absolute value in the float vector to scale within -128 to 127<br>    max_val = np.max(np.abs(fp32_vector))<br>    normalized_vector = (fp32_vector / max_val) * 127<br>    # Step 2: Convert to int8<br>    int8_vector = normalized_vector.astype(np.int8)<br>    return int8_vector<br><br># MongoDB BinData Vector creation<br>def generate_bson_vector_with_pymongo(vector, data_type: BinaryVectorDtype):<br>  return Binary.from_vector(vector, data_type)<br><br>def get_embedding(text, model=&quot;text-embedding-3-small&quot;):<br>   text = text.replace(&quot;\n&quot;, &quot; &quot;)<br>   return openai.embeddings.create(input = [text], model=model).data[0].embedding<br><br>client = OpenAI()<br><br>for chunk in tqdm(chunks):<br>    chunk.metadata.update({&quot;fp32&quot;: client.embeddings.create(<br>        model=&quot;text-embedding-3-small&quot;,<br>        input=chunk.page_content<br>        ).data[0].embedding})<br>    chunk.metadata.update({&quot;int8&quot;: fp32_to_int8(chunk.metadata[&#39;fp32&#39;])})<br><br>docs = []<br>for chunk in chunks:<br>    doc = {&quot;content&quot;:chunk.page_content, <br>           &quot;page_number&quot;:chunk.metadata[&quot;page_number&quot;],<br>           &quot;file_name&quot;:chunk.metadata[&quot;file_name&quot;],<br>           &quot;int8&quot;:generate_bson_vector_with_pymongo(chunk.metadata[&quot;int8&quot;],BinaryVectorDtype.INT8),<br>           &quot;fp32&quot;:chunk.metadata[&quot;fp32&quot;]}<br>    docs.append(doc)</pre><h3>Persist with MongoDB Atlas</h3><p>We persisted the data in MongoDB Atlas</p><pre>mcollection.insert_many(docs)</pre><h3>Create Atlas Vector search Index</h3><p>We create 2 vector search index here for comparison w.r.t results and storage efficiency</p><ul><li>float 32 Atlas Vector search index</li><li>int8 Atlas Vector search index</li></ul><pre>search_index_model_int8 = SearchIndexModel(<br>  definition={<br>    &quot;fields&quot;:<br>                    [{&quot;type&quot;: &quot;vector&quot;,<br>                      &quot;path&quot;: &quot;int8&quot;,<br>                      &quot;numDimensions&quot;: 1536,<br>                      &quot;similarity&quot;: &quot;cosine&quot;<br>                      }<br>                     ]<br>  },<br>  name=&quot;binDataIndex&quot;,<br>  type=&quot;vectorSearch&quot;,<br>)<br><br>result = mcollection.create_search_index(model=search_index_model_int8)<br>print(result)<br><br>search_index_model_fp32 = SearchIndexModel(<br>  definition={<br>    &quot;fields&quot;:<br>                    [{&quot;type&quot;: &quot;vector&quot;,<br>                      &quot;path&quot;: &quot;fp32&quot;,<br>                      &quot;numDimensions&quot;: 1536,<br>                      &quot;similarity&quot;: &quot;cosine&quot;<br>                      }<br>                     ]<br>  },<br>  name=&quot;default&quot;,<br>  type=&quot;vectorSearch&quot;,<br>)<br><br>result = mcollection.create_search_index(model=search_index_model_fp32)<br>print(result)</pre><h3>Run Vector-search pipeline</h3><p>We ran a vector search query with same query against both Float32 and int8 Atlas vector search index</p><pre>def run_vector_search(query_vector, col, index_name, path,num_candidates=10, limit=10,):<br><br>  results = {}<br>  pipe = [{&#39;$vectorSearch&#39;: {<br>            &quot;index&quot;:  index_name,<br>            &quot;path&quot;: path,<br>            &quot;numCandidates&quot;: num_candidates,<br>            &quot;limit&quot;: limit,<br>            &quot;queryVector&quot;: query_vector,<br>          }<br>        },<br>        {<br>            &quot;$project&quot;: {<br>                &quot;_id&quot;: 1,<br>                &quot;content&quot;: 1,<br>                &quot;score&quot;: { &quot;$meta&quot;: &quot;vectorSearchScore&quot; }<br>            }<br>        }<br>      ]<br>  cursor = col.aggregate(pipe)<br>  results = list(cursor)<br>  return results<br><br>query = &quot;What was the dataset used as training source&quot;<br>query_fp32 = client.embeddings.create(<br>        model=&quot;text-embedding-3-small&quot;,<br>        input=query<br>        ).data[0].embedding<br>query_int8 = generate_bson_vector_with_pymongo(fp32_to_int8(query_fp32),BinaryVectorDtype.INT8)<br><br>fp32_results = run_vector_search(query_fp32,mcollection,&quot;default&quot;,&quot;fp32&quot;)<br><br>int8_results = run_vector_search(query_int8,mcollection,&quot;binDataIndex&quot;,&quot;int8&quot;)</pre><h4>Result Accuracy</h4><p>We observed the for the same query, vector search yielded same set of documents against both float32 and int8 Atlas vector search index.</p><p><strong>Float32 Vector-search Results</strong></p><pre>pd.DataFrame(fp32_results, columns=[&#39;_id&#39;, &#39;content&#39;, &#39;score&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ybj4WYRn9LJTmguBrRMOBg.png" /></figure><p><strong>Int8 Vector-search Results</strong></p><pre>pd.DataFrame(int8_results, columns=[&#39;_id&#39;, &#39;content&#39;, &#39;score&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL9oc4R8TRk_FBnKAbRSXQ.png" /></figure><p><strong>Storage/RAM Requirements</strong></p><p>We saw Storage/RAM requirements going down by ~ 74 percent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7y-WdxGWufYOUMfD5agFIg.png" /></figure><h3>Conclusion</h3><p>This article presents a scalable solution to embedding-based search challenges by leveraging quantization. By transforming float32 embeddings to int8, we effectively balance accuracy and cost, enabling affordable large-scale deployment without a significant compromise on search quality. Quantized embeddings hold exciting potential for resource-conscious applications across industries, from document search engines to recommendation systems and beyond.</p><p>Through this approach, we not only reduce costs but also open the door to sustainable, high-performance data architectures for embedding-based applications.</p><p>MongoDB Atlas is also planning to come up with Automatic Quantization. Quantization as of now is supported natively by a few AI providers such as Cohere. Some more reads <a href="https://www.mongodb.com/blog/post/vector-quantization-scale-search-generative-ai-applications">here</a> and <a href="https://www.mongodb.com/developer/products/atlas/ingesting_quantized_vectors_with_cohere/">here</a> for benchmarks and tutorials.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f908f3c3ee57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Travelmate — RAG Chat with MongoDb Atlas Collection]]></title>
            <link>https://medium.com/@vinod.krishnan13/travelmate-rag-chat-with-mongodb-atlas-collection-8e7636207921?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7636207921</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[pre-filters]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 04:54:17 GMT</pubDate>
            <atom:updated>2024-08-17T05:30:22.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>Travelmate — RAG Chat with MongoDb Atlas Collection</h3><h3><strong>Introduction</strong></h3><p>In this article, we will be building a chatbot called <strong>Travelmate </strong>which makes accommodation suggestions based on user inputs on description of their desired vacation stay. We will be leveraging <strong><em>Atlas’s vector search index </em></strong>as vector store along with <strong><em>Open AI’s </em></strong>LLM capabilities and <strong><em>langchain framework</em></strong> for AI orchestration. We will use <strong>streamlit</strong> library to build the <strong>UI</strong> for <strong>Travelmate</strong>.</p><p>Codebase can be found <a href="https://github.com/vinodkrishnan23/RAGMusings/tree/travelmate">here</a>.</p><h3><strong>Architecture Diagram</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*soAyQ_yXTV4wRvlSsbm46w.png" /></figure><p>We will be using <a href="https://huggingface.co/datasets/MongoDB/airbnb_embeddings">MongoDB/airbnb_embeddings</a> dataset, This dataset already contains the vector embeddings generated for description field by OpenAI’s <strong><em>text-embedding-3-small</em></strong> embedding model.</p><p><strong>Pre-requisites</strong> —</p><ul><li>Mongodb Atlas Account and a Free Tier M0 Cluster</li><li>Open AI API Key</li><li>Install requirements using files for <a href="https://github.com/vinodkrishnan23/RAGMusings/blob/travelmate/travelmate/requirements.txt">python virtual environment</a> or <a href="https://github.com/vinodkrishnan23/RAGMusings/blob/travelmate/travelmate/conda-spec-file.txt">conda environment </a>as applicable</li><li>Data ingested from <a href="https://huggingface.co/datasets/MongoDB/airbnb_embeddings">MongoDB/airbnb_embeddings</a> using the script <a href="https://github.com/vinodkrishnan23/RAGMusings/blob/travelmate/travelmate/prep_data/ingest_dataset.py">here</a> (which will also create a atlas vector search index)</li></ul><p>Once the data is ingested a sample document will look as below in Atlas MongoDB collection</p><pre>{<br>  &quot;_id&quot;: {<br>    &quot;$oid&quot;: &quot;66bc9aea74fa354fdf54026e&quot;<br>  },<br>  &quot;listing_url&quot;: &quot;https://www.airbnb.com/rooms/29761068&quot;,<br>  &quot;name&quot;: &quot;House  River,Garden &amp;Sunset&quot;,<br>  &quot;summary&quot;: &quot;A Casa fica 2 minutos do rio Douro junto ao jardim do Calem.&quot;,<br>  &quot;space&quot;: &quot;A Casa  restaurada junto do rio douro e Foz Velha.&quot;,<br>  &quot;description&quot;: &quot;A Casa fica 2 minutos do rio Douro junto ao jardim do Calem. A Casa  restaurada junto do rio douro e Foz Velha. os hospedes tem a casa inteira para desfrutar da vista fantástica do Rio douro e os jardins que circundam a área. Lugar calmo,com belos restaurantes, mercearias cafés,explanadas. A casa esta situada a 5 minutos do jardim do Calem, e do rio Douro. tem o eléctrico e paragens de autocarros públicos,autocarros Turísticos. Nas redondezas encontra comercio tradicional,Supermercados,cafés,restaurantes especializados em peixe e pratos tradicionais. Na Marginal junto a Casa tem transportes públicos Autocarro e Eléctrico, A 15 minutos da Foz do Douro,  praias onde pode-se ver o por do sol único&quot;,<br>  &quot;neighborhood_overview&quot;: &quot;&quot;,<br>  &quot;notes&quot;: &quot;A 15 minutos da Foz do Douro,  praias onde pode-se ver o por do sol único&quot;,<br>  &quot;transit&quot;: &quot;Na Marginal junto a Casa tem transportes públicos Autocarro e Eléctrico,&quot;,<br>  &quot;access&quot;: &quot;os hospedes tem a casa inteira para desfrutar da vista fantástica do Rio douro e os jardins que circundam a área. Lugar calmo,com belos restaurantes, mercearias cafés,explanadas.&quot;,<br>  &quot;interaction&quot;: &quot;A casa esta situada a 5 minutos do jardim do Calem, e do rio Douro. tem o eléctrico e paragens de autocarros públicos,autocarros Turísticos. Nas redondezas encontra comercio tradicional,Supermercados,cafés,restaurantes especializados em peixe e pratos tradicionais.&quot;,<br>  &quot;house_rules&quot;: &quot;&quot;,<br>  &quot;property_type&quot;: &quot;House&quot;,<br>  &quot;room_type&quot;: &quot;Entire home/apt&quot;,<br>  &quot;bed_type&quot;: &quot;Real Bed&quot;,<br>  &quot;minimum_nights&quot;: 2,<br>  &quot;maximum_nights&quot;: 31,<br>  &quot;cancellation_policy&quot;: &quot;flexible&quot;,<br>  &quot;accommodates&quot;: 4,<br>  &quot;bedrooms&quot;: 1,<br>  &quot;beds&quot;: 1,<br>  &quot;number_of_reviews&quot;: 2,<br>  &quot;bathrooms&quot;: 1,<br>  &quot;amenities&quot;: [<br>    &quot;TV&quot;,<br>    &quot;Wifi&quot;,<br>    &quot;Kitchen&quot;,<br>    &quot;Free parking on premises&quot;,<br>    &quot;Heating&quot;,<br>    &quot;Smoke detector&quot;,<br>    &quot;First aid kit&quot;,<br>    &quot;Safety card&quot;,<br>    &quot;Wide hallway clearance&quot;,<br>    &quot;Step-free access&quot;,<br>    &quot;Wide doorway&quot;,<br>    &quot;Flat path to front door&quot;,<br>    &quot;Well-lit path to entrance&quot;,<br>    &quot;Disabled parking spot&quot;,<br>    &quot;Beachfront&quot;<br>  ],<br>  &quot;price&quot;: 52,<br>  &quot;security_deposit&quot;: 0,<br>  &quot;host&quot;: {<br>    &quot;host_id&quot;: &quot;223714881&quot;,<br>    &quot;host_url&quot;: &quot;https://www.airbnb.com/users/show/223714881&quot;,<br>    &quot;host_name&quot;: &quot;House River Garden &amp; Sunset&quot;,<br>    &quot;host_has_profile_pic&quot;: true,<br>    &quot;host_identity_verified&quot;: false<br>  },<br>  &quot;address&quot;: {<br>    &quot;street&quot;: &quot;Porto, Porto, Portugal&quot;,<br>    &quot;government_area&quot;: &quot;Lordelo do Ouro e Massarelos&quot;,<br>    &quot;market&quot;: &quot;Porto&quot;,<br>    &quot;country&quot;: &quot;Portugal&quot;,<br>    &quot;country_code&quot;: &quot;PT&quot;,<br>    &quot;location&quot;: {<br>      &quot;type&quot;: &quot;Point&quot;,<br>      &quot;coordinates&quot;: [<br>        -8.65229,<br>        41.1501<br>      ],<br>      &quot;is_location_exact&quot;: true<br>    }<br>  },<br>  &quot;availability&quot;: {<br>    &quot;availability_30&quot;: 30,<br>    &quot;availability_60&quot;: 60,<br>    &quot;availability_90&quot;: 90,<br>    &quot;availability_365&quot;: 362<br>  },<br>  &quot;review_scores&quot;: {<br>    &quot;review_scores_accuracy&quot;: 10,<br>    &quot;review_scores_cleanliness&quot;: 10,<br>    &quot;review_scores_checkin&quot;: 10,<br>    &quot;review_scores_communication&quot;: 10,<br>    &quot;review_scores_location&quot;: 10,<br>    &quot;review_scores_value&quot;: 10,<br>    &quot;review_scores_rating&quot;: 100<br>  },<br>  &quot;text_embeddings&quot;: [<br>    0.0018826715,<br>    -0.0071269087,<br>    0.0086836396,...............more<br>    0.0141370622,<br>    ]<br>}</pre><p>Python library Imports to run the travelmate application</p><pre># For the UI and system variables<br>import streamlit as st<br>import os<br># For mongodb connection object and vector search index creation<br>from pymongo import MongoClient<br>from pymongo.operations import SearchIndexModel<br># All langchain imports for openAI, Retrievers, Mongodb Vector store, prompts .<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_openai import OpenAIEmbeddings, OpenAI, ChatOpenAI<br>from datasets import load_dataset<br>import pandas as pd<br>from langchain_openai import OpenAIEmbeddings, OpenAI, ChatOpenAI<br>from langchain.retrievers.self_query.base import SelfQueryRetriever<br>from langchain.chains.query_constructor.base import AttributeInfo<br>from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch<br>from langchain_core.documents import Document<br>from langchain_core.prompts import PromptTemplate<br>from langchain.chains.combine_documents import create_stuff_documents_chain</pre><h3><strong>Retrieval</strong></h3><p>Retrieval means fetching relevant documents from any vector store — MongoDB Atlas vector-store is being used here. Here we are using Langchain’s SelfQueryRetriever which gives an in-built functionality to leverage pre-filters configured on the vector search index while querying the MongoDB Atlas vector store.</p><p>The script being discussed in this article can be found <a href="https://github.com/vinodkrishnan23/RAGMusings/blob/travelmate/travelmate/rag_travelmate.py">here</a> and be reffered to fill the missing gaps/variables</p><p>Search Index Definition created by script <a href="https://github.com/vinodkrishnan23/RAGMusings/blob/travelmate/travelmate/prep_data/ingest_dataset.py">here</a>. This search index will be configured for 3 pre-filters</p><ul><li>bedrooms — count of bedrooms in stay</li><li>bathrooms — count of bathrooms in stay</li><li>security_deposit — Deposit for the stay</li></ul><pre>from pymongo import MongoClient<br>from pymongo.operations import SearchIndexModel<br><br>MONGODB_ATLAS_CLUSTER_URI = &#39;YOUR MONGODB ATLAS CONNECTION STRING&#39;<br><br>client = MongoClient(MONGODB_ATLAS_CLUSTER_URI)<br><br>MDB_NAME = &#39;YOUR DATABASE NAME&#39;<br><br>COLLECTION_NAME = &#39;YOUR COLLECTION NAME&#39;<br><br>ATLAS_VECTOR_SEARCH_INDEX_NAME=&#39;NAME YOUR INDEX HERE&#39;<br><br>search_index_model = SearchIndexModel(<br>  definition={<br>    &quot;fields&quot;: [<br>      {<br>        &quot;type&quot;: &quot;vector&quot;,<br>        &quot;numDimensions&quot;: 1536,<br>        &quot;path&quot;: &quot;text_embeddings&quot;,<br>        &quot;similarity&quot;: &quot;cosine&quot;<br>      },<br>      # Pre filters are configured as below<br>      {<br>        &quot;type&quot;: &quot;filter&quot;,<br>        &quot;path&quot;: &quot;bathrooms&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;filter&quot;,<br>        &quot;path&quot;: &quot;bedrooms&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;filter&quot;,<br>        &quot;path&quot;: &quot;security_deposit&quot;<br>      }<br>    ]<br>  },<br>  name=ATLAS_VECTOR_SEARCH_INDEX_NAME,<br>  type=&quot;vectorSearch&quot;,<br>)<br><br>try:<br>    result = collection.create_search_index(model=search_index_model)<br>except Exception as e:<br>    print(&quot;Vector search Index Exists&quot;)</pre><p>Create MongoDB Atlas vector-store object</p><pre>from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch<br><br># mcollection is collection object in mongodb terms<br># embeddings is the Open AI&#39;s text-embedding-3-small embedding model<br># text_embeddings is the field in mongodb collection which has vector embeddings<br># description is the field in mongodb collection whose embeddings are text_embeddings<br><br># ATLAS_VECTOR_SEARCH_INDEX_NAME is name of vector search index created <br># as part of data ingestion as per configuration provided by you <br># in /prep_data/.env<br><br><br>vectorstore = MongoDBAtlasVectorSearch(<br>  collection=mcollection,<br>  embedding=embeddings,<br>  embedding_key=&#39;text_embeddings&#39;,<br>  text_key=&#39;description&#39;,<br>  index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,<br>  relevance_score_fn=&quot;cosine&quot;,<br>)</pre><p>Create a SelfQueryRetriever object</p><pre>from langchain.retrievers.self_query.base import SelfQueryRetriever<br>#llm is OpenAI&#39;s gpt-3.5-turbo <br># <br># Pre filter fields configured in index need a one liner description about them<br># This will be leveraged by SelfQueryRetriever to modify vector search query<br># to add the pre-filter construct accurately<br><br>metadata_field_info = [<br>    AttributeInfo(<br>        name=&quot;bathrooms&quot;,<br>        description=&quot;Number of bathrooms in any accomodation or hotel or stay&quot;,<br>        type=&quot;integer or double&quot;,<br>    ),<br>    AttributeInfo(<br>        name=&quot;bedrooms&quot;,<br>        description=&quot;Number of bathrooms in any accomodation or hotel or stay&quot;,<br>        type=&quot;integer or double&quot;,<br>    ),<br>    AttributeInfo(<br>        name=&quot;security_deposit&quot;,<br>        description=&quot;It also known as security deposit, It is the Amount of security deposit in any accomodation or hotel or stay&quot;,<br>        type=&quot;integer or double&quot;,<br>    )<br>]<br># Description of data stored in your collection<br>document_content_description = &quot;Brief description of accomodation or hotel or stay&quot;<br><br><br>retriever = SelfQueryRetriever.from_llm(<br>    llm,<br>    vectorstore,<br>    document_content_description,<br>    metadata_field_info,<br>    verbose=True<br>)</pre><p>Calling the Retriever with user prompt</p><pre>from langchain_core.documents import Document<br><br># prompt = &quot;&lt;Input captured by the streamlit interface from end user&gt;&quot;<br>prompt = &quot;&quot;&quot;Give me few quaint riverside accommodation options with 2 bedrooms <br>            and has 0 security deposit&quot;&quot;&quot;<br>relevant_docs=retriever.invoke(prompt)<br># prints Output<br>for doc in relevant_docs:<br>    print(doc)</pre><p>Output from MongoDB AtlasVectorstore</p><pre>page_content=&#39;★ Mar 2-17 and Apr 8-11 are discounted to $454/night (vs our standard $632/nt). The discount applies automatically. ★ Located directly on the sand, our home is big, modern and maintained with great attention to detail. Beachside lanai, hammock, BBQ, kayaks &amp; an array of beach gear ensures maximum beach/ocean fun. Two grocery stores are located less than five minutes away. Beds: Cal King (1), Queen (1), Twins (2), Sleeper Sofas (2). NOTE: upon request, the two twins are convertible into a king. Sitting directly on a small skiff of sandy beach, our place offers ocean views as far as the eye can see. But the beachfront location is just one of the many desirable features. The place - fully remodeled in 2016 - offers 2 stories and over 1,900 sq. ft. of comfortable, modern, and elegant living space with a tasteful Hawaiian décor. Upstairs features vaulted ceilings, two bedrooms, two full baths, big great room, gourmet kitchen, dining room, and two large ocean-facing lanais. Downstairs featur&#39; metadata={&#39;source&#39;: &#39;https://www.airbnb.com/rooms/229954&#39;, &#39;bathrooms&#39;: 3.0, &#39;bedrooms&#39;: 3.0, &#39;security_deposit&#39;: 500.0}<br>page_content=&#39;Close to Lapa and the famous stairs of the Selaron with 360º view 1st floor-2 bedrooms, 2 bathrooms, kitchen and dining and living room.  2nd floor-suite, a large lounge with 2 sofa beds and a balcony.  terrace  It`s possible to rent only the 1st    360&#39; metadata={&#39;source&#39;: &#39;https://www.airbnb.com/rooms/3090578&#39;, &#39;bathrooms&#39;: 3.0, &#39;bedrooms&#39;: 3.0, &#39;security_deposit&#39;: None}<br>page_content=&#39;Get away from the hustle of Waikiki. Relax at this beautiful Hawaiian home on the marina. This home is set along Oahu’s beautiful Hawaii Kai Marina, in a safe and quiet neighborhood. ADDITIONAL FEATURES &amp; AMENITIES -Hammock -Jetted Bath Tub -Kayaks &amp; Stand up Paddle board -BBQ Grill -24/7 Local resident insight Points of Interest: -10 minutes drive to Hanauma Bay -20 minutes drive to Diamond Head Beach Access: -On property marina access leading to the ocean -15 minutes drive to Waikiki Beach Create gourmet feasts in our fully-equipped kitchen. Nod off to the soothing sounds of the ocean every night in any of the three air-conditioned bedrooms. The Master suite features entry onto the beautiful terrace overlooking the marina and an attached bathroom. Our second Master suite features mountain views and an attached bathroom. Our guest bedroom has a queen bed with a detached bathroom. There are two living rooms, each with large flat screen TVs and comfortable sofas that convert into full-s&#39; metadata={&#39;source&#39;: &#39;https://www.airbnb.com/rooms/28037210&#39;, &#39;bathrooms&#39;: 3.0, &#39;bedrooms&#39;: 3.0, &#39;security_deposit&#39;: 299.0}<br>page_content=&#39;This custom designed home by Hawaii’s renowned architect Mark Eyler is located on the idyllic northshore of Kauai. HAWAII STATE TAX WILL BE ADDED TO THE DAY RATE and sent to you in a special offer Designed for professional surfer Bruce Irons, the architecture and interior design blends Balinese, Hawaiian and Asian elements with a contemporary style. This home offers a standard of unparalleled beauty combined with elegance in a modern tropical setting.  LAULE&#39;A HALE, which means peaceful and happy in Hawaiian, is the perfect description for this home. In classic tropical design, each living space opens up to bring the outdoors in accentuating the awesome mountain, waterfall and ocean views and allowing the cooling trade winds to soothe you.  With almost 4,000 square feet of living space, this home features 3 bedrooms, 3 and a half baths with spa-like amenities such as steam room, jacuzzi, infinity pool, yoga/meditation room and expansive outdoor living areas. These are just some of the &#39; metadata={&#39;source&#39;: &#39;https://www.airbnb.com/rooms/5640127&#39;, &#39;bathrooms&#39;: 3.0, &#39;bedrooms&#39;: 3.0, &#39;security_deposit&#39;: 5000.0}</pre><h3>Augmented Generation</h3><p>Invoking LLM with prompt and context (relevant docs from vectorstore ).</p><pre>from langchain_core.prompts import PromptTemplate<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br><br># Massaging the retrieved documents to minimise context sent to llm <br># and in proper format for LLM to understand<br>refined_documents=[]<br>            for doc in relevant_docs:<br>                document = Document(page_content=doc.page_content, metadata={&quot;source&quot;: doc.metadata[&quot;listing_url&quot;], &quot;bathrooms&quot;: doc.metadata[&quot;bathrooms&quot;], &quot;bedrooms&quot;: doc.metadata[&quot;bedrooms&quot;], &quot;security_deposit&quot;: doc.metadata[&quot;security_deposit&quot;]})<br>                refined_documents.append(document)<br><br># A God Prompt for Travel Assistant LLM<br>prompt = PromptTemplate(<br>            input_variables = [&quot;query&quot;,&quot;context&quot;],<br>            template=&quot;&quot;&quot;You are a friendly travel assistant and <br>                        you suggest travellers accomodations in a <br>                        cheerful manner Answer the question from a <br>                        traveller:{query} by searching the following <br>                        :{context} and provide the best accomodation based <br>                        on the requirements. Format in a readable fashion, <br>                        if you don&#39;t get any information from context <br>                        then apologise and ONLY say you dont know, <br>                        Don&#39;t hallucinate based on own knowledge&quot;&quot;&quot;)<br><br>document_chain = create_stuff_documents_chain(llm, prompt)<br><br>print(document_chain.stream({&quot;query&quot;:prompt, &quot;context&quot;:refined_documents}))<br></pre><p>Output from LLM</p><pre>Based on your requirements, I would suggest checking out the following accomodations:<br><br>A beachfront home located directly on the sand, with modern amenities and beach gear provided. It also offers a discount for certain dates and has a beautiful ocean view.<br><br>A peaceful and happy home on the northshore of Kauai, designed by a renowned architect and featuring Balinese, Hawaiian, and Asian elements. It has a spa-like atmosphere with a steam room, jacuzzi, and infinity pool.<br><br>I hope these options meet your needs and provide you with a comfortable and enjoyable stay. If not, I apologize and unfortunately, I don&#39;t have any other information to offer at this time. Is there anything else I can assist you with?</pre><h3>Streamlit Application</h3><p>Streamlit application is built with 2 streamlit column objects named as</p><ul><li>Chat Container — which will hold the chat between user and assistant</li><li>Chunk Container — shows Chunk Information or Documents returned by vector store, which was used by LLM to construct the answer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DyFXGvjOV0Bqu9GpaeiSA.png" /></figure><h3>Summary</h3><p>In this article, we used</p><ul><li>OpenAI GPT 3.5 Turbo as LLM; as embedding model</li><li>MongoDB Atlas vector search index — with pre-filters</li><li>Self Query Retriever for retrieving relevant context from Atlas vector search index leveraging pre-filters which appear in User’s Prompt</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7636207921" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vectors for dummies — HNSW]]></title>
            <link>https://medium.com/@vinod.krishnan13/vectors-for-dummies-hnsw-d05bcb7ac867?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/d05bcb7ac867</guid>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[k-nearest-neighbours]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[small-world-network]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 02:08:27 GMT</pubDate>
            <atom:updated>2024-07-22T02:10:57.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vectors for dummies — HNSW</h3><p><strong>What is HNSW and why is it relevant now</strong></p><p>In the <a href="https://medium.com/@vinod.krishnan13/vectors-for-dummies-part-1-29ce30182fec">previous article</a>, we understood how unstructured data such as text/video/images can be represented as <strong>Vector Embeddings</strong> using the powerful embedding models (neural networks).</p><p>We discussed how <strong>MongoDB Atlas</strong> helps us store vector embeddings (double array) right besides our main data in collection. Atlas also lets us create a special type of index called <strong>vector search index</strong> in order to surf through the vector embeddings and return relevant results with low latency.</p><p>In this article, we will dig deeper to understand HNSW better. We will be referring to <a href="https://arxiv.org/abs/1603.09320">Hierarchical Navigable Small World white paper</a> .</p><p>Let’s assume we have a dataset which consists of a million documents/rows, One of the fields in these document/row is the vector embedding (<strong>embedding</strong> in below image) for that data point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7UoBH3CpEjKzlORxBMnRA.png" /></figure><p>We understand vector embedding represents a contextual location of a given document in an n-dimensional space. The aim here is to find vectors/documents which are closer to our query vector; In essence we need to calculate the distance between the query vector and all document vector embeddings within our dataset.</p><p>Lets try it old fashioned brute way, we do the distance calculation for our query vector against each document’s vector embedding</p><p><strong>Enter Naive K-Nearest Neighbour Algorithm</strong></p><p>In this algorithm, we do not need to create any data structure, during the search we end up calculating the distance metric for all vector embeddings in a dataset, The time complexity here becomes O(n). This will not give us the performance that we expect in large scale datasets or high dimensional dataset.</p><p>For simplicity sakes, Let’s assume we have 5 datapoints in 2D space as below</p><p>A (0, 0)<br>B (1, 0)<br>C (0, 1)<br>D (1, 1)<br>E (0.5, 0.5)</p><p>Given Query — Q (0.2,0.2), calculate distance against all vectors in the dataset,</p><p>Note -We are using euclidean distance calculations</p><ul><li>Distance to A (0, 0): ≈0.283</li><li>Distance to B (1, 0): ≈0.824</li><li>Distance to C (0, 1): ≈0.824</li><li>Distance to D (1, 1): ≈1.131</li><li>Distance to E (0.5, 0.5): ≈0.424</li></ul><p>Get top K nearest datapoints as results</p><ul><li>If k = 2 ; results = A, E</li><li>If k=3 ; results = A, E, B</li></ul><p><strong>Drawbacks for Naive K-Nearest Neighbour Algorithm</strong></p><ul><li>“Brute force”, exact search queries run in O(n*d) time</li><li>Time Complexity for search is O(n * d); n — number of vectors/data-points ; d — dimension of vectors</li><li>Does not scale well for large numbers of vectors, or in high-dimensional vector spaces</li></ul><p>Naive K-NN approach doesn’t scale well with huge dataset/high dimensional dataset owing to time complexity of <strong>O(n * d)</strong></p><blockquote><strong>Problem Statement</strong></blockquote><blockquote>“Search through high dimensional or large dataset to find relevant results and with low latency”</blockquote><blockquote><strong>Solution</strong></blockquote><blockquote>We need a special data structure here to search through high dimensional or large dataset in a <strong>selective/efficient yet meaningful manner</strong> and return <strong>relevant results</strong> <strong>quickly</strong></blockquote><p>In this article, We will be time travelling through various DS driven approaches and understanding how we got to <strong>Hierarchical Navigable Small World (HNSW)</strong> data structure</p><p>We will be covering</p><ul><li>K-nn graph</li><li>Navigable Small World graph</li><li>Hierarchical Navigable Small World (HNSW) graph</li></ul><blockquote>Let the data structure games begin</blockquote><p><strong>K-nn graph</strong></p><p>Its a union between Naive K — nearest neighbour algorithm and proximity graphs. A proximity graphs is made of</p><ul><li>Nodes — represent entities/data-points in graph data structure</li><li>Edges — represents relationship/notion of proximity between entities/data-points in a graph data structure</li></ul><p><strong>K-nn graph Construction Illustration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gdstcjs8PeQ5m0Eh" /></figure><p><strong>K-nn graph Search</strong></p><p>Search commences from a low degree random node the graph data structure and moves greedily towards the query node.</p><p><strong>K-nn graph Drawbacks</strong></p><p><strong>Whilst Creation of graph</strong></p><ul><li>High Computation cost — O((n*d)²)</li><li>Memory Usage</li></ul><p><strong>Whilst Search / Graph Traversal</strong></p><ul><li>Scalability — Proximity graphs may not scale well with high-dimensional data due to the curse of dimensionality.</li><li>Local Minima in Search: Greedy search algorithms can get stuck in local minima</li></ul><p>The underlying issue is we are only considering local properties of graph while making edges/connections, which leads to Local Minima in search</p><p><strong>Navigable Small World graph (NSW)</strong></p><p>The origin of NSW can be dated back to the Small World Experiment performed by Milgram in 1960’s which established below findings; This lead to the concept of <strong>“six degrees of separation.”</strong></p><ul><li><strong>Small-World Phenomenon</strong> — empirical evidence indicating that social networks have short path lengths despite their large size.</li><li><strong>Network Structure </strong>— It highlighted the importance of network structure and the presence of hubs or highly connected individuals who play a crucial role in connecting different parts of the network.</li></ul><p>NSW graphs are <strong>inspired</strong> by</p><ul><li>small-world networks</li><li>aim to provide a structure that allows efficient navigation between nodes</li><li>maintain the ability to find nearest neighbours quickly.</li></ul><p><strong>NSW Graph Construction</strong></p><ul><li>When a new node is inserted, it is linked by edges to the M nearest vertices to it in the graph</li><li>Links to the closest neighbours of the elements inserted in the beginning of the construction later become bridges between the network hubs that keep the overall graph connectivity and allow the logarithmic scaling of the number of hops during greedy routing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wE4Ib364n9c3kKkMG9jg8Q.png" /><figcaption>Dark Green Node are New Nodes, each new node builds M new connections/edges with its neighbours in existing NSW graph, Notice that the degree of a node doesn’t always need to be M, it can be higher as well as graph adds more nodes. This way earlier inserted nodes in the NSW graph become the long range connections within graph for navigation.</figcaption></figure><p><strong>NSW Graph Search/Traversal</strong></p><p><strong>Zoom Out Phase</strong></p><ul><li>Choose a random low degree entry node</li><li>Navigate through connected neighbor nodes with higher degree</li><li>Stop when present node’s distance from entry low degree node reaches the scale of distance between query and entry low degree node</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*ia6FaeMjSoRBMux1" /><figcaption>EN = Entry Node;Q = Query Node; EN-4 = distance between Node#4 and EN;EN-Q = distance between Node#Q and EN; At Node#4 Zoom Out phase ends and Zoom in Phase commences</figcaption></figure><p><strong>Zoom In Phase</strong></p><ul><li>We start filtering out results from explored area in zoom out phase,</li><li>The algorithm uses a greedy search approach to move closer to the query point and precisely identifies the nearest target by evaluating distances and optimising the search path</li></ul><p><strong>NSW Drawbacks</strong></p><ul><li>If average degree of node is less within the constructed NSW graph, then the probability of being stuck in a distant false local minimum is higher</li><li>Poly-logarithmic complexity scaling</li></ul><blockquote>No. of distance calc. ∝ avg number of hops * avg number of nodes in greedy path</blockquote><p><strong>Hierarchical Navigable Small World (HNSW) graph</strong></p><p>The idea of Hierarchical NSW algorithm is to separate the edge/links according to their length scale into different layers and then search in a multilayer graph.</p><p>It is similar to 1D probabilistic skip-list data structure, only difference is instead of linked lists in skip-list, here we take proximity graphs for each layer in HNSW data structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sXSDtbSg6psSrbHu" /></figure><p><strong>HNSW Graph Construction</strong></p><ul><li>Nodes in HNSW are inserted sequentially, Every node is randomly assigned an integer <strong><em>l</em></strong> indicating the maximum layer at which this node can present in the graph.</li><li><strong><em>l</em></strong> is selected randomly for each node with an exponentially decaying probability distribution normalised by the non-zero multiplier mL</li></ul><blockquote>l = ⌊-ln(<em>unif</em>(0..1))∙<em>mL</em>⌋</blockquote><blockquote><em>mL = </em>normalization factor for level generation</blockquote><ul><li>Majority of nodes have l assigned as 0, so most of nodes exist only in layer⁰</li><li>if l = 1, then the node can only be found on layer⁰ and layer¹.</li><li>The layer⁰ is actually a NSW graph with all nodes</li><li>Any layer &gt; layer⁰ will have subset of nodes that exists in layer0</li></ul><p><strong>Construction Parameters</strong></p><ul><li><strong>Layer</strong> ~ <em>l</em> = -ln(<em>unif</em>(0..1))∙<em>mL</em> — layer of node in HNSW graph</li><li><strong>mL</strong> — normalization factor ~ <em>1 / ln(M)</em></li><li><strong>efConstruction</strong> — a list whose size determines number of nodes to consider before making connections</li><li><strong>M</strong> — number of connections to be made for each node</li><li><strong>Mmax⁰</strong>— max number of connections which can be made at layer 0</li><li><strong>Mmax</strong> — max number of connections which can be made at any layer</li></ul><p><strong>Adding new nodes</strong></p><ul><li>The algorithm starts from entry point in layer-n and moves to the nearest neighbour</li><li>From the nearest neighbour, it moves to layer-n-1 , where it again finds nearest neighbour</li><li>1 and 2 are repeated until layer¹ is reached (l was layer assigned for this node)</li><li>When algorithm reaches layer¹, we look for efConstruction number of nodes to find nearest neighbour</li><li>Out of efConstruction number of nodes identified, we pick nearest M nodes to create connections</li></ul><p>Before creating connections in layer¹, it is ensured that</p><ul><li>no more than M connections are made — to reduce complexity</li><li>Heuristically connections are verified in a way to make distant connections — long range links</li><li>Connections made between nodes in layer⁰ should never exceed Mmax⁰</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rzmBxnp27LeUQgX3" /><figcaption>Source —<a href="https://towardsdatascience.com/similarity-search-part-4-hierarchical-navigable-small-world-hnsw-2aad4fe87d37"> Similarity Search</a></figcaption></figure><p><strong>HNSW Graph — Heuristics assisted connections</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Q07WN053ngGHM4AC25nCaA.png" /></figure><p><strong>HNSW Graph Traversal / Search</strong></p><p>The search starts from the highest layer and proceeds to one level below every time the local nearest neighbour is greedily found among the layer nodes. Ultimately, the found nearest neighbour on the lowest layer is the answer to the query.</p><p>In Mongodb Atlas 2 of the knobs provided while vector search index creation are below Search Parameters -</p><ul><li><strong>efSearch</strong> ~ <strong>numCandidates</strong> ~ entry points to consider while searching HNSW strcuture</li><li><strong>limit</strong> ~ number of returned results</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*sGfaKKNFnYsY1BY5xg3KWg.png" /><figcaption>Source —</figcaption></figure><p>HNSW Graph tackles the long range connection problem by making heuristics based connections between new node and existing node within the graph.</p><p>HNSW Graph’s layered proximity graph ensures logarithmic time complexity, In this case we can evaluate only a needed fixed portion of the connections for each element independently of the networks size, thus allowing a logarithmic scalability. In such structure the search starts from the upper layer which has only the longest links(the “zoom-in” phase). The algorithm greedily traverses through the elements from the upper layer until a local minimum is reached. After that, the search switches to the lower layer (which has shorter links), restarts from the element which was the local minimum in the previous layer and the process repeats. The maximum number of connections per element in all layers can be made constant, thus allowing a logarithmic complexity scaling of routing in a navigable small world network.</p><p><strong>Conclusion</strong></p><p>In this article, we understood the search problem statement associated with vector embeddings and saw how over a period of time solutions evolved and how we eventually came up with HNSW graph algorithm, We understood drawbacks of each method and how HNSW solves these drawbacks and stands the test of time till date. Combining multi-layer graph strategy with heuristics based connections strategy, HNSW ensures O(logn) time search complexity at the same time also ensures accuracy to an extent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d05bcb7ac867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vectors for dummies — Part 1]]></title>
            <link>https://medium.com/@vinod.krishnan13/vectors-for-dummies-part-1-29ce30182fec?source=rss-83f97bb71364------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ce30182fec</guid>
            <category><![CDATA[skip-list]]></category>
            <category><![CDATA[vectorshift]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Vinod Krishnan]]></dc:creator>
            <pubDate>Sun, 05 May 2024 00:07:02 GMT</pubDate>
            <atom:updated>2024-05-05T00:43:59.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vectors for dummies — Part 1</h3><h4>What are vectors and why do we need them now</h4><p>Vectors in physics/mathematics/computer science are objects which have both magnitude and direction in space, vectors can be represented in various ways, such as arrows in diagrams, <strong>coordinates in space</strong>, or as mathematical objects like <strong>matrices</strong> or <strong>lists with n numbers (in an n-dimensional vector space)</strong>. They are fundamental in many fields of study, including physics, engineering, computer graphics, and more.</p><h4><strong>What is the database problem statement we are trying to solve with vectors?</strong></h4><p>Over a period of time database landscape has evolved, It begun with structured data stored in excel which evolved into relational sql databases where we use “where” clauses to query data in SQL. We often created <strong>b-tree indexes</strong> to speed up the search queries, Fundamentally the search is pivotal to generate any insight out of data stored in a database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCJr8N73cFPD7QQRemCIQQ.png" /><figcaption>B-tree representation</figcaption></figure><p>Then we started storing text blob data, we understood there has to be a better way to index this data, Enter <strong>Lucene indexing</strong> , the search engine library behind E<strong>lasticsearch, Atlas Search.</strong></p><p>Inverted indexes support full text search capability. Being primarily a text indexing and search library, <strong>Lucene lacks native support for semantic search</strong>, which involves understanding the context of queries semantically and fetching context relevant documents beyond just matching keywords This capability to perform context driven search on unstructured/semi-structured data such as video, images and audios remained elusive.</p><p>Now more than 80 percent of data in this world is unstructured, How do we make it queryable, the relational way will definitely not work, so again we need a better way to represent these images.videos, audios, text in a contextual manner</p><p>Enter vector embeddings, We all have plotted 2-D graphs in our childhood, solved mathematical problems of identifying closest points in 2-D space out of 3 x-y co-ordinate pairs. Now think of a n-dimensional contextual space and we are plotting these images, videos, audios, text in this n-D graph as data points, Similar data points would exist closer to each other in n-Dimensional space, But how do we calculate distance between n-dimension co-ordinates, This is where we use distance metrics , a few are mentioned below</p><ul><li>Euclidean</li><li>Cosine Similarity</li><li>Dot-product</li></ul><p>So we now know how to identify data points closer to each other based on above mentioned distance metrics, But How do we do search similar data points from a big collection of a million videos/text/audios, We can’t use a brute force method to calculate distance for all vectors (k- nearest neighbours algorithm), Instead we need a better way to organise this vector data so we can search through it efficiently.</p><p><strong>The Solution</strong> — <strong>HNSW </strong>(Hierarchical Navigable Small World) — Approximate Nearest Neighbour algorithm.</p><p>This is a data structure which helps you organise millions of vector by arranging them in form of small worlds graphs on multiple layers and then navigate through them in an approximate manner to return results, To understand this with example, We will navigate our path through the universe, via galaxies, solar systems, eventually to our home planet i.e. earth, We start with top-most layer (Universe Layer - has single entry point assuming oneuniverse), We calculate the distance metric between our <strong>query/home plant/earth vector</strong> with all <strong>three galaxy vectors</strong> in galaxy layer and choose the left most galaxy vector (as the distance is the least with query vector), We greedily identify friend of current vector which has least distance from our query vector, once we hit the local minima, we move on to the next plane and repeat the same process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyWqj8pAM-mHCQIwJX4M7Q.png" /></figure><p>We keep on doing this until we reach local minimum for Planet Layer and thats when we stop and return results. This is how we are able to find contextually relevant answers to our queries (without need of exact matches) from any type of data (text blob, audio, video etc.). This ANN algorithm is faster when compared to a k-NN algorithm. Vector capabilities of database can be used to solve multiple usecases such as</p><ul><li>Semantic Search</li><li>Similarity Search</li><li>RAG — Retrieval Augmented Generation — Long term memory for LLM’s</li><li>Image Search</li></ul><p>Now there are several vector database out there that can help with implementing vector solutions for above usecases, to name a few</p><ul><li>Pinecone (vector/keyword search capability)</li><li>Weaviate (vector/keyword search capability)</li><li>Mongodb Atlas (General Purpose Database with vector/keyword search capability)</li></ul><p>In the next part of this Vector series we will implement a gen-AI usecase with Mongodb Atlas….See you soon in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ce30182fec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>