<?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 Apoorva Joshi on Medium]]></title>
        <description><![CDATA[Stories by Apoorva Joshi on Medium]]></description>
        <link>https://medium.com/@appujo?source=rss-162522dfc382------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Wm6oDsX7ZNrZSGd0ElIoBg.jpeg</url>
            <title>Stories by Apoorva Joshi on Medium</title>
            <link>https://medium.com/@appujo?source=rss-162522dfc382------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:28:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@appujo/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[Handling Data Changes in MongoDB]]></title>
            <link>https://medium.com/mongodb/handling-data-changes-in-mongodb-f7fbb401caf4?source=rss-162522dfc382------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fbb401caf4</guid>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Apoorva Joshi]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 22:58:33 GMT</pubDate>
            <atom:updated>2024-12-04T22:58:33.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvgZriq1OCw7yVYDEqrTYA.png" /></figure><p>This month, I talked with multiple customers about how to deal with and design for potential changes to their data in MongoDB. The most commonly anticipated data changes I observed across these customers were updates to fields in existing documents, and/or new documents with net new fields.</p><p>In this article, I will discuss misconceptions that the developers had about MongoDB, that resulted in design anti-patterns. I will also talk about a schema design pattern that is well-suited for handling data changes and schema validation to prevent bad updates.</p><h3>Common misconceptions about MongoDB</h3><h4>❌ Writes to a MongoDB collection require locks to ensure consistency, which can impact read performance.</h4><p>Writes, including updates, are atomic operations at the document level in MongoDB. This means guaranteed consistency for individual documents, ensuring that reads see documents in a complete and stable state even when a write is in progress concurrently. For single-document updates, there is no need to implement application-side locking mechanisms or use transactions to ensure consistency.</p><h4>❌ In a write-intensive workload, documents should be decomposed into smaller parts to align with your write patterns.</h4><p>This advice is in fact often true for larger documents as, when the storage engine hits a checkpoint and flushes changes to disk, it avoids the need to re-write a large document for the sake of changes to one small part of it. However, there is an important caveat: If your documents are less than 32KB in size, you probably won’t see much benefit from decomposing them. That’s because the MongoDB storage engine works with a default 32KB block size and moves data to and from disk in blocks, rather than document by document. If you make a change to a document within a block, when those changes are flushed to disk, the whole block gets written back.</p><blockquote>If your documents are greater than 200 KB in size, you may first want to take a closer look at your document schema to see if it can be optimized — in most cases, it can!</blockquote><h4>❌ Data of different shapes and containing different fields cannot co-exist in the same MongoDB collection.</h4><p>On the contrary, MongoDB’s flexible document model allows for documents with different fields and data types to co-exist in the same collection. This allows you to implement dynamic schema changes, enabling you to add, remove, or modify fields as your data evolves, without downtime or complex migrations.</p><h3>Proposed solutions</h3><p>Assuming that updates required some form of application-side protection to avoid inconsistent reads, and that documents with varying fields and data types could not coexist in the same collection, the development teams created more collections than necessary, effectively creating a relational data model within MongoDB. With that in mind, I made the following suggestions to the teams:</p><h3>Consolidate the collections</h3><p>My first suggestion to the teams was to consolidate all the documents into a single collection. With documents less than 32 KB in size, a new set of fields or updating some fields in existing documents on a not-so-frequent cadence is not reason enough to create a new collection, especially if these fields need to be queried with the rest of the data.</p><p>Having data in separate collections means performing $lookup operations at query time — $lookups are akin to SQL joins and should be avoided where possible since, like joins in an RDBMS, they are resource-intensive and can cause performance bottlenecks at scale. In MongoDB, in most cases, $lookups can be avoided by optimizing the data schema.</p><h3>Use the Polymorphic pattern</h3><p>The primary reason we saw the teams creating multiple collections was that they were anticipating new documents with some new fields. The <a href="https://www.mongodb.com/developer/products/mongodb/polymorphic-pattern?utm_campaign=devrel&amp;utm_medium=medium&amp;utm_content=dr-insights-changing-data&amp;utm_term=apoorva.joshi">Polymorphic design pattern</a> in MongoDB is well-suited for exactly this. When new documents have more similarities than differences with existing data, this design pattern can help keep documents in the same collection while accommodating the differences.</p><p>For example, one of the teams was building a centralized knowledge base to power AI applications across the organization. The data for the knowledge base can come from multiple sources, resulting in documents with mostly the same fields, but different metadata fields depending on the source of the data. Implementing the Polymorphic pattern in this case would look as follows:</p><pre>[<br>  {<br>    &quot;_id&quot;: &quot;64a7c2f1d9b13e45b0a1a001&quot;,<br>    &quot;type&quot;: &quot;HR&quot;,<br>    &quot;last_updated&quot;: &quot;2023-07-10&quot;<br>    &quot;text&quot;: &quot;Our company provides employees with health benefits, including medical, dental, and vision insurance..&quot;,<br>    &quot;embedding&quot;: [0.12,-0.45,0.78,...],<br>    &quot;metadata&quot;: {<br>      &quot;chunk_id&quot;: 1,<br>      &quot;source_url&quot;: &quot;https://internal.company.com/hr/policy-handbook&quot;,<br>      &quot;department&quot;: &quot;HR&quot;,<br>      &quot;policy_id&quot;: &quot;HR-2024-001&quot;,<br>      &quot;effective_date&quot;: &quot;2024-01-01&quot;,<br>      &quot;review_frequency&quot;: &quot;Annually&quot;<br>    }<br>  },<br>  {<br>    &quot;_id&quot;: &quot;64a7c2f1d9b13e45b0a1a002&quot;,<br>    &quot;type&quot;: &quot;Technical Docs&quot;,<br>    &quot;last_updated&quot;: &quot;2023-11-15&quot;,<br>    &quot;text&quot;: &quot;To set up the software, download the installer from the portal and run the setup wizard...&quot;,<br>    &quot;embedding&quot;: [-0.34,0.67,-0.21,...],<br>    &quot;metadata&quot;: {<br>      &quot;chunk_id&quot;: 2,<br>      &quot;source_url&quot;: &quot;https://docs.company.com/technical/setup-guide&quot;,<br>      &quot;product&quot;: &quot;Enterprise Software Suite&quot;,<br>      &quot;version&quot;: &quot;3.5.2&quot;,<br>      &quot;module&quot;: &quot;Installation&quot;<br>    }<br>  }<br>]</pre><p>By structuring the data as shown above, querying for all the documents can be accomplished with a simple query. The same collection will also support queries for documents from a specific data source via a filter on the `type` attribute.</p><blockquote>If all new documents are expected to have a new, mostly static schema, you can also consider using the <a href="https://www.mongodb.com/blog/post/building-with-patterns-the-schema-versioning-pattern?utm_campaign=devrel&amp;utm_medium=medium&amp;utm_content=dr-insights-changing-data&amp;utm_term=apoorva.joshi">Schema Versioning pattern</a> which builds on top of the Polymorphic pattern.</blockquote><h3>Use schema validation to prevent bad updates</h3><p>One of the teams required users to be able to update documents in their main collection. However, they were concerned about users potentially making bad updates to this critical collection. To tackle this, I suggested enforcing <a href="https://www.mongodb.com/docs/manual/core/schema-validation?utm_campaign=devrel&amp;utm_medium=medium&amp;utm_content=dr-insights-changing-data&amp;utm_term=apoorva.joshi">schema validation</a> on the collection. With schema validation, you can create validation rules for fields in your documents such as allowed data types and values. All document inserts and, by extension, updates into the collection are checked against these rules, and insert operations that would result in an invalid document are rejected.</p><p>To add schema validation to an existing collection (this is typically the case), run the <strong>collMod</strong> command with the schema validation rules defined as a JSON object using the <strong>$jsonSchema</strong> operator:</p><pre>db.runCommand( { collMod: &quot;knowledge_base&quot;,<br>  validator: {<br>     $jsonSchema: {<br>        bsonType: &quot;object&quot;,<br>        required: [&quot;text&quot;, &quot;embedding&quot;],<br>        properties: {<br>           text: {<br>              bsonType: &quot;string&quot;,<br>              description: &quot;must be a string and is required&quot;<br>           },<br>           embedding: {<br>              bsonType: &quot;array&quot;,<br>              description: &quot;must be an array and is required&quot;,<br>              minItems:1536,<br>              items: {<br>                  bsonType: &quot;double&quot;<br>              }<br>           }<br>        }<br>     }<br>  }<br>} )</pre><p>If a user then tries to push an update that does not adhere to the schema validation rules, they will receive an error:</p><pre>const doc = {<br>  &quot;_id&quot;: &quot;64a7c2f1d9b13e45b0a1a002&quot;,<br>  &quot;type&quot;: &quot;Technical Docs&quot;,<br>  &quot;last_updated&quot;: &quot;2024-11-18&quot;,<br>  &quot;text&quot;: &quot;The API supports authentication via OAuth 2.0, allowing secure integration with third-party applications...&quot;,<br>  &quot;embedding&quot;: [0.41,-0.18,0.67,...],<br>  &quot;metadata&quot;: {<br>    &quot;chunk_id&quot;: 3,<br>    &quot;source_url&quot;: &quot;https://docs.company.com/api/v1.2/release-notes&quot;,<br>    &quot;product&quot;: &quot;Developer API Suite&quot;,<br>    &quot;version&quot;: &quot;1.2.0&quot;,<br>    &quot;module&quot;: &quot;Authentication&quot;<br>  }<br>};<br>db.knowledge_base.insertOne(doc);<br><br><br>MongoServerError: Document failed validation<br>Additional information: {<br>  failingDocumentId: ObjectId(&#39;673bd1b0a64320164962cb32&#39;),<br>  details: {<br>    operatorName: &#39;$jsonSchema&#39;,<br>    schemaRulesNotSatisfied: [<br>      {<br>        operatorName: &#39;properties&#39;,<br>        propertiesNotSatisfied: [<br>          {<br>            propertyName: &#39;embedding&#39;,<br>            description: &#39;must be an array and is required&#39;,<br>            details: [<br>              {<br>                operatorName: &#39;minItems&#39;,<br>                specifiedAs: { minItems: 1536 },<br>                reason: &#39;array did not match specified length&#39;,<br>                consideredValue: [-0.34,0.67,-0.21,...],<br>                numberOfItems: 768<br>              }<br>            ]<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>The above error occurred because the user tried to insert a document where the dimensions of the embedding vector (768) did not match the dimensions specified in the validation rule (1536).</p><h3>Summary</h3><p>Whether it’s updating existing data or changing the shape of your data, data changes are inevitable when it comes to building software applications. MongoDB’s flexible document model is designed to evolve with your application’s data needs. With the right schema design and validation, MongoDB allows you to efficiently and safely evolve your data model without any complexity and downtime.</p><p>To learn more about schema design best practices, visit our <a href="https://www.mongodb.com/developer/?utm_campaign=devrel&amp;utm_medium=medium&amp;utm_content=dr-insights-changing-data&amp;utm_term=apoorva.joshi">Developer Center</a>. If you would like advice on data modeling from a MongoDB expert, schedule a <a href="https://www.mongodb.com/events/mongodb-schema-design-reviews?utm_campaign=devrel&amp;utm_medium=medium&amp;utm_content=dr-insights-changing-data&amp;utm_term=apoorva.joshi">Design Review</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fbb401caf4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/handling-data-changes-in-mongodb-f7fbb401caf4">Handling Data Changes in MongoDB</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Choose the Best Embedding Model for Your LLM Application]]></title>
            <link>https://medium.com/mongodb/how-to-choose-the-best-embedding-model-for-your-llm-application-2f65fcdfa58d?source=rss-162522dfc382------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f65fcdfa58d</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Apoorva Joshi]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 22:15:57 GMT</pubDate>
            <atom:updated>2025-11-05T19:10:09.618Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are building generative AI (GenAI) applications in 2025, you’ve probably heard the term “embeddings” a few times by now and are seeing new embedding models hit the shelf every week. So why do so many people suddenly care about embeddings, a concept that has existed since the 1950s? And if embeddings are so important and you must use them, how do you choose among the vast number of options for embedding models out there?</p><p>This tutorial will cover the following:</p><ul><li>What are embeddings?</li><li>Importance of embeddings in RAG applications</li><li>How to choose the best embedding model for your RAG application</li><li>Evaluating embedding models</li></ul><h3>What are embeddings and embedding models?</h3><p><strong>An embedding is an array of numbers (a vector) representing a piece of information, such as text, images, audio, video, etc.</strong> Together, these numbers capture semantics and other important features of the data. The immediate consequence of doing this is that semantically similar entities map close to each other while dissimilar entities map farther apart in the vector space. For clarity, see the image below for a depiction of a high-dimensional vector space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAqMdCQjTmj9QZb3EcLDKA.png" /><figcaption>2D representation of a higher-dimensional vector space</figcaption></figure><p>Embedding models are specialized machine learning models that are trained on large corpora of data to learn complex semantic relationships within them. Given a raw piece of information as input, these models generate multi-dimensional vectors (embeddings) that capture the semantic meaning and key attributes of the input data.</p><h3>What is RAG (briefly)?</h3><p>Retrieval-augmented generation, as the name suggests, aims to improve the quality of pre-trained LLM generation using data retrieved from external knowledge sources. The success of RAG lies in retrieving the most relevant results from the knowledge base. This is where embeddings come into the picture. A RAG pipeline looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*lcUQ17_Cjynhskcm8nWmIw.png" /><figcaption>RAG Workflow</figcaption></figure><p>The pipeline above shows semantic search, a common retrieval approach in GenAI applications. In this technique, embeddings are first generated for all documents in the knowledge base using an embedding model. When a user asks a question, the same embedding model generates an embedding for the query. The system then finds the most relevant documents by comparing how similar their embeddings are to the query embedding. Finally, the retrieved documents are sent to an LLM along with the user’s question and any additional prompts to generate an answer.</p><h3>Choosing the best embedding model for your RAG application</h3><p>As we have seen above, embeddings are central to RAG. But with so many embedding models out there, how do we choose the best one for our use case?</p><p>A good place to start when looking for the best embedding models is the <a href="https://huggingface.co/spaces/embedding-benchmark/RTEB">Retrieval Text Embedding Benchmark (RTEB) Leaderboard</a> on Hugging Face. RTEB improves upon existing benchmarks, such as <a href="https://huggingface.co/spaces/mteb/leaderboard">MTEB</a>, by evaluating embedding models on a combination of open and private datasets, thereby creating a fair, transparent, and application-focused standard for measuring how models perform on unseen data.</p><blockquote>Evaluations of this magnitude for multimodal models are just emerging (see the <a href="https://huggingface.co/spaces/TIGER-Lab/MMEB-Leaderboard">Massive Multimodal Embedding Benchmark (MMEB)</a>), so we will only focus on text embedding models for this tutorial. However, all the guidance here on choosing the best embedding model also applies to multimodal models.</blockquote><p>While the RTEB leaderboard is a great starting point, we recommend benchmarking a few candidate models on your data to validate their performance for your specific use case and constraints, such as cost and latency. We will see how to do this later in the tutorial, but first, let’s take a closer look at the leaderboard.</p><p>Here’s a snapshot of the top 10 best embedding models on the RTEB leaderboard currently, sorted in decreasing order of overall retrieval performance, indicated by the Mean(Task) column:</p><figure><img alt="Top 10 embedding models on the RTEB leaderboard" src="https://cdn-images-1.medium.com/max/1024/1*wOLdwuXBnjiGrPEx79aw6g.png" /><figcaption><em>Top 10 embedding models on the RTEB leaderboard</em></figcaption></figure><p>When choosing candidate models for evaluation, we recommend focusing on the following columns:</p><ul><li><strong>Mean (Task)</strong>: Represents average [Normalized Discounted Cumulative Gain](https://en.wikipedia.org/wiki/Discounted_cumulative_gain) (NDCG) @ 10 across several open and private datasets. NDCG is a common metric to measure the performance of retrieval systems. A higher NDCG indicates an embedding model that is better at ranking relevant items higher in a list of retrieved results.</li><li><strong>Embedding Dimensions</strong>: Length of the embedding vector produced by the embedding model. Smaller embeddings are more storage-efficient and will be faster to retrieve, while more dimensions can capture nuanced details and relationships in the data. Ultimately, you want a good trade-off between capturing the complexity of data and operational efficiency.</li><li><strong>Max Tokens</strong>: Maximum number of tokens that can be compressed into a single embedding. While higher token limits offer more flexibility, embedding too much data in a single vector can degrade retrieval quality. The optimal token count for your use case requires additional experimentation but is beyond the scope of this tutorial.</li><li><strong>Model Size</strong>: Number of parameters in the embedding model. This is roughly proportional to the amount of compute and memory required to run the model. While retrieval performance generally scales with model size, larger models also increase application latency. This latency-performance trade-off becomes especially important in production environments. This metric is particularly relevant when hosting your own open-source models. Note that most top-performing models on the leaderboard are currently fully managed proprietary models, the parameter counts of which are not publicly disclosed.</li></ul><p>The top 10 best embedding models on the leaderboard contain a mix of proprietary vs open-source models. Let’s compare some of these to find the best embedding model for our dataset.</p><h4>Before we begin</h4><p>Here are some things to note about our evaluation experiment.</p><h4>Dataset</h4><p>MongoDB’s <a href="https://huggingface.co/datasets/MongoDB/cosmopedia-wikihow-chunked">cosmopedia-wikihow-chunked</a> dataset, which is available on Hugging Face, and consists of prechunked WikiHow-style articles.</p><h4>Embedding models evaluated</h4><ul><li><a href="https://docs.voyageai.com/docs/embeddings">voyage-3-large</a>: The top-performing model on the leaderboard, which is a proprietary general-purpose text embedding model from VoyageAI.</li><li><a href="https://ai.google.dev/gemini-api/docs/embeddings">gemini-embedding-001</a>: Google’s first embedding model from the Gemini model family.</li><li><a href="https://platform.openai.com/docs/guides/embeddings">text-embedding-3-large</a>: The latest embedding model from OpenAI, and a popular choice among developers.</li></ul><h4>Evaluation metrics</h4><p>We used the following metrics to evaluate embedding performance:</p><ul><li><strong>Embedding latency</strong>: Time taken to generate embeddings</li><li><strong>Retrieval quality</strong>: Relevance of retrieved documents to the user query</li></ul><h4>Where’s the code?</h4><p>Evaluation notebooks for each of the above embedding models are available:</p><ul><li>Voyage AI’s <a href="https://github.com/mongodb-developer/GenAI-Showcase/blob/main/notebooks/evals/voyageai-embeddings-eval.ipynb">voyage-3-large</a></li><li>Google’s <a href="https://github.com/mongodb-developer/GenAI-Showcase/blob/main/notebooks/evals/gemini-embeddings-eval.ipynb">gemini-embedding-001</a></li><li>OpenAI’s <a href="https://github.com/mongodb-developer/GenAI-Showcase/blob/main/notebooks/evals/openai-embeddings-eval.ipynb">text-embedding-3-large</a></li></ul><p>To run the notebooks, simply click the <strong>Open in Colab</strong> shield at the top of the notebook. This will open the notebook in Google Colab, a hosted Jupyter Notebook service that requires no setup to use and provides free access to computing resources, including GPUs.</p><h3>Step 1: Install the required libraries</h3><p>The libraries required for each embedding model differ slightly, but the common ones are as follows:</p><ul><li><strong>datasets</strong>: Python library to get access to datasets available on Hugging Face Hub</li><li><strong>numpy</strong>: Python library that provides tools to perform mathematical operations on arrays</li><li><strong>pandas</strong>: Python library for data analysis, exploration, and manipulation</li><li><strong>tdqm</strong>: Python module to show a progress bar for loops</li></ul><pre>! pip install -qU datasets numpy pandas tqdm</pre><p>Additionally for Voyage AI:<br><strong>voyagea</strong>i: Python library to interact with Voyage AI’s APIs</p><pre>! pip install -qU voyageai</pre><p>Additionally for Gemini:<br><strong>google-genai</strong>: Google’s GenAI Python SDK</p><pre>! pip install -qU google-genai</pre><p>Additionally for the OpenAI:<br><strong>openai</strong>: Python library to access OpenAI’s APIs</p><pre>! pip install -qU openai</pre><h3>Step 2: Set up prerequisites</h3><p>The Voyage AI, Gemini and OpenAI models are available via APIs. So you’ll need to obtain API keys and make them available to the respective clients. Follow the steps below to obtain API keys:</p><ul><li><a href="https://docs.voyageai.com/docs/api-key-and-installation#authentication-with-api-keys">Voyage AI</a></li><li><a href="https://aistudio.google.com/app/apikey">Gemini</a></li><li><a href="https://platform.openai.com/api-keys">OpenAI</a></li></ul><p>Initialize Voyage AI client:</p><pre>import os<br>import getpass<br>import voyageai<br><br>os.environ[&quot;VOYAGE_API_KEY&quot;] = getpass.getpass(&quot;Voyage API Key:&quot;)<br>voyage_client = voyageai.Client()</pre><p>Initialize Gemini client:</p><pre>from google import genai<br>os.environ[&quot;GEMINI_API_KEY&quot;] = getpass.getpass(&quot;Gemini API Key:&quot;)<br>gemini_client = genai.Client()</pre><p>Initialize OpenAI client:</p><pre>from openai import OpenAI<br>os.environ[&quot;OPENAI_API_KEY&quot;] = getpass.getpass(&quot;OpenAI API Key:&quot;)<br>openai_client = OpenAI()</pre><h3>Step 3: Download the evaluation dataset</h3><p>As mentioned previously, we will use MongoDB’s cosmopedia-wikihow-chunked dataset. The dataset is quite large (1M+ documents). So we will stream it and grab the first 2k records, instead of downloading the entire dataset to disk.</p><pre>from datasets import load_dataset<br>import pandas as pd<br><br># Use streaming=True to load the dataset without downloading it fully<br>data = load_dataset(&quot;MongoDB/cosmopedia-wikihow-chunked&quot;, split=&quot;train&quot;, streaming=True)<br># Get first 2k records from the dataset<br>data_head = data.take(2000)<br>df = pd.DataFrame(data_head)</pre><p>Here’s a snapshot of what the dataset looks like:</p><figure><img alt="Dataset snapshot" src="https://cdn-images-1.medium.com/max/1024/1*qUzaYNXH2-SnWWkY3K2J5A.png" /><figcaption><em>Dataset snapshot</em></figcaption></figure><p>The dataset consists of ~350 WikiHow documents broken up into smaller chunks, since in RAG you typically embed smaller chunks of a large document rather than the entire document at once. Each row in the dataset represents a single chunk, and the text column contains the chunk content that we will embed.</p><h3>Step 4: Create embeddings</h3><p>Now, let’s create embedding functions for each of our embedding models.</p><p>For <strong>voyage-3-large</strong>:</p><pre>def get_embeddings(text: str, input_type: str) -&gt; List[float]:<br>    &quot;&quot;&quot;<br>    Get embeddings using the Voyage AI API.<br><br>    Args:<br>        text (str): Text to embed<br>        input_type (str): Type of input to embed. Can be &quot;document&quot; or &quot;query&quot;.<br><br>    Returns:<br>        List[float]: Embedding vector<br>    &quot;&quot;&quot;<br>    response = voyage_client.embed(text, model=&quot;voyage-3-large&quot;, input_type=input_type)<br>    return response.embeddings[0]</pre><p>The embedding function above uses the embed method of Voyage AI’s API. The method takes a text string (text), model name (model), in this case voyage-3-large, and an input_type as arguments and returns an embeddings object consisting of the embedding vector of the input text. The input_type can be document or query, depending on whether you are embedding a list of documents or user queries. Voyage uses this value to prepend the inputs with special prompts to enhance retrieval quality.</p><p>For <strong>gemini-embedding-001</strong>:</p><pre>def get_embeddings(text: str) -&gt; List[float]:<br>    &quot;&quot;&quot;<br>    Get embeddings using the Gemini API.<br><br>    Args:<br>        text (str): Text to embed<br><br>    Returns:<br>        List[float]: Embedding vector<br>    &quot;&quot;&quot;<br>    response = gemini_client.models.embed_content(<br>        model=&quot;gemini-embedding-001&quot;, contents=text<br>    )<br>    return response.embeddings[0].values</pre><p>The embedding function for <strong>gemini-embedding-001</strong> is similar to the previous one, with some key differences. It uses the embed_content method from Google’s GenAI SDK. The method takes a text string (contents) and model name (model), in this case gemini-embedding-001, as arguments and returns an embeddings object consisting of the embedding vector of the input text.</p><p>For<strong> text-embedding-3-large</strong>:</p><pre>def get_embeddings(text: str) -&gt; List[float]:<br>    &quot;&quot;&quot;<br>    Generate embeddings using the OpenAI API.<br><br>    Args:<br>        text (str): Text to embed<br><br>    Returns:<br>        List[float]: Embedding vector<br>    &quot;&quot;&quot;<br>    text = text.replace(&quot;\n&quot;, &quot; &quot;)<br>    response = openai_client.embeddings.create(<br>        input=text, model=&quot;text-embedding-3-large&quot;<br>    )<br>    return response.data[0].embedding</pre><p>Finally, the embedding function for <strong>text-embedding-3-large </strong>uses OpenAI’s<strong> </strong>Embeddings API to generate embeddings. The create method of the API takes a text string (input) and model name (model) as input and, similar to the other APIs above, returns an embeddings object consisting of the embedding vector.</p><h3>Step 5: Evaluation</h3><p>As mentioned previously, we will evaluate the models based on embedding latency and retrieval quality.</p><h4>Measuring embedding latency</h4><p>For our evaluation, we will create a local vector store, which is essentially a Python list of embedded texts. To measure embedding latency, we embed the text column for all chunks in our dataset and calculate the average time per chunk. This gives us a sense of how fast each candidate model can process text, which applies to both document and query embedding.</p><pre>import numpy as np<br>from tqdm.auto import tqdm<br><br># Get all the texts in the dataset<br>texts = df[&quot;text&quot;].tolist()<br><br>embeddings = []<br># Generate embeddings<br>for text in tqdm(texts):<br>    embedding = get_embeddings(text, &quot;document&quot;)<br>    # Add to the list of embeddings<br>    embeddings.append(np.array(embedding))</pre><p>The average embedding latency numbers are as follows:</p><figure><img alt="Average embedding latency numbers" src="https://cdn-images-1.medium.com/max/1024/1*poY0nn1FNwMTFm89gm2REw.png" /></figure><p>voyage-3-large demonstrates the fastest embedding speed at 89ms per chunk, making it 2.2x faster than gemini-embedding-001 and 3.5x faster than text-embedding-3-large. voyage-3-large’s lower dimensionality (1024 vs 3072) likely contributes to its speed advantage, and could also reduce storage and computational costs for retrieval downstream.</p><h4>Measuring retrieval quality</h4><p>To evaluate retrieval quality, we use a small set of questions based on themes seen in our dataset. For each question, we retrieve the top 3 most relevant chunks from our local “vector store” based on the cosine similarity between the query embedding and the chunk embedding as follows:</p><pre>from sentence_transformers.util import cos_sim<br><br># Converting embeddings list to a Numpy array- required to calculate cosine similarity<br>embeddings = np.asarray(embeddings)<br><br>def query(query: str, top_k: int = 3) -&gt; None:<br>    &quot;&quot;&quot;<br>    Query the local vector store for the top 3 most relevant documents.<br><br>    Args:<br>        query (str): User query<br>        top_k (int, optional): Number of documents to return. Defaults to 3.<br>    &quot;&quot;&quot;<br>    # Generate embedding for the user query<br>    query_emb = np.asarray(get_embeddings(query))<br>    # Calculate cosine similarity<br>    scores = cos_sim(query_emb, embeddings)[0]<br>    # Get indices of the top k records<br>    idxs = np.argsort(-scores)[:top_k]<br><br>    print(f&quot;Query: {query}&quot;)<br>    for idx in idxs:<br>        print(f&quot;Score: {scores[idx]:.4f}&quot;)<br>        print(texts[idx])<br>        print(&quot;--------&quot;)</pre><p>We then pass the query and the retrieved chunks to an LLM, in this case Claude Sonnet 4.5 and prompt it to assess the relevance of the retrieved chunks to the query as follows:</p><pre>Given a query and the documents retrieved by three embedding models, tell me which model retrieved the most relevant results and why:<br><br>Query: &lt;query&gt;<br><br>Model 1:<br>   1. Result #1<br>   2. Result #2<br>   3. Result #3<br><br>Model 2:<br>   1. Result #1<br>   2. Result #2<br>   3. Result #3<br><br>Model 3:<br>   1. Result #1<br>   2. Result #2<br>   3. Result #3</pre><p>Notice that we intentionally omitted model names from the evaluation prompt to avoid biasing the LLM judge based on its prior knowledge about specific models and providers. For reference, Model 1 is voyage-3-large, Model 2 is gemini-embedding-001, and Model 3 is text-embedding-3-large.</p><p>This evaluation method is known as LLM-as-a-judge, and is a widely used evaluation technique for LLM-based applications, where strong LLMs are used to assess answer quality. You can extend the simple prompt above by adding ground truth answers, specific evaluation criteria, or even scoring rubrics that produce numerical ratings. Also, while we’ve used a very small dataset in this blog, to evaluate your system effectively, you should create a test set of at least 50 samples that includes common user questions, edge cases (complex, ambiguous, or multi-part queries), and adversarial inputs to assess robustness against malicious or inappropriate queries. See the Resources section for more on LLM application evaluation.</p><p>Based on our preliminary evaluation, the LLM judge ranked voyage-3-large as the best performing model, followed by text-embedding-3-large and gemini-embedding-001. voyage-3-large produces the strongest ranking by placing the most relevant results at the top, while text-embedding-3-large retrieves all relevant results but with a weaker ranking. gemini-embedding-001 occasionally retrieves chunks that are irrelevant to the query.</p><h3>Conclusion</h3><p>In this tutorial, we looked into how to choose the best embedding model for RAG. The RTEB leaderboard is a good place to start, especially for text embedding models, but evaluating them on your data is important to find the best one for your specific use case. Storage and inference costs, embedding latency, and retrieval quality are all important parameters to consider while evaluating embedding models. The best embedding model is typically one that offers the best trade-off across these dimensions.</p><p>Now that you have a good understanding of embedding models, here are some resources to get started with building RAG applications using MongoDB:</p><p>- <a href="https://www.mongodb.com/docs/atlas/ai-integrations/langchain/#std-label-langchain">Build a RAG System with LangChain, OpenAI, and MongoDB</a></p><p>- <a href="https://www.mongodb.com/developer/products/atlas/rag-with-polm-stack-llamaindex-openai-mongodb/">How to Build a RAG System With LlamaIndex, OpenAI, and MongoDB</a></p><p>Follow along with these by creating a <a href="https://www.mongodb.com/cloud/atlas/register">free MongoDB Atlas cluster</a>.</p><h3>Resources</h3><ul><li><a href="https://docs.voyageai.com/docs/embeddings">Voyage AI Embeddings API docs</a></li><li><a href="https://ai.google.dev/gemini-api/docs/embeddings">Gemini Embeddings API docs</a></li><li><a href="https://platform.openai.com/docs/api-reference/embeddings/create">OpenAI Embeddings API docs</a></li><li><a href="https://hamel.dev/blog/posts/evals-faq/">Evaluating your LLM Apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f65fcdfa58d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/how-to-choose-the-best-embedding-model-for-your-llm-application-2f65fcdfa58d">How to Choose the Best Embedding Model for Your LLM Application</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Build Together — Sneak peek into MongoDB.local NYC’s AI afterparty]]></title>
            <link>https://medium.com/mongodb/ai-build-together-sneak-peek-into-mongodb-local-nycs-ai-afterparty-de080ab8355f?source=rss-162522dfc382------2</link>
            <guid isPermaLink="false">https://medium.com/p/de080ab8355f</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ideathon]]></category>
            <dc:creator><![CDATA[Apoorva Joshi]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 16:58:52 GMT</pubDate>
            <atom:updated>2024-06-14T16:31:27.327Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI Build Together — Sneak peek into MongoDB.local NYC’s AI afterparty</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_hpH5DtiEcrguQ6sQ4hnA.png" /></figure><p>A few weeks ago, I attended my first MongoDB.local in New York City. As an AI Developer Advocate at the company, there was much to be excited about at the event — the announcement of the <a href="https://www.mongodb.com/services/consulting/ai-applications-program">MongoDB AI Applications Program</a> (MAAP) and natural language queries in MongoDB Compass and Atlas Charts being the highlights for me. MAAP is an important milestone for MongoDB. It is the culmination of all the efforts we have made in the past year to build strong partnerships within the AI ecosystem and it also demonstrates our continued commitment to helping organizations of all sizes successfully build AI-powered applications.</p><p>To celebrate this major milestone and a very successful .local, our Developer Relations group at MongoDB hosted an “AI Build Together” ideathon in collaboration with a few of our AI partners to wrap up .local NYC. Here’s a recap of how the event came about, who attended, and our takeaways.</p><h3>Goals</h3><p>The goal of this event was to create an after-hours networking and collaboration opportunity for .local attendees. Given that this event would take place after a long day of .local activities, we knew that we needed something more compelling than just conversation, free food, and swag. This is how the idea of an AI-focused ideathon came about.</p><p>An ideathon is meant to be a collaborative event where people get together to discuss and evaluate ideas. Given the buzz around AI at .local and in general, it only seemed fitting to do something AI-related. Hence an AI-focused ideathon which we called “AI Build Together” after one of MongoDB’s core values.</p><h3>Planning</h3><p>The idea for AI Build Together was inspired, in part, by Google’s <a href="https://pair.withgoogle.com/guidebook/workshop">People + AI Workshop</a> which is designed to be a two-day workshop where people work in teams to design AI-based solutions for hypothetical scenarios, but the lessons learned can be applied to real-world products.</p><p>For AI Build Together, we adapted the Google workshop to a two-hour format where teams collaboratively brainstormed AI workflows around real-world scenarios such as education, healthcare, sustainability, etc. Specifically, we asked the teams to come up with a problem statement and whiteboard an AI-based solution for the problem, including potential tools that would be required to solve it. Since we were welcoming several of our AI partners at .local, we invited these experts to guide and advise teams as they worked through solutions. Finally, we ended the event with 2–3 minute pitches from each team.</p><h3>Building Together</h3><p>AI Build Together ended up being a huge hit — we saw over 60 attendees and 11 experts from our AI partners such as <a href="https://arize.com/">Arize AI</a>, <a href="https://aws.amazon.com/ai/">AWS</a>, <a href="https://www.dataworkz.com/">Dataworkz</a>, <a href="https://www.llamaindex.ai/">LlamaIndex</a>, <a href="https://www.together.ai/">Together AI</a> and <a href="https://unstructured.io/">Unstructured</a> show up for the event after a long day at .local NYC. We had 7 teams pitch AI-based solutions for education, supply chain, healthcare, devops, cybersecurity, sustainability, and productivity.</p><p>From all the great ideas presented, my top three favorite AI solutions were as follows:</p><ul><li><strong>Healthcare</strong>: A tool for frontline mental health workers that uses a patient’s behavioral characteristics such as facial expressions, body language, etc. as additional diagnostic signals, in addition to verbally reported information, to generate a more accurate preliminary analysis of the patient’s mental condition.</li><li><strong>Education</strong>: Personalized learning agents for students that track individual preferences, learning styles, pace, and history to provide personalized learning objectives and milestones, different content formats based on learning style, adaptive assessments based on identified knowledge gaps, etc.</li><li><strong>Sustainability</strong>: A multimodal tool that analyzes satellite, drone, sensor data, and environment reports to track changes in plant and animal species populations within national parks and provides recommendations to park rangers about conservation efforts and remediation activities.</li></ul><p>Here are some quotes shared by participants about their experience and what they took away from AI Build Together:</p><p>“I loved the AI Build Together event! It was fantastic to be able to ideate with like-minded individuals who are also passionate about education. Having recently transitioned from education to software engineering, this event provided me with the chance to not only explore the possibilities of AI but also to connect with and learn from senior engineers.” — Alex McKean, Software Engineer, Self-employed</p><p>“It exemplified community really well. People had a task to focus on, groups of people had an opportunity to collaborate and meet new people in a small group setting, it was fun and left a positive impression on all.” — Nuri Halperin, Owner, Plus N Consulting</p><p>“This event really helped take a lot of the technical, theoretical and ‘magic’ of what you can do with MongoDB and AI that we had all been learning about at the .local and made it much more real. I will definitely use the experience to try my hand at building out an app, and keep on hacking!” — Justin Jenkins, Software Development Engineer 3, Pushpay</p><h3>Takeaways</h3><p>AI Build Together was a great way to bring together people from different backgrounds to explore and brainstorm the future of AI in different disciplines. The creative ideas and solutions that came about during the event emphasized the potential of AI to significantly improve the lives of people around the world and the importance of interdisciplinary collaboration to build responsible AI systems. We hope to bring AI Build Together to more cities across the world. To find MongoDB developer events near you, check our <a href="https://www.mongodb.com/developer/events/?utm_campaign=devrel&amp;utm_source=community&amp;utm_medium=medium&amp;utm_content=aibt-local-nyc-recap&amp;utm_term=apoorva.joshi">events page.</a></p><p>This event would not have been possible without our partners and experts, so huge shoutouts go to <a href="https://www.linkedin.com/in/amanberkeley/">Aman Khan</a>, <a href="https://www.linkedin.com/in/adzane/">Andrew Zane</a>, <a href="https://www.linkedin.com/in/nutlope/">Hassan El Mghari</a>, <a href="https://www.linkedin.com/in/igor-alekseev-b6425835/">Igor Alekseev</a>, <a href="https://www.linkedin.com/in/jerry-liu-64390071/">Jerry Liu</a>, <a href="https://www.linkedin.com/in/johnwillisatlanta/">John Willis</a>, <a href="https://www.linkedin.com/in/kyle-mongiello-168843249/">Kyle Mongiello</a>, <a href="https://www.linkedin.com/in/nikhil-smotra/">Nikhil Smotra</a> and <a href="https://www.linkedin.com/in/patrickdebois/">Patrick Debois</a> for participating in the event and for their continued partnership.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de080ab8355f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/ai-build-together-sneak-peek-into-mongodb-local-nycs-ai-afterparty-de080ab8355f">AI Build Together — Sneak peek into MongoDB.local NYC’s AI afterparty</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>