You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
langchain/docs/docs/integrations/vectorstores/mongodb_atlas.ipynb

439 lines
12 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "683953b3",
"metadata": {},
"source": [
"# MongoDB Atlas\n",
"\n",
">[MongoDB Atlas](https://www.mongodb.com/docs/atlas/) is a fully-managed cloud database available in AWS, Azure, and GCP. It now has support for native Vector Search on your MongoDB document data.\n",
"\n",
"This notebook shows how to use [MongoDB Atlas Vector Search](https://www.mongodb.com/products/platform/atlas-vector-search) to store your embeddings in MongoDB documents, create a vector search index, and perform KNN search with an approximate nearest neighbor algorithm (`Hierarchical Navigable Small Worlds`). It uses the [$vectorSearch MQL Stage](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-overview/). \n",
"\n",
"\n",
"To use MongoDB Atlas, you must first deploy a cluster. We have a Forever-Free tier of clusters available. To get started head over to Atlas here: [quick start](https://www.mongodb.com/docs/atlas/getting-started/).\n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"id": "5abfec15",
"metadata": {},
"source": [
"> Note: \n",
">\n",
">* This feature is Generally Available and ready for production deployments.\n",
">* The langchain version 0.0.305 ([release notes](https://github.com/langchain-ai/langchain/releases/tag/v0.0.305)) introduces the support for $vectorSearch MQL stage, which is available with MongoDB Atlas 6.0.11 and 7.0.2. Users utilizing earlier versions of MongoDB Atlas need to pin their LangChain version to <=0.0.304\n",
"> \n",
"> "
]
},
{
"cell_type": "markdown",
"id": "1b5ce18d",
"metadata": {},
"source": [
"In the notebook we will demonstrate how to perform `Retrieval Augmented Generation` (RAG) using MongoDB Atlas, OpenAI and Langchain. We will be performing Similarity Search, Similarity Search with Metadata Pre-Filtering, and Question Answering over the PDF document for [GPT 4 technical report](https://arxiv.org/pdf/2303.08774.pdf) that came out in March 2023 and hence is not part of the OpenAI's Large Language Model(LLM)'s parametric memory, which had a knowledge cutoff of September 2021."
]
},
{
"cell_type": "markdown",
"id": "457ace44-1d95-4001-9dd5-78811ab208ad",
"metadata": {},
"source": [
"We want to use `OpenAIEmbeddings` so we need to set up our OpenAI API Key. "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2d8f240d",
"metadata": {},
"outputs": [],
"source": [
"import getpass\n",
"import os\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"
]
},
{
"cell_type": "markdown",
"id": "70482cd8",
"metadata": {},
"source": [
"Now we will setup the environment variables for the MongoDB Atlas cluster"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4d7788cf",
"metadata": {},
"outputs": [],
"source": [
"%pip install --upgrade --quiet langchain pypdf pymongo langchain-openai tiktoken"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7ef41b37",
"metadata": {},
"outputs": [],
"source": [
"import getpass\n",
"\n",
"MONGODB_ATLAS_CLUSTER_URI = getpass.getpass(\"MongoDB Atlas Cluster URI:\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "00d78318",
"metadata": {},
"outputs": [],
"source": [
"from pymongo import MongoClient\n",
"\n",
"# initialize MongoDB python client\n",
"client = MongoClient(MONGODB_ATLAS_CLUSTER_URI)\n",
"\n",
"DB_NAME = \"langchain_db\"\n",
"COLLECTION_NAME = \"test\"\n",
"ATLAS_VECTOR_SEARCH_INDEX_NAME = \"index_name\"\n",
"\n",
"MONGODB_COLLECTION = client[DB_NAME][COLLECTION_NAME]"
]
},
{
"cell_type": "markdown",
"id": "eb0cc10f-b84e-4e5e-b445-eb61f10bf085",
"metadata": {},
"source": [
"## Create Vector Search Index"
]
},
{
"cell_type": "markdown",
"id": "1f3ecc42",
"metadata": {},
"source": [
"Now, let's create a vector search index on your cluster. In the below example, `embedding` is the name of the field that contains the embedding vector. Please refer to the [documentation](https://www.mongodb.com/docs/atlas/atlas-vector-search/create-index/) to get more details on how to define an Atlas Vector Search index.\n",
"You can name the index `{ATLAS_VECTOR_SEARCH_INDEX_NAME}` and create the index on the namespace `{DB_NAME}.{COLLECTION_NAME}`. Finally, write the following definition in the JSON editor on MongoDB Atlas:\n",
"\n",
"```json\n",
"{\n",
" \"name\": \"index_name\",\n",
" \"type\": \"vectorSearch\",\n",
" \"fields\":[\n",
" {\n",
" \"type\": \"vector\",\n",
" \"path\": \"embedding\",\n",
" \"numDimensions\": 1536,\n",
" \"similarity\": \"cosine\"\n",
" }\n",
" ]\n",
"}\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "42873e5a",
"metadata": {},
"source": [
"# Insert Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aac9563e",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain_community.document_loaders import PyPDFLoader\n",
"\n",
"# Load the PDF\n",
"loader = PyPDFLoader(\"https://arxiv.org/pdf/2303.08774.pdf\")\n",
"data = loader.load()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a5578113",
"metadata": {},
"outputs": [],
"source": [
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
"\n",
"text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)\n",
"docs = text_splitter.split_documents(data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d378168f",
"metadata": {},
"outputs": [],
"source": [
"print(docs[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6e104aee",
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.vectorstores import MongoDBAtlasVectorSearch\n",
"from langchain_openai import OpenAIEmbeddings\n",
"\n",
"# insert the documents in MongoDB Atlas with their embedding\n",
"vector_search = MongoDBAtlasVectorSearch.from_documents(\n",
" documents=docs,\n",
" embedding=OpenAIEmbeddings(disallowed_special=()),\n",
" collection=MONGODB_COLLECTION,\n",
" index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7bf6841e",
"metadata": {},
"outputs": [],
"source": [
"# Perform a similarity search between the embedding of the query and the embeddings of the documents\n",
"query = \"What were the compute requirements for training GPT 4\"\n",
"results = vector_search.similarity_search(query)\n",
"\n",
"print(results[0].page_content)"
]
},
{
"cell_type": "markdown",
"id": "9e58c2d8",
"metadata": {},
"source": [
"# Querying data"
]
},
{
"cell_type": "markdown",
"id": "851a2ec9-9390-49a4-8412-3e132c9f789d",
"metadata": {},
"source": [
"We can also instantiate the vector store directly and execute a query as follows:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "985d28fe",
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.vectorstores import MongoDBAtlasVectorSearch\n",
"from langchain_openai import OpenAIEmbeddings\n",
"\n",
"vector_search = MongoDBAtlasVectorSearch.from_connection_string(\n",
" MONGODB_ATLAS_CLUSTER_URI,\n",
" DB_NAME + \".\" + COLLECTION_NAME,\n",
" OpenAIEmbeddings(disallowed_special=()),\n",
" index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "02aef29c-5da0-41b8-b4fc-98fd71b94abf",
"metadata": {},
"source": [
"## Pre-filtering with Similarity Search"
]
},
{
"cell_type": "markdown",
"id": "f3b2d36d-d47a-482f-999d-85c23eb67eed",
"metadata": {},
"source": [
"Atlas Vector Search supports pre-filtering using MQL Operators for filtering. Below is an example index and query on the same data loaded above that allows you do metadata filtering on the \"page\" field. You can update your existing index with the filter defined and do pre-filtering with vector search."
]
},
{
"cell_type": "markdown",
"id": "2b385a46-1e54-471f-95b2-202813d90bb2",
"metadata": {},
"source": [
"```json\n",
"{\n",
" \"name\": \"index_name\",\n",
" \"type\": \"vectorSearch\",\n",
" \"fields\":[\n",
" {\n",
" \"type\": \"vector\",\n",
" \"path\": \"embedding\",\n",
" \"numDimensions\": 1536,\n",
" \"similarity\": \"cosine\"\n",
" },\n",
" {\n",
" \"type\": \"filter\",\n",
" \"path\": \"page\"\n",
" }\n",
" ]\n",
"}\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dfc8487d-14ec-42c9-9670-80fe02816196",
"metadata": {},
"outputs": [],
"source": [
"query = \"What were the compute requirements for training GPT 4\"\n",
"\n",
"results = vector_search.similarity_search_with_score(\n",
" query=query, k=5, pre_filter={\"page\": {\"$eq\": 1}}\n",
")\n",
"\n",
"# Display results\n",
"for result in results:\n",
" print(result)"
]
},
{
"cell_type": "markdown",
"id": "6d9a2dbe",
"metadata": {},
"source": [
"## Similarity Search with Score"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "497baffa",
"metadata": {},
"outputs": [],
"source": [
"query = \"What were the compute requirements for training GPT 4\"\n",
"\n",
"results = vector_search.similarity_search_with_score(\n",
" query=query,\n",
" k=5,\n",
")\n",
"\n",
"# Display results\n",
"for result in results:\n",
" print(result)"
]
},
{
"cell_type": "markdown",
"id": "cbade5f0",
"metadata": {},
"source": [
"## Question Answering "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bc6475f9",
"metadata": {},
"outputs": [],
"source": [
"qa_retriever = vector_search.as_retriever(\n",
" search_type=\"similarity\",\n",
" search_kwargs={\"k\": 25},\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8e13e96c",
"metadata": {},
"outputs": [],
"source": [
"from langchain.prompts import PromptTemplate\n",
"\n",
"prompt_template = \"\"\"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n",
"\n",
"{context}\n",
"\n",
"Question: {question}\n",
"\"\"\"\n",
"PROMPT = PromptTemplate(\n",
" template=prompt_template, input_variables=[\"context\", \"question\"]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff0edb02",
"metadata": {},
"outputs": [],
"source": [
"from langchain.chains import RetrievalQA\n",
"from langchain_openai import OpenAI\n",
"\n",
"qa = RetrievalQA.from_chain_type(\n",
" llm=OpenAI(),\n",
" chain_type=\"stuff\",\n",
" retriever=qa_retriever,\n",
" return_source_documents=True,\n",
" chain_type_kwargs={\"prompt\": PROMPT},\n",
")\n",
"\n",
"docs = qa({\"query\": \"gpt-4 compute requirements\"})\n",
"\n",
"print(docs[\"result\"])\n",
"print(docs[\"source_documents\"])"
]
},
{
"cell_type": "markdown",
"id": "61636bb2",
"metadata": {},
"source": [
"GPT-4 requires significantly more compute than earlier GPT models. On a dataset derived from OpenAI's internal codebase, GPT-4 requires 100p (petaflops) of compute to reach the lowest loss, while the smaller models require 1-10n (nanoflops)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}