You can use any embedding model to power your AI apps with MongoDB Atlas, including OpenAI, Cohere, and Bedrock.
Here we give an example with OpenAI. Note that you will need to have credits added in your OpenAI account to continue. This code sample will use <$0.05 credits.
Create an OpenAI Account and API Key: https://platform.openai.com/api-keys
Add credits if you don’t have any: https://platform.openai.com/account/billing/overview
Store your API key with your MongoDB Atlas URI and other environment keys. The best practice is to store them as environment variables.
Import OpenAI Libraries:
pip install --upgrade langchain langchain-mongodb langchain-openai pymongo pypdf
Code Sample:
import pymongo, pprint
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_mongodb import MongoDBAtlasVectorSearch
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
uri = <your connection string>
# Create a new client and connect to the server
client = MongoClient(uri, server_api=ServerApi('1'))
# Initialize embeddings
OPENAI_API_KEY = <your open ai key>
embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)