id
stringlengths
14
15
text
stringlengths
23
2.21k
source
stringlengths
52
97
e4fa732f8a3d-5
fund� worthless. \n\nWe are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come. \n\nTonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. \n\nThe U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs. \n\nWe are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='And tonight I am announcing that we will join our allies in closing off American air space to all Russian flights – further isolating Russia – and adding an additional squeeze –on their economy. The Ruble has lost 30% of its value. \n\nThe Russian stock market has lost 40% of its value and trading remains suspended. Russia’s economy is reeling and Putin alone is to blame. \n\nTogether with our allies we are providing support to the Ukrainians in their fight for freedom. Military assistance. Economic assistance. Humanitarian assistance. \n\nWe are giving more than $1 Billion in direct assistance to Ukraine. \n\nAnd we will continue to aid the Ukrainian people as they defend their country and to help ease their suffering. \n\nLet me be clear, our forces are not engaged and will not engage in conflict with Russian forces in Ukraine. \n\nOur forces are not going to Europe to fight in Ukraine, but to defend our NATO Allies – in the event that Putin decides to keep moving west.', metadata={'source': '../../../state_of_the_union.txt'})]vector_store_from_docs = Annoy.from_documents(docs, embeddings_func)query = "What did
https://python.langchain.com/docs/integrations/vectorstores/annoy
e4fa732f8a3d-6
= Annoy.from_documents(docs, embeddings_func)query = "What did the president say about Ketanji Brown Jackson"docs = vector_store_from_docs.similarity_search(query)print(docs[0].page_content[:100]) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights AcCreate VectorStore via existing embeddings​embs = embeddings_func.embed_documents(texts)data = list(zip(texts, embs))vector_store_from_embeddings = Annoy.from_embeddings(data, embeddings_func)vector_store_from_embeddings.similarity_search_with_score("food", k=3) [(Document(page_content='pizza is great', metadata={}), 1.0944390296936035), (Document(page_content='I love salad', metadata={}), 1.1273186206817627), (Document(page_content='my car', metadata={}), 1.1580758094787598)]Search via embeddings​motorbike_emb = embeddings_func.embed_query("motorbike")vector_store.similarity_search_by_vector(motorbike_emb, k=3) [Document(page_content='my car', metadata={}), Document(page_content='a dog', metadata={}), Document(page_content='pizza is great', metadata={})]vector_store.similarity_search_with_score_by_vector(motorbike_emb, k=3) [(Document(page_content='my car', metadata={}), 1.0870471000671387), (Document(page_content='a dog', metadata={}), 1.2095637321472168), (Document(page_content='pizza is great', metadata={}), 1.3254905939102173)]Search via docstore id​vector_store.index_to_docstore_id
https://python.langchain.com/docs/integrations/vectorstores/annoy
e4fa732f8a3d-7
via docstore id​vector_store.index_to_docstore_id {0: '2d1498a8-a37c-4798-acb9-0016504ed798', 1: '2d30aecc-88e0-4469-9d51-0ef7e9858e6d', 2: '927f1120-985b-4691-b577-ad5cb42e011c', 3: '3056ddcf-a62f-48c8-bd98-b9e57a3dfcae'}some_docstore_id = 0 # texts[0]vector_store.docstore._dict[vector_store.index_to_docstore_id[some_docstore_id]] Document(page_content='pizza is great', metadata={})# same document has distance 0vector_store.similarity_search_with_score_by_index(some_docstore_id, k=3) [(Document(page_content='pizza is great', metadata={}), 0.0), (Document(page_content='I love salad', metadata={}), 1.0734446048736572), (Document(page_content='my car', metadata={}), 1.2895267009735107)]Save and load​vector_store.save_local("my_annoy_index_and_docstore") saving configloaded_vector_store = Annoy.load_local( "my_annoy_index_and_docstore", embeddings=embeddings_func)# same document has distance 0loaded_vector_store.similarity_search_with_score_by_index(some_docstore_id, k=3) [(Document(page_content='pizza is great', metadata={}), 0.0), (Document(page_content='I love salad', metadata={}),
https://python.langchain.com/docs/integrations/vectorstores/annoy
e4fa732f8a3d-8
(Document(page_content='I love salad', metadata={}), 1.0734446048736572), (Document(page_content='my car', metadata={}), 1.2895267009735107)]Construct from scratch​import uuidfrom annoy import AnnoyIndexfrom langchain.docstore.document import Documentfrom langchain.docstore.in_memory import InMemoryDocstoremetadatas = [{"x": "food"}, {"x": "food"}, {"x": "stuff"}, {"x": "animal"}]# embeddingsembeddings = embeddings_func.embed_documents(texts)# embedding dimf = len(embeddings[0])# indexmetric = "angular"index = AnnoyIndex(f, metric=metric)for i, emb in enumerate(embeddings): index.add_item(i, emb)index.build(10)# docstoredocuments = []for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Document(page_content=text, metadata=metadata))index_to_docstore_id = {i: str(uuid.uuid4()) for i in range(len(documents))}docstore = InMemoryDocstore( {index_to_docstore_id[i]: doc for i, doc in enumerate(documents)})db_manually = Annoy( embeddings_func.embed_query, index, metric, docstore, index_to_docstore_id)db_manually.similarity_search_with_score("eating!", k=3) [(Document(page_content='pizza is great', metadata={'x': 'food'}), 1.1314140558242798), (Document(page_content='I love salad', metadata={'x': 'food'}), 1.1668788194656372),
https://python.langchain.com/docs/integrations/vectorstores/annoy
e4fa732f8a3d-9
1.1668788194656372), (Document(page_content='my car', metadata={'x': 'stuff'}), 1.226445198059082)]PreviousAnalyticDBNextAtlasCreate VectorStore from textsCreate VectorStore from docsCreate VectorStore via existing embeddingsSearch via embeddingsSearch via docstore idSave and loadConstruct from scratchCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/annoy
a96338c0351e-0
MatchingEngine | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/matchingengine
a96338c0351e-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesMatchingEngineOn this pageMatchingEngineThis notebook shows how to use functionality related to the GCP Vertex AI MatchingEngine vector database.Vertex AI Matching Engine provides the industry's leading high-scale low latency vector database. These vector databases are commonly referred to as vector similarity-matching or an approximate nearest neighbor (ANN) service.Note: This module expects an endpoint and deployed index already created as the creation time takes close to one hour. To see how to create an index refer to the section Create Index and deploy it to an EndpointCreate VectorStore from texts​from langchain.vectorstores import MatchingEnginetexts = [ "The cat sat on", "the mat.", "I like to", "eat pizza for", "dinner.", "The sun sets", "in the west.",]vector_store = MatchingEngine.from_components( texts=texts, project_id="<my_project_id>",
https://python.langchain.com/docs/integrations/vectorstores/matchingengine
a96338c0351e-2
texts=texts, project_id="<my_project_id>", region="<my_region>", gcs_bucket_uri="<my_gcs_bucket>", index_id="<my_matching_engine_index_id>", endpoint_id="<my_matching_engine_endpoint_id>",)vector_store.add_texts(texts=texts)vector_store.similarity_search("lunch", k=2)Create Index and deploy it to an Endpoint​Imports, Constants and Configs​# Installing dependencies.pip install tensorflow \ google-cloud-aiplatform \ tensorflow-hub \ tensorflow-textimport osimport jsonfrom google.cloud import aiplatformimport tensorflow_hub as hubimport tensorflow_textPROJECT_ID = "<my_project_id>"REGION = "<my_region>"VPC_NETWORK = "<my_vpc_network_name>"PEERING_RANGE_NAME = "ann-langchain-me-range" # Name for creating the VPC peering.BUCKET_URI = "gs://<bucket_uri>"# The number of dimensions for the tensorflow universal sentence encoder.# If other embedder is used, the dimensions would probably need to change.DIMENSIONS = 512DISPLAY_NAME = "index-test-name"EMBEDDING_DIR = f"{BUCKET_URI}/banana"DEPLOYED_INDEX_ID = "endpoint-test-name"PROJECT_NUMBER = !gcloud projects list --filter="PROJECT_ID:'{PROJECT_ID}'" --format='value(PROJECT_NUMBER)'PROJECT_NUMBER = PROJECT_NUMBER[0]VPC_NETWORK_FULL = f"projects/{PROJECT_NUMBER}/global/networks/{VPC_NETWORK}"# Change this if you need the VPC to be created.CREATE_VPC = False# Set the project id gcloud config set project {PROJECT_ID}# Remove the if condition to run the encapsulated codeif
https://python.langchain.com/docs/integrations/vectorstores/matchingengine
a96338c0351e-3
config set project {PROJECT_ID}# Remove the if condition to run the encapsulated codeif CREATE_VPC: # Create a VPC network gcloud compute networks create {VPC_NETWORK} --bgp-routing-mode=regional --subnet-mode=auto --project={PROJECT_ID} # Add necessary firewall rules gcloud compute firewall-rules create {VPC_NETWORK}-allow-icmp --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow icmp gcloud compute firewall-rules create {VPC_NETWORK}-allow-internal --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow all --source-ranges 10.128.0.0/9 gcloud compute firewall-rules create {VPC_NETWORK}-allow-rdp --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow tcp:3389 gcloud compute firewall-rules create {VPC_NETWORK}-allow-ssh --network {VPC_NETWORK} --priority 65534 --project {PROJECT_ID} --allow tcp:22 # Reserve IP range gcloud compute addresses create {PEERING_RANGE_NAME} --global --prefix-length=16 --network={VPC_NETWORK} --purpose=VPC_PEERING --project={PROJECT_ID} --description="peering range" # Set up peering with service networking # Your account must have the "Compute Network Admin" role to run the following. gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com --network={VPC_NETWORK} --ranges={PEERING_RANGE_NAME} --project={PROJECT_ID}# Creating bucket. gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URIUsing Tensorflow Universal Sentence Encoder as an Embedder​# Load the Universal Sentence Encoder modulemodule_url =
https://python.langchain.com/docs/integrations/vectorstores/matchingengine
a96338c0351e-4
Sentence Encoder as an Embedder​# Load the Universal Sentence Encoder modulemodule_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"model = hub.load(module_url)# Generate embeddings for each wordembeddings = model(["banana"])Inserting a test embedding​initial_config = { "id": "banana_id", "embedding": [float(x) for x in list(embeddings.numpy()[0])],}with open("data.json", "w") as f: json.dump(initial_config, f)gsutil cp data.json {EMBEDDING_DIR}/file.jsonaiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)Creating Index​my_index = aiplatform.MatchingEngineIndex.create_tree_ah_index( display_name=DISPLAY_NAME, contents_delta_uri=EMBEDDING_DIR, dimensions=DIMENSIONS, approximate_neighbors_count=150, distance_measure_type="DOT_PRODUCT_DISTANCE",)Creating Endpoint​my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create( display_name=f"{DISPLAY_NAME}-endpoint", network=VPC_NETWORK_FULL,)Deploy Index​my_index_endpoint = my_index_endpoint.deploy_index( index=my_index, deployed_index_id=DEPLOYED_INDEX_ID)my_index_endpoint.deployed_indexesPreviousMarqoNextMilvusCreate VectorStore from textsCreate Index and deploy it to an EndpointImports, Constants and ConfigsUsing Tensorflow Universal Sentence Encoder as an EmbedderInserting a test embeddingCreating IndexCreating EndpointDeploy IndexCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/matchingengine
72d7a3a288b7-0
SingleStoreDB | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/singlestoredb
72d7a3a288b7-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesSingleStoreDBSingleStoreDBSingleStoreDB is a high-performance distributed SQL database that supports deployment both in the cloud and on-premises. It provides vector storage, and vector functions including dot_product and euclidean_distance, thereby supporting AI applications that require text similarity matching. This tutorial illustrates how to work with vector data in SingleStoreDB.# Establishing a connection to the database is facilitated through the singlestoredb Python connector.# Please ensure that this connector is installed in your working environment.pip install singlestoredbimport osimport getpass# We want to use OpenAIEmbeddings so we have to get the OpenAI API Key.os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import SingleStoreDBfrom langchain.document_loaders import TextLoader# Load text samplesloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter =
https://python.langchain.com/docs/integrations/vectorstores/singlestoredb
72d7a3a288b7-2
= TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()There are several ways to establish a connection to the database. You can either set up environment variables or pass named parameters to the SingleStoreDB constructor. Alternatively, you may provide these parameters to the from_documents and from_texts methods.# Setup connection url as environment variableos.environ["SINGLESTOREDB_URL"] = "root:pass@localhost:3306/db"# Load documents to the storedocsearch = SingleStoreDB.from_documents( docs, embeddings, table_name="notebook", # use table with a custom name)query = "What did the president say about Ketanji Brown Jackson"docs = docsearch.similarity_search(query) # Find documents that correspond to the queryprint(docs[0].page_content)PreviousRocksetNextscikit-learnCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/singlestoredb
d284632beb03-0
Activeloop's Deep Lake | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesActiveloop's Deep LakeOn this pageActiveloop's Deep LakeActiveloop's Deep Lake as a Multi-Modal Vector Store that stores embeddings and their metadata including text, jsons, images, audio, video, and more. It saves the data locally, in your cloud, or on Activeloop storage. It performs hybrid search including embeddings and their attributes.This notebook showcases basic functionality related to Activeloop's Deep Lake. While Deep Lake can store embeddings, it is capable of storing any type of data. It is a serverless data lake with version control, query engine and streaming dataloaders to deep learning frameworks. For more information, please see the Deep Lake documentation or api referencepip install openai 'deeplake[enterprise]' tiktokenfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import DeepLakeimport osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-2
getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")activeloop_token = getpass.getpass("activeloop token:")embeddings = OpenAIEmbeddings()from langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()Create a dataset locally at ./deeplake/, then run similarity search. The Deeplake+LangChain integration uses Deep Lake datasets under the hood, so dataset and vector store are used interchangeably. To create a dataset in your own cloud, or in the Deep Lake storage, adjust the path accordingly.db = DeepLake( dataset_path="./my_deeplake/", embedding_function=embeddings, overwrite=True)db.add_documents(docs)# or shorter# db = DeepLake.from_documents(docs, dataset_path="./my_deeplake/", embedding=embeddings, overwrite=True)query = "What did the president say about Ketanji Brown Jackson"docs = db.similarity_search(query)print(docs[0].page_content)Later, you can reload the dataset without recomputing embeddingsdb = DeepLake( dataset_path="./my_deeplake/", embedding_function=embeddings, read_only=True)docs = db.similarity_search(query)Deep Lake, for now, is single writer and multiple reader. Setting read_only=True helps to avoid acquiring the writer lock.Retrieval Question/Answering​from langchain.chains import RetrievalQAfrom langchain.llms import OpenAIChatqa = RetrievalQA.from_chain_type( llm=OpenAIChat(model="gpt-3.5-turbo"), chain_type="stuff",
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-3
chain_type="stuff", retriever=db.as_retriever(),)query = "What did the president say about Ketanji Brown Jackson"qa.run(query)Attribute based filtering in metadata​Let's create another vector store containing metadata with the year the documents were created.import randomfor d in docs: d.metadata["year"] = random.randint(2012, 2014)db = DeepLake.from_documents( docs, embeddings, dataset_path="./my_deeplake/", overwrite=True)db.similarity_search( "What did the president say about Ketanji Brown Jackson", filter={"metadata": {"year": 2013}},)Choosing distance function​Distance function L2 for Euclidean, L1 for Nuclear, Max l-infinity distance, cos for cosine similarity, dot for dot product db.similarity_search( "What did the president say about Ketanji Brown Jackson?", distance_metric="cos")Maximal Marginal relevance​Using maximal marginal relevancedb.max_marginal_relevance_search( "What did the president say about Ketanji Brown Jackson?")Delete dataset​db.delete_dataset() and if delete fails you can also force deleteDeepLake.force_delete_by_path("./my_deeplake") Deep Lake datasets on cloud (Activeloop, AWS, GCS, etc.) or in memory​By default, Deep Lake datasets are stored locally. To store them in memory, in the Deep Lake Managed DB, or in any object storage, you can provide the corresponding path and credentials when creating the vector store. Some paths require registration with Activeloop and creation of an API token that can be retrieved hereos.environ["ACTIVELOOP_TOKEN"] = activeloop_token# Embed and store the textsusername = "<username>"
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-4
= activeloop_token# Embed and store the textsusername = "<username>" # your username on app.activeloop.aidataset_path = f"hub://{username}/langchain_testing_python" # could be also ./local/path (much faster locally), s3://bucket/path/to/dataset, gcs://path/to/dataset, etc.docs = text_splitter.split_documents(documents)embedding = OpenAIEmbeddings()db = DeepLake(dataset_path=dataset_path, embedding_function=embeddings, overwrite=True)db.add_documents(docs)query = "What did the president say about Ketanji Brown Jackson"docs = db.similarity_search(query)print(docs[0].page_content)tensor_db execution option​In order to utilize Deep Lake's Managed Tensor Database, it is necessary to specify the runtime parameter as {'tensor_db': True} during the creation of the vector store. This configuration enables the execution of queries on the Managed Tensor Database, rather than on the client side. It should be noted that this functionality is not applicable to datasets stored locally or in-memory. In the event that a vector store has already been created outside of the Managed Tensor Database, it is possible to transfer it to the Managed Tensor Database by following the prescribed steps.# Embed and store the textsusername = "adilkhan" # your username on app.activeloop.aidataset_path = f"hub://{username}/langchain_testing"docs = text_splitter.split_documents(documents)embedding = OpenAIEmbeddings()db = DeepLake( dataset_path=dataset_path, embedding_function=embeddings, overwrite=True, runtime={"tensor_db": True},)db.add_documents(docs)TQL Search​Furthermore, the execution of queries is also supported within the similarity_search method, whereby the query can be specified utilizing Deep Lake's Tensor Query Language (TQL).search_id =
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-5
whereby the query can be specified utilizing Deep Lake's Tensor Query Language (TQL).search_id = db.vectorstore.dataset.id[0].numpy()docs = db.similarity_search( query=None, tql_query=f"SELECT * WHERE id == '{search_id[0]}'",)docsCreating vector stores on AWS S3​dataset_path = f"s3://BUCKET/langchain_test" # could be also ./local/path (much faster locally), hub://bucket/path/to/dataset, gcs://path/to/dataset, etc.embedding = OpenAIEmbeddings()db = DeepLake.from_documents( docs, dataset_path=dataset_path, embedding=embeddings, overwrite=True, creds={ "aws_access_key_id": os.environ["AWS_ACCESS_KEY_ID"], "aws_secret_access_key": os.environ["AWS_SECRET_ACCESS_KEY"], "aws_session_token": os.environ["AWS_SESSION_TOKEN"], # Optional },) s3://hub-2.0-datasets-n/langchain_test loaded successfully. Evaluating ingest: 100%|██████████| 1/1 [00:10<00:00 \ Dataset(path='s3://hub-2.0-datasets-n/langchain_test', tensors=['embedding', 'ids', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- ------- -------
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-6
dtype compression ------- ------- ------- ------- ------- embedding generic (4, 1536) float32 None ids text (4, 1) str None metadata json (4, 1) str None text text (4, 1) str None Deep Lake API​you can access the Deep Lake dataset at db.vectorstore# get structure of the datasetdb.vectorstore.summary() Dataset(path='hub://adilkhan/langchain_testing', tensors=['embedding', 'id', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- ------- ------- ------- embedding embedding (42, 1536) float32 None id text (42, 1) str None metadata json (42, 1) str None text text (42, 1) str
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-7
text (42, 1) str None # get embeddings numpy arrayembeds = db.vectorstore.dataset.embedding.numpy()Transfer local dataset to cloud​Copy already created dataset to the cloud. You can also transfer from cloud to local.import deeplakeusername = "davitbun" # your username on app.activeloop.aisource = f"hub://{username}/langchain_test" # could be local, s3, gcs, etc.destination = f"hub://{username}/langchain_test_copy" # could be local, s3, gcs, etc.deeplake.deepcopy(src=source, dest=destination, overwrite=True) Copying dataset: 100%|██████████| 56/56 [00:38<00:00 This dataset can be visualized in Jupyter Notebook by ds.visualize() or at https://app.activeloop.ai/davitbun/langchain_test_copy Your Deep Lake dataset has been successfully created! The dataset is private so make sure you are logged in! Dataset(path='hub://davitbun/langchain_test_copy', tensors=['embedding', 'ids', 'metadata', 'text'])db = DeepLake(dataset_path=destination, embedding_function=embeddings)db.add_documents(docs) This dataset can be visualized in Jupyter Notebook by ds.visualize() or at https://app.activeloop.ai/davitbun/langchain_test_copy / hub://davitbun/langchain_test_copy loaded successfully.
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-8
/ hub://davitbun/langchain_test_copy loaded successfully. Deep Lake Dataset in hub://davitbun/langchain_test_copy already exists, loading from the storage Dataset(path='hub://davitbun/langchain_test_copy', tensors=['embedding', 'ids', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- ------- ------- ------- embedding generic (4, 1536) float32 None ids text (4, 1) str None metadata json (4, 1) str None text text (4, 1) str None Evaluating ingest: 100%|██████████| 1/1 [00:31<00:00 - Dataset(path='hub://davitbun/langchain_test_copy', tensors=['embedding', 'ids', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- ------- ------- -------
https://python.langchain.com/docs/integrations/vectorstores/deeplake
d284632beb03-9
------- ------- ------- ------- ------- embedding generic (8, 1536) float32 None ids text (8, 1) str None metadata json (8, 1) str None text text (8, 1) str None ['ad42f3fe-e188-11ed-b66d-41c5f7b85421', 'ad42f3ff-e188-11ed-b66d-41c5f7b85421', 'ad42f400-e188-11ed-b66d-41c5f7b85421', 'ad42f401-e188-11ed-b66d-41c5f7b85421']PreviousClickHouse Vector SearchNextDocArrayHnswSearchRetrieval Question/AnsweringAttribute based filtering in metadataChoosing distance functionMaximal Marginal relevanceDelete datasetDeep Lake datasets on cloud (Activeloop, AWS, GCS, etc.) or in memoryTQL SearchCreating vector stores on AWS S3Deep Lake APITransfer local dataset to cloudCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/deeplake
525e8345939d-0
PGVector | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesPGVectorOn this pagePGVectorPGVector is an open-source vector similarity search for PostgresIt supports:exact and approximate nearest neighbor searchL2 distance, inner product, and cosine distanceThis notebook shows how to use the Postgres vector database (PGVector).See the installation instruction.# Pip install necessary packagepip install pgvectorpip install openaipip install psycopg2-binarypip install tiktoken Requirement already satisfied: pgvector in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (0.1.8) Requirement already satisfied: numpy in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from pgvector) (1.24.3) Requirement already satisfied: openai in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (0.27.7) Requirement already satisfied: requests>=2.20 in
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-2
(0.27.7) Requirement already satisfied: requests>=2.20 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from openai) (2.28.2) Requirement already satisfied: tqdm in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from openai) (4.65.0) Requirement already satisfied: aiohttp in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from openai) (3.8.4) Requirement already satisfied: charset-normalizer<4,>=2 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.20->openai) (3.1.0) Requirement already satisfied: idna<4,>=2.5 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.20->openai) (3.4) Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.20->openai) (1.26.15) Requirement already satisfied: certifi>=2017.4.17 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.20->openai) (2023.5.7) Requirement already satisfied: attrs>=17.3.0 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from aiohttp->openai) (23.1.0)
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-3
(from aiohttp->openai) (23.1.0) Requirement already satisfied: multidict<7.0,>=4.5 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from aiohttp->openai) (6.0.4) Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from aiohttp->openai) (4.0.2) Requirement already satisfied: yarl<2.0,>=1.0 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from aiohttp->openai) (1.9.2) Requirement already satisfied: frozenlist>=1.1.1 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from aiohttp->openai) (1.3.3) Requirement already satisfied: aiosignal>=1.1.2 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from aiohttp->openai) (1.3.1) Requirement already satisfied: psycopg2-binary in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (2.9.6) Requirement already satisfied: tiktoken in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (0.4.0) Requirement already satisfied: regex>=2022.1.18 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from tiktoken)
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-4
(from tiktoken) (2023.5.5) Requirement already satisfied: requests>=2.26.0 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from tiktoken) (2.28.2) Requirement already satisfied: charset-normalizer<4,>=2 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.26.0->tiktoken) (3.1.0) Requirement already satisfied: idna<4,>=2.5 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.26.0->tiktoken) (3.4) Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.26.0->tiktoken) (1.26.15) Requirement already satisfied: certifi>=2017.4.17 in /Users/joyeed/langchain/langchain/.venv/lib/python3.9/site-packages (from requests>=2.26.0->tiktoken) (2023.5.7)We want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") OpenAI API Key:········## Loading Environment Variablesfrom typing import List, Tuplefrom dotenv import load_dotenvload_dotenv() Falsefrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-5
Falsefrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores.pgvector import PGVectorfrom langchain.document_loaders import TextLoaderfrom langchain.docstore.document import Documentloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()# PGVector needs the connection string to the database.CONNECTION_STRING = "postgresql+psycopg2://harrisonchase@localhost:5432/test3"# # Alternatively, you can create it from enviornment variables.# import os# CONNECTION_STRING = PGVector.connection_string_from_db_params(# driver=os.environ.get("PGVECTOR_DRIVER", "psycopg2"),# host=os.environ.get("PGVECTOR_HOST", "localhost"),# port=int(os.environ.get("PGVECTOR_PORT", "5432")),# database=os.environ.get("PGVECTOR_DATABASE", "postgres"),# user=os.environ.get("PGVECTOR_USER", "postgres"),# password=os.environ.get("PGVECTOR_PASSWORD", "postgres"),# )Similarity Search with Euclidean Distance (Default)​# The PGVector Module will try to create a table with the name of the collection.# So, make sure that the collection name is unique and the user has the permission to create a table.COLLECTION_NAME = "state_of_the_union_test"db = PGVector.from_documents( embedding=embeddings, documents=docs, collection_name=COLLECTION_NAME, connection_string=CONNECTION_STRING,)query = "What did the president say about Ketanji Brown Jackson"docs_with_score =
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-6
= "What did the president say about Ketanji Brown Jackson"docs_with_score = db.similarity_search_with_score(query)for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print(doc.page_content) print("-" * 80) -------------------------------------------------------------------------------- Score: 0.18460171628856903 Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Score: 0.18460171628856903 Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-7
I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Score: 0.18470284560586236 Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Score: 0.21730864082247825 A former top litigator in private
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-8
0.21730864082247825 A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. --------------------------------------------------------------------------------Working with vectorstore​Above, we created a vectorstore from scratch. However, often times we want to work with an existing vectorstore.
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-9
In order to do that, we can initialize it directly.store = PGVector( collection_name=COLLECTION_NAME, connection_string=CONNECTION_STRING, embedding_function=embeddings,)Add documents​We can add documents to the existing vectorstore.store.add_documents([Document(page_content="foo")]) ['048c2e14-1cf3-11ee-8777-e65801318980']docs_with_score = db.similarity_search_with_score("foo")docs_with_score[0] (Document(page_content='foo', metadata={}), 3.3203430005457335e-09)docs_with_score[1] (Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \n\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', metadata={'source': '../../../state_of_the_union.txt'}), 0.2404395365581814)Overriding a vectorstore​If you have an existing collection, you override
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-10
a vectorstore​If you have an existing collection, you override it by doing from_documents and setting pre_delete_collection = Truedb = PGVector.from_documents( documents=docs, embedding=embeddings, collection_name=COLLECTION_NAME, connection_string=CONNECTION_STRING, pre_delete_collection=True,)docs_with_score = db.similarity_search_with_score("foo")docs_with_score[0] (Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \n\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', metadata={'source': '../../../state_of_the_union.txt'}), 0.2404115088144465)Using a VectorStore as a Retriever​retriever = store.as_retriever()print(retriever) tags=None metadata=None vectorstore=<langchain.vectorstores.pgvector.PGVector object at 0x29f94f880> search_type='similarity'
https://python.langchain.com/docs/integrations/vectorstores/pgvector
525e8345939d-11
object at 0x29f94f880> search_type='similarity' search_kwargs={}Previouspg_embeddingNextPineconeSimilarity Search with Euclidean Distance (Default)Working with vectorstoreAdd documentsOverriding a vectorstoreUsing a VectorStore as a RetrieverCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/pgvector
a6cf1fb45b14-0
Zilliz | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/zilliz
a6cf1fb45b14-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesZillizZillizZilliz Cloud is a fully managed service on cloud for LF AI Milvus®,This notebook shows how to use functionality related to the Zilliz Cloud managed vector database.To run, you should have a Zilliz Cloud instance up and running. Here are the installation instructionspip install pymilvusWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") OpenAI API Key:········# replaceZILLIZ_CLOUD_URI = "" # example: "https://in01-17f69c292d4a5sa.aws-us-west-2.vectordb.zillizcloud.com:19536"ZILLIZ_CLOUD_USERNAME = "" # example: "username"ZILLIZ_CLOUD_PASSWORD = "" # example:
https://python.langchain.com/docs/integrations/vectorstores/zilliz
a6cf1fb45b14-2
"" # example: "username"ZILLIZ_CLOUD_PASSWORD = "" # example: "*********"ZILLIZ_CLOUD_API_KEY = "" # example: "*********" (for serverless clusters which can be used as replacements for user and password)from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Milvusfrom langchain.document_loaders import TextLoaderfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()vector_db = Milvus.from_documents( docs, embeddings, connection_args={ "uri": ZILLIZ_CLOUD_URI, "user": ZILLIZ_CLOUD_USERNAME, "password": ZILLIZ_CLOUD_PASSWORD, # "token": ZILLIZ_CLOUD_API_KEY, # API key, for serverless clusters which can be used as replacements for user and password "secure": True, },)query = "What did the president say about Ketanji Brown Jackson"docs = vector_db.similarity_search(query)docs[0].page_content 'Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen
https://python.langchain.com/docs/integrations/vectorstores/zilliz
a6cf1fb45b14-3
I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.'PreviousWeaviateNextGrouped by providerCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/zilliz
334da13dc961-0
ClickHouse Vector Search | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/clickhouse
334da13dc961-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesClickHouse Vector SearchOn this pageClickHouse Vector SearchClickHouse is the fastest and most resource efficient open-source database for real-time apps and analytics with full SQL support and a wide range of functions to assist users in writing analytical queries. Lately added data structures and distance search functions (like L2Distance) as well as approximate nearest neighbor search indexes enable ClickHouse to be used as a high performance and scalable vector database to store and search vectors with SQL.This notebook shows how to use functionality related to the ClickHouse vector search.Setting up envrionments​Setting up local clickhouse server with docker (optional)docker run -d -p 8123:8123 -p9000:9000 --name langchain-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server:23.4.2.11Setup up clickhouse client driverpip install clickhouse-connectWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassif
https://python.langchain.com/docs/integrations/vectorstores/clickhouse
334da13dc961-2
OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassif not os.environ["OPENAI_API_KEY"]: os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Clickhouse, ClickhouseSettingsfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()for d in docs: d.metadata = {"some": "metadata"}settings = ClickhouseSettings(table="clickhouse_vector_search_example")docsearch = Clickhouse.from_documents(docs, embeddings, config=settings)query = "What did the president say about Ketanji Brown Jackson"docs = docsearch.similarity_search(query) Inserting data...: 100%|██████████| 42/42 [00:00<00:00, 2801.49it/s]print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States
https://python.langchain.com/docs/integrations/vectorstores/clickhouse
334da13dc961-3
Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.Get connection info and data schema​print(str(docsearch)) default.clickhouse_vector_search_example @ localhost:8123 username: None Table Schema: --------------------------------------------------- |id |Nullable(String) | |document |Nullable(String) | |embedding |Array(Float32) | |metadata |Object('json') | |uuid |UUID | --------------------------------------------------- Clickhouse table schema​Clickhouse table will be automatically created if not exist by default. Advanced users could pre-create the table with optimized settings. For
https://python.langchain.com/docs/integrations/vectorstores/clickhouse
334da13dc961-4
automatically created if not exist by default. Advanced users could pre-create the table with optimized settings. For distributed Clickhouse cluster with sharding, table engine should be configured as Distributed.print(f"Clickhouse Table DDL:\n\n{docsearch.schema}") Clickhouse Table DDL: CREATE TABLE IF NOT EXISTS default.clickhouse_vector_search_example( id Nullable(String), document Nullable(String), embedding Array(Float32), metadata JSON, uuid UUID DEFAULT generateUUIDv4(), CONSTRAINT cons_vec_len CHECK length(embedding) = 1536, INDEX vec_idx embedding TYPE annoy(100,'L2Distance') GRANULARITY 1000 ) ENGINE = MergeTree ORDER BY uuid SETTINGS index_granularity = 8192Filtering​You can have direct access to ClickHouse SQL where statement. You can write WHERE clause following standard SQL.NOTE: Please be aware of SQL injection, this interface must not be directly called by end-user.If you custimized your column_map under your setting, you search with filter like this:from langchain.vectorstores import Clickhouse, ClickhouseSettingsfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()for i, d in enumerate(docs): d.metadata = {"doc_id": i}docsearch = Clickhouse.from_documents(docs, embeddings) Inserting data...:
https://python.langchain.com/docs/integrations/vectorstores/clickhouse
334da13dc961-5
= Clickhouse.from_documents(docs, embeddings) Inserting data...: 100%|██████████| 42/42 [00:00<00:00, 6939.56it/s]meta = docsearch.metadata_columnoutput = docsearch.similarity_search_with_relevance_scores( "What did the president say about Ketanji Brown Jackson?", k=4, where_str=f"{meta}.doc_id<10",)for d, dist in output: print(dist, d.metadata, d.page_content[:20] + "...") 0.6779101415357189 {'doc_id': 0} Madam Speaker, Madam... 0.6997970363474885 {'doc_id': 8} And so many families... 0.7044504914336727 {'doc_id': 1} Groups of citizens b... 0.7053558702165094 {'doc_id': 6} And I’m taking robus...Deleting your data​docsearch.drop()PreviousClarifaiNextActiveloop's Deep LakeSetting up envrionmentsGet connection info and data schemaClickhouse table schemaFilteringDeleting your dataCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/clickhouse
ed65498ea416-0
scikit-learn | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/sklearn
ed65498ea416-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesscikit-learnOn this pagescikit-learnscikit-learn is an open source collection of machine learning algorithms, including some implementations of the k nearest neighbors. SKLearnVectorStore wraps this implementation and adds the possibility to persist the vector store in json, bson (binary json) or Apache Parquet format.This notebook shows how to use the SKLearnVectorStore vector database.# # if you plan to use bson serialization, install also:# %pip install bson# # if you plan to use parquet serialization, install also:%pip install pandas pyarrowTo use OpenAI embeddings, you will need an OpenAI key. You can get one at https://platform.openai.com/account/api-keys or feel free to use any other embeddings.import osfrom getpass import getpassos.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI key:")Basic usage​Load a sample document corpus​from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import
https://python.langchain.com/docs/integrations/vectorstores/sklearn
ed65498ea416-2
langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import SKLearnVectorStorefrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()Create the SKLearnVectorStore, index the document corpus and run a sample query​import tempfilepersist_path = os.path.join(tempfile.gettempdir(), "union.parquet")vector_store = SKLearnVectorStore.from_documents( documents=docs, embedding=embeddings, persist_path=persist_path, # persist_path and serializer are optional serializer="parquet",)query = "What did the president say about Ketanji Brown Jackson"docs = vector_store.similarity_search(query)print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our
https://python.langchain.com/docs/integrations/vectorstores/sklearn
ed65498ea416-3
days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.Saving and loading a vector store​vector_store.persist()print("Vector store was persisted to", persist_path) Vector store was persisted to /var/folders/6r/wc15p6m13nl_nl_n_xfqpc5c0000gp/T/union.parquetvector_store2 = SKLearnVectorStore( embedding=embeddings, persist_path=persist_path, serializer="parquet")print("A new instance of vector store was loaded from", persist_path) A new instance of vector store was loaded from /var/folders/6r/wc15p6m13nl_nl_n_xfqpc5c0000gp/T/union.parquetdocs = vector_store2.similarity_search(query)print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice
https://python.langchain.com/docs/integrations/vectorstores/sklearn
ed65498ea416-4
Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.Clean-up​os.remove(persist_path)PreviousSingleStoreDBNextStarRocksBasic usageLoad a sample document corpusCreate the SKLearnVectorStore, index the document corpus and run a sample querySaving and loading a vector storeClean-upCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/sklearn
7d6e6fa3a1a3-0
AnalyticDB | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/analyticdb
7d6e6fa3a1a3-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesAnalyticDBAnalyticDBAnalyticDB for PostgreSQL is a massively parallel processing (MPP) data warehousing service that is designed to analyze large volumes of data online.AnalyticDB for PostgreSQL is developed based on the open source Greenplum Database project and is enhanced with in-depth extensions by Alibaba Cloud. AnalyticDB for PostgreSQL is compatible with the ANSI SQL 2003 syntax and the PostgreSQL and Oracle database ecosystems. AnalyticDB for PostgreSQL also supports row store and column store. AnalyticDB for PostgreSQL processes petabytes of data offline at a high performance level and supports highly concurrent online queries.This notebook shows how to use functionality related to the AnalyticDB vector database.
https://python.langchain.com/docs/integrations/vectorstores/analyticdb
7d6e6fa3a1a3-2
To run, you should have an AnalyticDB instance up and running:Using AnalyticDB Cloud Vector Database. Click here to fast deploy it.from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import AnalyticDBSplit documents and get embeddings by call OpenAI APIfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()Connect to AnalyticDB by setting related ENVIRONMENTS.export PG_HOST={your_analyticdb_hostname}export PG_PORT={your_analyticdb_port} # Optional, default is 5432export PG_DATABASE={your_database} # Optional, default is postgresexport PG_USER={database_username}export PG_PASSWORD={database_password}Then store your embeddings and documents into AnalyticDBimport osconnection_string = AnalyticDB.connection_string_from_db_params( driver=os.environ.get("PG_DRIVER", "psycopg2cffi"), host=os.environ.get("PG_HOST", "localhost"), port=int(os.environ.get("PG_PORT", "5432")), database=os.environ.get("PG_DATABASE", "postgres"), user=os.environ.get("PG_USER", "postgres"), password=os.environ.get("PG_PASSWORD", "postgres"),)vector_db = AnalyticDB.from_documents( docs, embeddings, connection_string=connection_string,)Query and retrieve dataquery = "What did the president say about Ketanji Brown Jackson"docs = vector_db.similarity_search(query)print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to
https://python.langchain.com/docs/integrations/vectorstores/analyticdb
7d6e6fa3a1a3-3
Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.PreviousAlibaba Cloud OpenSearchNextAnnoyCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/analyticdb
781e9d57f53a-0
Tair | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/tair
781e9d57f53a-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesTairTairTair is a cloud native in-memory database service developed by Alibaba Cloud.
https://python.langchain.com/docs/integrations/vectorstores/tair
781e9d57f53a-2
It provides rich data models and enterprise-grade capabilities to support your real-time online scenarios while maintaining full compatibility with open source Redis. Tair also introduces persistent memory-optimized instances that are based on the new non-volatile memory (NVM) storage medium.This notebook shows how to use functionality related to the Tair vector database.To run, you should have a Tair instance up and running.from langchain.embeddings.fake import FakeEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Tairfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = FakeEmbeddings(size=128)Connect to Tair using the TAIR_URL environment variable export TAIR_URL="redis://{username}:{password}@{tair_address}:{tair_port}"or the keyword argument tair_url.Then store documents and embeddings into Tair.tair_url = "redis://localhost:6379"# drop first if index already existsTair.drop_index(tair_url=tair_url)vector_store = Tair.from_documents(docs, embeddings, tair_url=tair_url)Query similar documents.query = "What did the president say about Ketanji Brown Jackson"docs = vector_store.similarity_search(query)docs[0] Document(page_content='We’re going after the criminals who stole billions in relief money meant for small businesses and millions of Americans. \n\nAnd tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. \n\nBy the end of this year, the deficit will be down to less than half what it was before I took office. \n\nThe only president ever to cut the deficit by more than one trillion dollars in a single
https://python.langchain.com/docs/integrations/vectorstores/tair
781e9d57f53a-3
\n\nThe only president ever to cut the deficit by more than one trillion dollars in a single year. \n\nLowering your costs also means demanding more competition. \n\nI’m a capitalist, but capitalism without competition isn’t capitalism. \n\nIt’s exploitation—and it drives up prices. \n\nWhen corporations don’t have to compete, their profits go up, your prices go up, and small businesses and family farmers and ranchers go under. \n\nWe see it happening with ocean carriers moving goods in and out of America. \n\nDuring the pandemic, these foreign-owned companies raised prices by as much as 1,000% and made record profits.', metadata={'source': '../../../state_of_the_union.txt'})PreviousSupabase (Postgres)NextTigrisCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/tair
4139eebdbcc6-0
Atlas | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/atlas
4139eebdbcc6-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesAtlasAtlasAtlas is a platform for interacting with both small and internet scale unstructured datasets by Nomic. This notebook shows you how to use functionality related to the AtlasDB vectorstore.pip install spacypython3 -m spacy download en_core_web_smpip install nomicimport timefrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import SpacyTextSplitterfrom langchain.vectorstores import AtlasDBfrom langchain.document_loaders import TextLoaderATLAS_TEST_API_KEY = "7xDPkYXSYDc1_ErdTPIcoAR9RNd8YDlkS3nVNXcVoIMZ6"loader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = SpacyTextSplitter(separator="|")texts = []for doc in text_splitter.split_documents(documents): texts.extend(doc.page_content.split("|"))texts = [e.strip() for e in texts]db =
https://python.langchain.com/docs/integrations/vectorstores/atlas
4139eebdbcc6-2
= [e.strip() for e in texts]db = AtlasDB.from_texts( texts=texts, name="test_index_" + str(time.time()), # unique name for your vector store description="test_index", # a description for your vector store api_key=ATLAS_TEST_API_KEY, index_kwargs={"build_topic_model": True},)db.project.wait_for_project_lock()db.project<strong><a href="https://atlas.nomic.ai/dashboard/project/ee2354a3-7f9a-4c6b-af43-b0cda09d7198">test_index_1677255228.136989</strong></a> <br> A description for your project 508 datums inserted. <br> 1 index built. <br><strong>Projections</strong><ul><li>test_index_1677255228.136989_index. Status Completed. <a target="_blank" href="https://atlas.nomic.ai/map/ee2354a3-7f9a-4c6b-af43-b0cda09d7198/db996d77-8981-48a0-897a-ff2c22bbf541">view online</a></li></ul><hr><script> destroy = function() { document.getElementById("iframedb996d77-8981-48a0-897a-ff2c22bbf541").remove()
https://python.langchain.com/docs/integrations/vectorstores/atlas
4139eebdbcc6-3
} </script> <h4>Projection ID: db996d77-8981-48a0-897a-ff2c22bbf541</h4> <div class="actions"> <div id="hide" class="action" onclick="destroy()">Hide embedded project</div> <div class="action" id="out"> <a href="https://atlas.nomic.ai/map/ee2354a3-7f9a-4c6b-af43-b0cda09d7198/db996d77-8981-48a0-897a-ff2c22bbf541" target="_blank">Explore on atlas.nomic.ai</a> </div> </div> <iframe class="iframe" id="iframedb996d77-8981-48a0-897a-ff2c22bbf541" allow="clipboard-read; clipboard-write" src="https://atlas.nomic.ai/map/ee2354a3-7f9a-4c6b-af43-b0cda09d7198/db996d77-8981-48a0-897a-ff2c22bbf541"> </iframe> <style> .iframe { /* vh
https://python.langchain.com/docs/integrations/vectorstores/atlas
4139eebdbcc6-4
.iframe { /* vh can be **very** large in vscode html. */ height: min(75vh, 66vw); width: 100%; } </style> <style> .actions { display: block; } .action { min-height: 18px; margin: 5px; transition: all 500ms ease-in-out; } .action:hover { cursor: pointer; } #hide:hover::after { content: " X"; } #out:hover::after { content: ""; }
https://python.langchain.com/docs/integrations/vectorstores/atlas
4139eebdbcc6-5
""; } </style>PreviousAnnoyNextAwaDBCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/atlas
95b057af9e0e-0
Clarifai | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesClarifaiOn this pageClarifaiClarifai is an AI Platform that provides the full AI lifecycle ranging from data exploration, data labeling, model training, evaluation, and inference. A Clarifai application can be used as a vector database after uploading inputs. This notebook shows how to use functionality related to the Clarifai vector database.To use Clarifai, you must have an account and a Personal Access Token (PAT) key.
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-2
Check here to get or create a PAT.Dependencies# Install required dependenciespip install clarifaiImportsHere we will be setting the personal access token. You can find your PAT under settings/security on the platform.# Please login and get your API key from https://clarifai.com/settings/securityfrom getpass import getpassCLARIFAI_PAT = getpass()We want to use OpenAIEmbeddings so we have to get the OpenAI API Key.# Import the required modulesfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.document_loaders import TextLoaderfrom langchain.vectorstores import ClarifaiSetupSetup the user id and app id where the text data will be uploaded. Note: when creating that application please select an appropriate base workflow for indexing your text documents such as the Language-Understanding workflow.You will have to first create an account on Clarifai and then create an application.USER_ID = "USERNAME_ID"APP_ID = "APPLICATION_ID"NUMBER_OF_DOCS = 4From Texts​Create a Clarifai vectorstore from a list of texts. This section will upload each text with its respective metadata to a Clarifai Application. The Clarifai Application can then be used for semantic search to find relevant texts.texts = [ "I really enjoy spending time with you", "I hate spending time with my dog", "I want to go for a run", "I went to the movies yesterday", "I love playing soccer with my friends",]metadatas = [{"id": i, "text": text} for i, text in enumerate(texts)]clarifai_vector_db = Clarifai.from_texts( user_id=USER_ID, app_id=APP_ID, texts=texts, pat=CLARIFAI_PAT,
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-3
texts=texts, pat=CLARIFAI_PAT, number_of_docs=NUMBER_OF_DOCS, metadatas=metadatas,)docs = clarifai_vector_db.similarity_search("I would love to see you")docs [Document(page_content='I really enjoy spending time with you', metadata={'text': 'I really enjoy spending time with you', 'id': 0.0}), Document(page_content='I went to the movies yesterday', metadata={'text': 'I went to the movies yesterday', 'id': 3.0}), Document(page_content='zab', metadata={'page': '2'}), Document(page_content='zab', metadata={'page': '2'})]From Documents​Create a Clarifai vectorstore from a list of Documents. This section will upload each document with its respective metadata to a Clarifai Application. The Clarifai Application can then be used for semantic search to find relevant documents.loader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)docs[:4] [Document(page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago,
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-4
an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. \n\nIn this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.� The Ukrainian Ambassador to the United States is here tonight. \n\nLet each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world. \n\nPlease rise if you are able and show that, Yes, we the United States of America stand with the Ukrainian people. \n\nThroughout our history we’ve learned this lesson when dictators do not pay a price for their aggression they cause more chaos. \n\nThey keep moving. \n\nAnd the costs and the threats to America and the world keep rising. \n\nThat’s why the NATO Alliance was created to secure peace and stability in Europe after World War 2. \n\nThe United States is a member along with 29 other nations. \n\nIt matters. American diplomacy matters. American resolve matters.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='Putin’s latest attack on Ukraine was
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-5
Document(page_content='Putin’s latest attack on Ukraine was premeditated and unprovoked. \n\nHe rejected repeated efforts at diplomacy. \n\nHe thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready. Here is what we did. \n\nWe prepared extensively and carefully. \n\nWe spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. \n\nI spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression. \n\nWe countered Russia’s lies with truth. \n\nAnd now that he has acted the free world is holding him accountable. \n\nAlong with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='We are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than ever. \n\nTogether with our allies –we are right now enforcing powerful economic sanctions. \n\nWe are cutting off Russia’s largest banks from the international financial system. \n\nPreventing Russia’s central bank from defending the Russian Ruble making Putin’s $630 Billion “war fund� worthless. \n\nWe are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come. \n\nTonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-6
\n\nTonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. \n\nThe U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs. \n\nWe are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains.', metadata={'source': '../../../state_of_the_union.txt'})]USER_ID = "USERNAME_ID"APP_ID = "APPLICATION_ID"NUMBER_OF_DOCS = 4clarifai_vector_db = Clarifai.from_documents( user_id=USER_ID, app_id=APP_ID, documents=docs, pat=CLARIFAI_PAT_KEY, number_of_docs=NUMBER_OF_DOCS,)docs = clarifai_vector_db.similarity_search("Texts related to criminals and violence")docs [Document(page_content='And I will keep doing everything in my power to crack down on gun trafficking and ghost guns you can buy online and make at home—they have no serial numbers and can’t be traced. \n\nAnd I ask Congress to pass proven measures to reduce gun violence. Pass universal background checks. Why should anyone on a terrorist list be able to purchase a weapon? \n\nBan assault weapons and high-capacity magazines. \n\nRepeal the liability shield that makes gun manufacturers the only industry in America that can’t be sued. \n\nThese laws don’t infringe on the Second Amendment. They save lives. \n\nThe most fundamental right in America is the right to vote – and to have it counted. And it’s under assault. \n\nIn state after state, new laws have been passed, not only to suppress the vote, but
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-7
state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n\nWe cannot let this happen.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. \n\nI’ve worked on these issues a long time. \n\nI know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the
https://python.langchain.com/docs/integrations/vectorstores/clarifai
95b057af9e0e-8
if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \n\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', metadata={'source': '../../../state_of_the_union.txt'}), Document(page_content='So let’s not abandon our streets. Or choose between safety and equal justice. \n\nLet’s come together to protect our communities, restore trust, and hold law enforcement accountable. \n\nThat’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers. \n\nThat’s why the American Rescue Plan provided $350 Billion that cities, states, and counties can use to hire more police and invest in proven strategies like community violence interruption—trusted messengers breaking the cycle of violence and trauma and giving young people hope. \n\nWe should all agree: The answer is not to Defund the police. The answer is to FUND the police with the resources and training they need to protect our communities. \n\nI ask Democrats and Republicans alike: Pass my budget and keep our neighborhoods safe.', metadata={'source': '../../../state_of_the_union.txt'})]PreviousChromaNextClickHouse Vector SearchFrom TextsFrom DocumentsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/clarifai
7606f0f274af-0
AwaDB | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/awadb
7606f0f274af-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesAwaDBOn this pageAwaDBAwaDB is an AI Native database for the search and storage of embedding vectors used by LLM Applications.This notebook shows how to use functionality related to the AwaDB.pip install awadbfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import AwaDBfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0)docs = text_splitter.split_documents(documents)db = AwaDB.from_documents(docs)query = "What did the president say about Ketanji Brown Jackson"docs = db.similarity_search(query)print(docs[0].page_content) And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of
https://python.langchain.com/docs/integrations/vectorstores/awadb
7606f0f274af-2
nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.Similarity search with score​The returned distance score is between 0-1. 0 is dissimilar, 1 is the most similardocs = db.similarity_search_with_score(query)print(docs[0]) (Document(page_content='And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}), 0.561813814013747)Restore the table created and added data before​AwaDB automatically persists added document dataIf you can restore the table you created and added before, you can just do this as below:awadb_client = awadb.Client()ret = awadb_client.Load("langchain_awadb")if ret: print("awadb load table success")else: print("awadb load table failed")awadb load table successPreviousAtlasNextAzure Cognitive SearchSimilarity search with scoreRestore the table created and added data beforeCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/awadb
4e52e9aa7bad-0
Alibaba Cloud OpenSearch | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/alibabacloud_opensearch
4e52e9aa7bad-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesAlibaba Cloud OpenSearchAlibaba Cloud OpenSearchAlibaba Cloud Opensearch is a one-stop platform to develop intelligent search services. OpenSearch was built on the large-scale distributed search engine developed by Alibaba. OpenSearch serves more than 500 business cases in Alibaba Group and thousands of Alibaba Cloud customers. OpenSearch helps develop search services in different search scenarios, including e-commerce, O2O, multimedia, the content industry, communities and forums, and big data query in enterprises.OpenSearch helps you develop high quality, maintenance-free, and high performance intelligent search services to provide your users with high search efficiency and accuracy.OpenSearch provides the vector search feature. In specific scenarios, especially test question search and image search scenarios, you can use the vector search feature together with the multimodal search feature to improve the accuracy of search results.This notebook shows how to use functionality related to the Alibaba Cloud OpenSearch Vector Search Edition.
https://python.langchain.com/docs/integrations/vectorstores/alibabacloud_opensearch
4e52e9aa7bad-2
To run, you should have an OpenSearch Vector Search Edition instance up and running:Read the help document to quickly familiarize and configure OpenSearch Vector Search Edition instance.After the instance is up and running, follow these steps to split documents, get embeddings, connect to the alibaba cloud opensearch instance, index documents, and perform vector retrieval.We need to install the following Python packages first.#!pip install alibabacloud-ha3engineWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import ( AlibabaCloudOpenSearch, AlibabaCloudOpenSearchSettings,)Split documents and get embeddings.from langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()Create opensearch settings.settings = AlibabaCloudOpenSearchSettings( endpoint="The endpoint of opensearch instance, You can find it from the console of Alibaba Cloud OpenSearch.", instance_id="The identify of opensearch instance, You can find it from the console of Alibaba Cloud OpenSearch.", datasource_name="The name of the data source specified when creating it.", username="The username specified when purchasing the instance.", password="The password specified when purchasing the instance.", embedding_index_name="The name of the vector attribute specified when configuring the instance attributes.", field_name_mapping={ "id": "id", # The id
https://python.langchain.com/docs/integrations/vectorstores/alibabacloud_opensearch
4e52e9aa7bad-3
"id": "id", # The id field name mapping of index document. "document": "document", # The text field name mapping of index document. "embedding": "embedding", # The embedding field name mapping of index document. "name_of_the_metadata_specified_during_search": "opensearch_metadata_field_name,=", # The metadata field name mapping of index document, could specify multiple, The value field contains mapping name and operator, the operator would be used when executing metadata filter query. },)# for example# settings = AlibabaCloudOpenSearchSettings(# endpoint="ha-cn-5yd39d83c03.public.ha.aliyuncs.com",# instance_id="ha-cn-5yd39d83c03",# datasource_name="ha-cn-5yd39d83c03_test",# username="this is a user name",# password="this is a password",# embedding_index_name="index_embedding",# field_name_mapping={# "id": "id",# "document": "document",# "embedding": "embedding",# "metadata_a": "metadata_a,=" #The value field contains mapping name and operator, the operator would be used when executing metadata filter query# "metadata_b": "metadata_b,>"# "metadata_c": "metadata_c,<"# "metadata_else": "metadata_else,="#
https://python.langchain.com/docs/integrations/vectorstores/alibabacloud_opensearch
4e52e9aa7bad-4
"metadata_else": "metadata_else,="# })Create an opensearch access instance by settings.# Create an opensearch instance and index docs.opensearch = AlibabaCloudOpenSearch.from_texts( texts=docs, embedding=embeddings, config=settings)or# Create an opensearch instance.opensearch = AlibabaCloudOpenSearch(embedding=embeddings, config=settings)Add texts and build index.metadatas = {"md_key_a": "md_val_a", "md_key_b": "md_val_b"}# the key of metadatas must match field_name_mapping in settings.opensearch.add_texts(texts=docs, ids=[], metadatas=metadatas)Query and retrieve data.query = "What did the president say about Ketanji Brown Jackson"docs = opensearch.similarity_search(query)print(docs[0].page_content)Query and retrieve data with metadata.query = "What did the president say about Ketanji Brown Jackson"metadatas = {"md_key_a": "md_val_a"}docs = opensearch.similarity_search(query, filter=metadatas)print(docs[0].page_content)If you encounter any problems during use, please feel free to contact xingshaomin.xsm@alibaba-inc.com, and we will do our best to provide you with assistance and support.PreviousVector storesNextAnalyticDBCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/alibabacloud_opensearch
4b0750257e4f-0
Qdrant | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesQdrantOn this pageQdrantQdrant (read: quadrant ) is a vector similarity search engine. It provides a production-ready service with a convenient API to store, search, and manage points - vectors with an additional payload. Qdrant is tailored to extended filtering support. It makes it useful for all sorts of neural network or semantic-based matching, faceted search, and other applications.This notebook shows how to use functionality related to the Qdrant vector database. There are various modes of how to run Qdrant, and depending on the chosen one, there will be some subtle differences. The options include:Local mode, no server requiredOn-premise server deploymentQdrant CloudSee the installation instructions.pip install qdrant-clientWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") OpenAI API Key:
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-2
= getpass.getpass("OpenAI API Key:") OpenAI API Key: ········from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Qdrantfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()Connecting to Qdrant from LangChain​Local mode​Python client allows you to run the same code in local mode without running the Qdrant server. That's great for testing things out and debugging or if you plan to store just a small amount of vectors. The embeddings might be fully kepy in memory or persisted on disk.In-memory​For some testing scenarios and quick experiments, you may prefer to keep all the data in memory only, so it gets lost when the client is destroyed - usually at the end of your script/notebook.qdrant = Qdrant.from_documents( docs, embeddings, location=":memory:", # Local mode with in-memory storage only collection_name="my_documents",)On-disk storage​Local mode, without using the Qdrant server, may also store your vectors on disk so they're persisted between runs.qdrant = Qdrant.from_documents( docs, embeddings, path="/tmp/local_qdrant", collection_name="my_documents",)On-premise server deployment​No matter if you choose to launch Qdrant locally with a Docker container, or select a Kubernetes deployment with
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-3
if you choose to launch Qdrant locally with a Docker container, or select a Kubernetes deployment with the official Helm chart, the way you're going to connect to such an instance will be identical. You'll need to provide a URL pointing to the service.url = "<---qdrant url here --->"qdrant = Qdrant.from_documents( docs, embeddings, url, prefer_grpc=True, collection_name="my_documents",)Qdrant Cloud​If you prefer not to keep yourself busy with managing the infrastructure, you can choose to set up a fully-managed Qdrant cluster on Qdrant Cloud. There is a free forever 1GB cluster included for trying out. The main difference with using a managed version of Qdrant is that you'll need to provide an API key to secure your deployment from being accessed publicly.url = "<---qdrant cloud cluster url here --->"api_key = "<---api key here--->"qdrant = Qdrant.from_documents( docs, embeddings, url, prefer_grpc=True, api_key=api_key, collection_name="my_documents",)Recreating the collection​Both Qdrant.from_texts and Qdrant.from_documents methods are great to start using Qdrant with Langchain. In the previous versions the collection was recreated every time you called any of them. That behaviour has changed. Currently, the collection is going to be reused if it already exists. Setting force_recreate to True allows to remove the old collection and start from scratch.url = "<---qdrant url here --->"qdrant = Qdrant.from_documents( docs, embeddings, url, prefer_grpc=True,
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-4
embeddings, url, prefer_grpc=True, collection_name="my_documents", force_recreate=True,)Similarity search​The simplest scenario for using Qdrant vector store is to perform a similarity search. Under the hood, our query will be encoded with the embedding_function and used to find similar documents in Qdrant collection.query = "What did the president say about Ketanji Brown Jackson"found_docs = qdrant.similarity_search(query)print(found_docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.Similarity search with score​Sometimes we might want to perform the search, but also obtain a relevancy score to know how good is a particular result.
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-5
The returned distance score is cosine distance. Therefore, a lower score is better.query = "What did the president say about Ketanji Brown Jackson"found_docs = qdrant.similarity_search_with_score(query)document, score = found_docs[0]print(document.page_content)print(f"\nScore: {score}") Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Score: 0.8153784913324512Metadata filtering​Qdrant has an extensive filtering system with rich type support. It is also possible to use the filters in Langchain, by passing an additional param to both the similarity_search_with_score and similarity_search methods.from qdrant_client.http import models as restquery = "What did the president say about Ketanji Brown Jackson"found_docs = qdrant.similarity_search_with_score(query, filter=rest.Filter(...))Maximum marginal relevance search (MMR)​If you'd like to look up for some similar
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-6
relevance search (MMR)​If you'd like to look up for some similar documents, but you'd also like to receive diverse results, MMR is method you should consider. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.query = "What did the president say about Ketanji Brown Jackson"found_docs = qdrant.max_marginal_relevance_search(query, k=2, fetch_k=10)for i, doc in enumerate(found_docs): print(f"{i + 1}.", doc.page_content, "\n") 1. Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. 2. We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. I recently visited the New York City Police Department days after the funerals of Officer
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-7
I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. Officer Mora was 27 years old. Officer Rivera was 22. Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. I’ve worked on these issues a long time. I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. Qdrant as a Retriever​Qdrant, as all the other vector stores, is a LangChain Retriever, by using cosine similarity. retriever = qdrant.as_retriever()retriever VectorStoreRetriever(vectorstore=<langchain.vectorstores.qdrant.Qdrant object at 0x7fc4e5720a00>, search_type='similarity', search_kwargs={})It might be also specified to use MMR as a search strategy, instead of similarity.retriever = qdrant.as_retriever(search_type="mmr")retriever VectorStoreRetriever(vectorstore=<langchain.vectorstores.qdrant.Qdrant object at
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-8
VectorStoreRetriever(vectorstore=<langchain.vectorstores.qdrant.Qdrant object at 0x7fc4e5720a00>, search_type='mmr', search_kwargs={})query = "What did the president say about Ketanji Brown Jackson"retriever.get_relevant_documents(query)[0] Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})Customizing Qdrant​There are some options to use an existing Qdrant collection within your Langchain application. In such cases you may need to define how to map Qdrant point into the Langchain Document.Named vectors​Qdrant supports multiple vectors per point by named vectors. Langchain requires just a single embedding per document and, by default, uses a single vector. However, if you work with a collection created externally or want to have the named vector used, you can configure it by providing its name.Qdrant.from_documents( docs, embeddings,
https://python.langchain.com/docs/integrations/vectorstores/qdrant
4b0750257e4f-9
name.Qdrant.from_documents( docs, embeddings, location=":memory:", collection_name="my_documents_2", vector_name="custom_vector",)As a Langchain user, you won't see any difference whether you use named vectors or not. Qdrant integration will handle the conversion under the hood.Metadata​Qdrant stores your vector embeddings along with the optional JSON-like payload. Payloads are optional, but since LangChain assumes the embeddings are generated from the documents, we keep the context data, so you can extract the original texts as well.By default, your document is going to be stored in the following payload structure:{ "page_content": "Lorem ipsum dolor sit amet", "metadata": { "foo": "bar" }}You can, however, decide to use different keys for the page content and metadata. That's useful if you already have a collection that you'd like to reuse.Qdrant.from_documents( docs, embeddings, location=":memory:", collection_name="my_documents_2", content_payload_key="my_page_content_key", metadata_payload_key="my_meta",) <langchain.vectorstores.qdrant.Qdrant at 0x7fc4e2baa230>PreviousPineconeNextRedisConnecting to Qdrant from LangChainLocal modeOn-premise server deploymentQdrant CloudRecreating the collectionSimilarity searchSimilarity search with scoreMetadata filteringMaximum marginal relevance search (MMR)Qdrant as a RetrieverCustomizing QdrantNamed vectorsMetadataCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/qdrant
55eb69a560bf-0
Tigris | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/tigris
55eb69a560bf-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesTigrisOn this pageTigrisTigris is an open source Serverless NoSQL Database and Search Platform designed to simplify building high-performance vector search applications.
https://python.langchain.com/docs/integrations/vectorstores/tigris
55eb69a560bf-2
Tigris eliminates the infrastructure complexity of managing, operating, and synchronizing multiple tools, allowing you to focus on building great applications instead.This notebook guides you how to use Tigris as your VectorStorePre requisitesAn OpenAI account. You can sign up for an account hereSign up for a free Tigris account. Once you have signed up for the Tigris account, create a new project called vectordemo. Next, make a note of the Uri for the region you've created your project in, the clientId and clientSecret. You can get all this information from the Application Keys section of the project.Let's first install our dependencies:pip install tigrisdb openapi-schema-pydantic openai tiktokenWe will load the OpenAI api key and Tigris credentials in our environmentimport osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")os.environ["TIGRIS_PROJECT"] = getpass.getpass("Tigris Project Name:")os.environ["TIGRIS_CLIENT_ID"] = getpass.getpass("Tigris Client Id:")os.environ["TIGRIS_CLIENT_SECRET"] = getpass.getpass("Tigris Client Secret:")from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Tigrisfrom langchain.document_loaders import TextLoaderInitialize Tigris vector store​Let's import our test dataset:loader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()vector_store = Tigris.from_documents(docs, embeddings, index_name="my_embeddings")Similarity Search​query = "What did the president
https://python.langchain.com/docs/integrations/vectorstores/tigris
55eb69a560bf-3
index_name="my_embeddings")Similarity Search​query = "What did the president say about Ketanji Brown Jackson"found_docs = vector_store.similarity_search(query)print(found_docs)Similarity Search with score (vector distance)​query = "What did the president say about Ketanji Brown Jackson"result = vector_store.similarity_search_with_score(query)for doc, score in result: print(f"document={doc}, score={score}")PreviousTairNextTypesenseInitialize Tigris vector storeSimilarity SearchSimilarity Search with score (vector distance)CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/tigris
c63785fbd405-0
Milvus | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/milvus
c63785fbd405-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesMilvusMilvusMilvus is a database that stores, indexes, and manages massive embedding vectors generated by deep neural networks and other machine learning (ML) models.This notebook shows how to use functionality related to the Milvus vector database.To run, you should have a Milvus instance up and running.pip install pymilvusWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") OpenAI API Key:········from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import Milvusfrom langchain.document_loaders import TextLoaderfrom langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter =
https://python.langchain.com/docs/integrations/vectorstores/milvus
c63785fbd405-2
= TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()vector_db = Milvus.from_documents( docs, embeddings, connection_args={"host": "127.0.0.1", "port": "19530"},)query = "What did the president say about Ketanji Brown Jackson"docs = vector_db.similarity_search(query)docs[0].page_content 'Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.'PreviousMatchingEngineNextMongoDB AtlasCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/vectorstores/milvus
a4cb4780b09c-0
Redis | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/vectorstores/redis
a4cb4780b09c-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsVector storesAlibaba Cloud OpenSearchAnalyticDBAnnoyAtlasAwaDBAzure Cognitive SearchCassandraChromaClarifaiClickHouse Vector SearchActiveloop's Deep LakeDocArrayHnswSearchDocArrayInMemorySearchElasticSearchFAISSHologresLanceDBMarqoMatchingEngineMilvusMongoDB AtlasMyScaleOpenSearchpg_embeddingPGVectorPineconeQdrantRedisRocksetSingleStoreDBscikit-learnStarRocksSupabase (Postgres)TairTigrisTypesenseVectaraWeaviateZillizGrouped by providerIntegrationsVector storesRedisOn this pageRedisRedis (Remote Dictionary Server) is an in-memory data structure store, used as a distributed, in-memory key–value database, cache and message broker, with optional durability.This notebook shows how to use functionality related to the Redis vector database.As database either Redis standalone server or Redis Sentinel HA setups are supported for connections with the "redis_url" parameter. More information about the different formats of the redis connection url can be found in the LangChain
https://python.langchain.com/docs/integrations/vectorstores/redis