mirror of
https://github.com/hwchase17/langchain.git
synced 2025-08-10 21:35:08 +00:00
RAG template for MongoDB Atlas Vector Search (#12526)
This commit is contained in:
parent
13b89815a3
commit
26f0ca222d
21
templates/rag-mongo/LICENSE
Normal file
21
templates/rag-mongo/LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 LangChain, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
17
templates/rag-mongo/README.md
Normal file
17
templates/rag-mongo/README.md
Normal file
@ -0,0 +1,17 @@
|
||||
# RAG Mongoß
|
||||
|
||||
This template performs RAG using MongoDB and OpenAI.
|
||||
|
||||
See [this notebook](https://colab.research.google.com/drive/1cr2HBAHyBmwKUerJq2if0JaNhy-hIq7I#scrollTo=TZp7_CBfxTOB) for additional context.
|
||||
|
||||
## Mongo
|
||||
|
||||
This template connects to MongoDB Atlas Vector Search.
|
||||
|
||||
Be sure that you have set a few env variables in `chain.py`:
|
||||
|
||||
* `MONGO_URI`
|
||||
|
||||
## LLM
|
||||
|
||||
Be sure that `OPENAI_API_KEY` is set in order to the OpenAI models.
|
2296
templates/rag-mongo/poetry.lock
generated
Normal file
2296
templates/rag-mongo/poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
templates/rag-mongo/pyproject.toml
Normal file
21
templates/rag-mongo/pyproject.toml
Normal file
@ -0,0 +1,21 @@
|
||||
[tool.poetry]
|
||||
name = "rag-mongo"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["Lance Martin <lance@langchain.dev>"]
|
||||
readme = "README.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.8.1,<4.0"
|
||||
langchain = ">=0.0.313, <0.1"
|
||||
openai = ">=0.28.1"
|
||||
tiktoken = ">=0.5.1"
|
||||
pymongo = ">=4.5.0"
|
||||
|
||||
[tool.langserve]
|
||||
export_module = "rag_mongo"
|
||||
export_attr = "chain"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
52
templates/rag-mongo/rag_mongo.ipynb
Normal file
52
templates/rag-mongo/rag_mongo.ipynb
Normal file
@ -0,0 +1,52 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"id": "681a5d1e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Connect to template\n",
|
||||
"\n",
|
||||
"In `server.py`, set -\n",
|
||||
"```\n",
|
||||
"add_routes(app, chain_ext, path=\"/rag_mongo\")\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d774be2a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langserve.client import RemoteRunnable\n",
|
||||
"\n",
|
||||
"rag_app_pinecone = RemoteRunnable(\"http://0.0.0.0:8001/rag_mongo\")\n",
|
||||
"rag_app_pinecone.invoke(\"How does agent memory work?\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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.9.16"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
3
templates/rag-mongo/rag_mongo/__init__.py
Normal file
3
templates/rag-mongo/rag_mongo/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from rag_mongo.chain import chain
|
||||
|
||||
__all__ = ["chain"]
|
79
templates/rag-mongo/rag_mongo/chain.py
Normal file
79
templates/rag-mongo/rag_mongo/chain.py
Normal file
@ -0,0 +1,79 @@
|
||||
import os
|
||||
|
||||
from langchain.chat_models import ChatOpenAI
|
||||
from langchain.embeddings import OpenAIEmbeddings
|
||||
from langchain.prompts import ChatPromptTemplate
|
||||
from langchain.pydantic_v1 import BaseModel
|
||||
from langchain.schema.output_parser import StrOutputParser
|
||||
from langchain.schema.runnable import RunnableParallel, RunnablePassthrough
|
||||
from langchain.vectorstores import MongoDBAtlasVectorSearch
|
||||
from pymongo import MongoClient
|
||||
|
||||
# Set DB
|
||||
if os.environ.get("MONGO_URI", None) is None:
|
||||
raise Exception("Missing `MONGO_URI` environment variable.")
|
||||
MONGO_URI = os.environ["MONGO_URI"]
|
||||
|
||||
DB_NAME = "langchain-test-2"
|
||||
COLLECTION_NAME = "test"
|
||||
ATLAS_VECTOR_SEARCH_INDEX_NAME = "default"
|
||||
|
||||
client = MongoClient(MONGO_URI)
|
||||
db = client[DB_NAME]
|
||||
MONGODB_COLLECTION = db[COLLECTION_NAME]
|
||||
|
||||
### Ingest code - you may need to run this the first time
|
||||
"""
|
||||
# Load
|
||||
from langchain.document_loaders import WebBaseLoader
|
||||
loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
|
||||
data = loader.load()
|
||||
|
||||
# Split
|
||||
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
|
||||
all_splits = text_splitter.split_documents(data)
|
||||
|
||||
# Add to vectorDB
|
||||
# Insert the documents in MongoDB Atlas Vector Search
|
||||
vectorstore = MongoDBAtlasVectorSearch.from_documents(
|
||||
documents=all_splits,
|
||||
embedding=OpenAIEmbeddings(disallowed_special=()),
|
||||
collection=MONGODB_COLLECTION,
|
||||
index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME
|
||||
)
|
||||
retriever = vectorstore.as_retriever()
|
||||
"""
|
||||
|
||||
# Read from MongoDB Atlas Vector Search
|
||||
vectorstore = MongoDBAtlasVectorSearch.from_connection_string(
|
||||
MONGO_URI,
|
||||
DB_NAME + "." + COLLECTION_NAME,
|
||||
OpenAIEmbeddings(disallowed_special=()),
|
||||
index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
|
||||
)
|
||||
retriever = vectorstore.as_retriever()
|
||||
|
||||
# RAG prompt
|
||||
template = """Answer the question based only on the following context:
|
||||
{context}
|
||||
Question: {question}
|
||||
"""
|
||||
prompt = ChatPromptTemplate.from_template(template)
|
||||
|
||||
# RAG
|
||||
model = ChatOpenAI()
|
||||
chain = (
|
||||
RunnableParallel({"context": retriever, "question": RunnablePassthrough()})
|
||||
| prompt
|
||||
| model
|
||||
| StrOutputParser()
|
||||
)
|
||||
|
||||
|
||||
# Add typing for input
|
||||
class Question(BaseModel):
|
||||
__root__: str
|
||||
|
||||
|
||||
chain = chain.with_types(input_type=Question)
|
0
templates/rag-mongo/tests/__init__.py
Normal file
0
templates/rag-mongo/tests/__init__.py
Normal file
Loading…
Reference in New Issue
Block a user