Introduction
Retrieval augmented generation (RAG) is a pattern that combines a large-scale language model (LM) with a retrieval system to generate natural language responses that are relevant, diverse, and informative. The retrieval system can be a vector database that stores pre-computed embeddings of documents or passages that can be efficiently searched by similarity. In a previous article, we discussed the importance of RAG patterns in modern LM-based generative AI applications and highlighted some of the options that are available in Azure that can be used for RAG components. In this article, we will focus on one of the options, Azure Cosmos DB for Mongo DB vCore, and show how it can be used as a vector database for RAG. We will also provide some sample code to demonstrate how to store and query embeddings using Azure Cosmos DB for Mongo DB vCore.
What is a Vector Database?
Here are some key points about vector databases:
- Vector Search: Vector databases enable efficient similarity search based on vector representations.
- Retrieval-Augmented Generation (RAG): An increasingly popular use case involves integrating vector databases with LLMs to generate contextually relevant and accurate responses to user prompts. This approach overcomes token limits and reduces the need for frequent fine-tuning of updated data.
What is vector search?
Vector search lets you find items that are similar in meaning or content, not just by matching a specific field. This can help you with tasks like searching for related text, finding images that match a theme, making suggestions, or spotting outliers. To do a vector search, you need to use a machine-learning model that turns your data into vectors (lists of numbers) that capture their features. This is done by using an embeddings API, such as Azure OpenAI Embeddings or Hugging Face on Azure. Then, you compare the distance between the vectors of your data and the vector of your query. The closer the vectors are, the more similar the data is to your query.
With native vector search support, you can make the most of your data in applications that use the OpenAI API. You can also build your own solutions that use vector embeddings.
Vector Database /Index option in Azure.
Service | Description |
Azure Cosmos DB for Mongo DB vCore | Store your application data and vector embeddings together in a single MongoDB-compatible service featuring native support for vector search. |
Azure Cosmos DB for PostgreSQL | Store your data and vectors together in a scalable PostgreSQL offering with native support for vector search. |
Azure Cosmos DB for NoSQL with Azure AI Search | Augment your Azure Cosmos DB data with the semantic and vector search capabilities of Azure AI Search. |
- Azure Cosmos DB Vector Database Extension for MongoDB vCore:
- Store your application data and vector embeddings together in a single MongoDB-compatible service.
- Benefit from native support for vector search.
- Avoid the extra cost of moving data to a separate vector database.
- Achieve data consistency, scale, and performance.
- Learn more1.
- Azure Cosmos DB Vector Database Extension for PostgreSQL:
- Store your data and vectors together in a scalable PostgreSQL offering.
- Leverage native support for vector search.
- Seamlessly integrate vector capabilities without additional database migration costs.
- Learn more1.
Azure Cosmos DB for NoSQL with Azure AI Search:- Augment your Azure Cosmos DB data with semantic and vector search capabilities.
- Combine the power of NoSQL with AI-driven search.
- Enhance retrieval-augmented generation scenarios.
- Learn more2.
Remember, vector databases play a crucial role in harnessing the potential of vector embeddings, enabling advanced search, and enhancing AI-driven applications. Choose the option that best aligns with your specific use case and requirements! 🚀
A simple and effective way to store, index, and search vector data in Azure Cosmos DB for MongoDB vCore is to use the built-in vector search feature. This feature allows you to perform similarity searches on arrays of numbers, such as embeddings, using MongoDB's $vector query operator. By using this feature, you can avoid the need to move your data to more expensive vector databases and integrate your AI-driven applications smoothly with your other data.
What is Azure Cosmos DB for Mongo DB v Core?
Azure Cosmos DB for Mongo DB vCore is a fully managed, scalable, and secure service that provides API compatibility with MongoDB. It allows you to use the familiar MongoDB tools and drivers to build applications that can leverage the benefits of Azure Cosmos DB, such as global distribution, automatic scaling, and SLA-backed availability and latency. Azure Cosmos DB for Mongo DB vCore also supports MongoDB's aggregation pipeline, which enables complex queries and transformations on the data. One of the features that makes Azure Cosmos DB for Mongo DB vCore suitable for RAG is the support for MongoDB's $vector query operator, which allows you to perform similarity searches on arrays of numbers, such as embeddings.RAG Pipeline Process
- Load Datastore
- Clean data
- Chunking Data
- Convert Chunks into vector embedding with LLM
- Create a Vector Index with Converted vector embeddings.
How to use Azure Cosmos DB for Mongo DB vCore as a vector database for RAG?
To use Azure Cosmos DB for Mongo DB vCore as a vector database for RAG, you need to follow these steps:
- Create an Azure Cosmos DB account with API for MongoDB and select the vCore model. You can choose the number of regions, availability zones, and throughput depending on your needs. You can also enable features such as geo-fencing, encryption at rest, and role-based access control.
- Create a database and a collection in your Azure Cosmos DB account. You can use any schema and indexing strategy that suits your application, but you need to ensure that the field that stores the embeddings is indexed as an array. You can use the MongoDB shell or any MongoDB driver to connect to your Azure Cosmos DB account and create the database and collection.
- Populate your collection with documents that contain the embeddings and any other metadata that you need for your RAG application. You can use any method to generate the embeddings, such as a pre-trained model or a custom model. You can also use any format to store the embeddings, such as a list or a base64-encoded string. You can use the MongoDB shell or any MongoDB driver to insert the documents into your collection. Alternatively, you can use Azure Data Factory or Azure Databricks to import data from various sources into your collection.
- Query your collection using the $vector operator to perform a similarity search on the embeddings. You can use the MongoDB shell or any MongoDB driver to query your collection. The $vector operator takes an array of numbers as input and returns the documents that have the most similar arrays in the specified field. You can also use other query operators and aggregation stages to filter, sort, and project the results. You can integrate the query results with your LM to generate natural language responses that are relevant, diverse, and informative.
Here is some sample code that shows how to use Azure Cosmos DB for Mongo DB vCore as a vector database for RAG:
Preliminaries
First, let's start by installing the
packages that we'll need later.
First, let's start by installing the packages that we'll need later.
loading endpoint and secret API keys
# Take a peek at one data item
{ "id": "1", "title": "Azure App Service", "content": "Azure App Service is a fully managed platform for building, deploying, and scaling web apps. You can host web apps, mobile app backends, and RESTful APIs. It supports a variety of programming languages and frameworks, such as .NET, Java, Node.js, Python, and PHP. The service offers built-in auto-scaling and load balancing capabilities. It also provides integration with other Azure services, such as Azure DevOps, GitHub, and Bitbucket.", "category": "Web", "titleVector": [ -0.0017071267357096076, -0.01391641329973936, 0.0017036213539540768, -0.018410328775644302,
Creating
Open AI Client for Library 1.xx
Connect
and setup Cosmos DB for MongoDB vCore
Set up the connection
Set
up the DB and collection
Create
the vector index
IMPORTANT: You can only create one index
per vector property. That
is, you cannot create more than one index that points to the same vector
property. If you want to change the index type (e.g., from IVF to HNSW) you
must drop the index first before creating a new index.
IVF
IVF is the default vector indexing
algorithm, which works on all cluster tiers. It's an approximate nearest
neighbors (ANN) approach that uses clustering to speed up the search for
similar vectors in a dataset.
HNSW
(preview ) you skip this
NSW is a graph-based data structure that
organizes vectors into clusters and subclusters. It facilitates fast
approximate nearest neighbor search, achieving higher speeds with improved
accuracy. As a preview feature, you can enable HNSW using Azure Feature
Enablement Control (AFEC) by selecting the “mongoHnswIndex” feature. For
detailed instructions, refer to the enable preview features documentation.
Keep in mind that HNSW operates on M50
cluster tiers and higher while in preview. 🚀
Upload
data to the collection
A simple insert_many()
to insert our data in JSON format into the
newly created DB and collection.
Vector
Search in Cosmos DB for MongoDB vCore
Q&A
over the data with GPT-3.5
Finally, we'll create a helper function
to feed prompts into the Completions
model. Then we'll create an interactive loop where
you can pose questions to the model and receive information grounded in your
data.
Source Code GitHub https://github.com/Usamawahabkhan/Usamawahabkhan-RAG-Azure-CosmosDb-MongoDb-vcore/blob/main/AzureOpenAI-CosmosDB-MongoDB-vCore_Tutorial.ipynb
Conclusion
In this article, we have seen how to use RAG, a powerful
technique for generating natural language answers from large-scale text
corpora, with Cosmos DB for MongoDB vCore, a fully managed and scalable
database service that supports the MongoDB API. We have shown how to upload
data to the collection, create a vector index, and perform vector search using
PyMongo and Faiss. We have also discussed some of the benefits and challenges
of using RAG and Cosmos DB for MongoDB vCore for building GenAI applications based
on LLMs.
RAG is becoming an essential part of any modern GenAI app
based on LLMs, as it enables generating of high-quality and diverse responses from
multiple sources of knowledge. Storing data is crucial and requires security,
availability and scalability, where Azure Cosmos DB can be a very valuable
choice. However, there are other options available in Azure and open source,
depending on the application requirements and compliance. We encourage you to
explore different alternatives and find the one that suits your needs best.