id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
d7b50aeab0ec-9
Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \n\nWe’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \n\nLet’s pass the Paycheck Fairness Act and paid leave. \n\nRaise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \n\nLet’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.', metadata={'source': '../../../state_of_the_union.txt', 'year': 2012})] Maximal Marginal relevance# Using maximal marginal relevance db.max_marginal_relevance_search('What did the president say about Ketanji Brown Jackson?')
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-10
[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', 'year': 2013}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-11
Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \n\nWe’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \n\nLet’s pass the Paycheck Fairness Act and paid leave. \n\nRaise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \n\nLet’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.', metadata={'source': '../../../state_of_the_union.txt', 'year': 2012}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-12
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', 'year': 2012}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-13
Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \n\nWhile it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. \n\nAnd soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \n\nSo tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \n\nFirst, beat the opioid epidemic.', metadata={'source': '../../../state_of_the_union.txt', 'year': 2013})] Delete dataset# db.delete_dataset() and if delete fails you can also force delete DeepLake.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, in case you want to store them in memory, in the Deep Lake Managed DB, or in any object storage, you can provide the corresponding path to the dataset. You can retrieve your user token from app.activeloop.ai os.environ['ACTIVELOOP_TOKEN'] = getpass.getpass('Activeloop Token:') # Embed and store the texts username = "<username>" # your username on app.activeloop.ai
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-14
username = "<username>" # your username on app.activeloop.ai dataset_path = f"hub://{username}/langchain_test" # could be also ./local/path (much faster locally), s3://bucket/path/to/dataset, gcs://path/to/dataset, etc. embedding = OpenAIEmbeddings() db = DeepLake(dataset_path=dataset_path, embedding_function=embeddings, overwrite=True) db.add_documents(docs) Your Deep Lake dataset has been successfully created! The dataset is private so make sure you are logged in! This dataset can be visualized in Jupyter Notebook by ds.visualize() or at https://app.activeloop.ai/davitbun/langchain_test hub://davitbun/langchain_test loaded successfully. Evaluating ingest: 100%|██████████| 1/1 [00:14<00:00 Dataset(path='hub://davitbun/langchain_test', 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 ['d6d6ccb4-e187-11ed-b66d-41c5f7b85421', 'd6d6ccb5-e187-11ed-b66d-41c5f7b85421', 'd6d6ccb6-e187-11ed-b66d-41c5f7b85421',
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-15
'd6d6ccb7-e187-11ed-b66d-41c5f7b85421'] query = "What did the president say about Ketanji Brown Jackson" docs = db.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 Breyer’s legacy of excellence. Creating dataset 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-16
}) 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 ------- ------- ------- ------- ------- 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.ds # get structure of the dataset db.ds.summary() Dataset(path='hub://davitbun/langchain_test', 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 # get embeddings numpy array embeds = db.ds.embedding.numpy() Transfer local dataset to cloud# Copy already created dataset to the cloud. You can also transfer from cloud to local. import deeplake username = "davitbun" # your username on app.activeloop.ai
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-17
username = "davitbun" # your username on app.activeloop.ai source = 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. 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
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
d7b50aeab0ec-18
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 ------- ------- ------- ------- ------- 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'] previous ClickHouse Vector Search next DocArrayHnswSearch Contents Retrieval Question/Answering Attribute based filtering in metadata Choosing distance function Maximal Marginal relevance Delete dataset Deep Lake datasets on cloud (Activeloop, AWS, GCS, etc.) or in memory Creating dataset on AWS S3 Deep Lake API Transfer local dataset to cloud By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
275ff793c10d-0
.ipynb .pdf OpenSearch Contents Installation similarity_search using Approximate k-NN similarity_search using Script Scoring similarity_search using Painless Scripting Using a preexisting OpenSearch instance OpenSearch# OpenSearch is a scalable, flexible, and extensible open-source software suite for search, analytics, and observability applications licensed under Apache 2.0. OpenSearch is a distributed search and analytics engine based on Apache Lucene. This notebook shows how to use functionality related to the OpenSearch database. To run, you should have an OpenSearch instance up and running: see here for an easy Docker installation. similarity_search by default performs the Approximate k-NN Search which uses one of the several algorithms like lucene, nmslib, faiss recommended for large datasets. To perform brute force search we have other search methods known as Script Scoring and Painless Scripting. Check this for more details. Installation# Install the Python client. !pip install opensearch-py We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import OpenSearchVectorSearch from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader 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() similarity_search using Approximate k-NN#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/opensearch.html
275ff793c10d-1
embeddings = OpenAIEmbeddings() similarity_search using Approximate k-NN# similarity_search using Approximate k-NN Search with Custom Parameters docsearch = OpenSearchVectorSearch.from_documents( docs, embeddings, opensearch_url="http://localhost:9200" ) # If using the default Docker installation, use this instantiation instead: # docsearch = OpenSearchVectorSearch.from_documents( # docs, # embeddings, # opensearch_url="https://localhost:9200", # http_auth=("admin", "admin"), # use_ssl = False, # verify_certs = False, # ssl_assert_hostname = False, # ssl_show_warn = False, # ) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query, k=10) print(docs[0].page_content) docsearch = OpenSearchVectorSearch.from_documents(docs, embeddings, opensearch_url="http://localhost:9200", engine="faiss", space_type="innerproduct", ef_construction=256, m=48) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) print(docs[0].page_content) similarity_search using Script Scoring# similarity_search using Script Scoring with Custom Parameters docsearch = OpenSearchVectorSearch.from_documents(docs, embeddings, opensearch_url="http://localhost:9200", is_appx_search=False) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search("What did the president say about Ketanji Brown Jackson", k=1, search_type="script_scoring")
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/opensearch.html
275ff793c10d-2
print(docs[0].page_content) similarity_search using Painless Scripting# similarity_search using Painless Scripting with Custom Parameters docsearch = OpenSearchVectorSearch.from_documents(docs, embeddings, opensearch_url="http://localhost:9200", is_appx_search=False) filter = {"bool": {"filter": {"term": {"text": "smuggling"}}}} query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search("What did the president say about Ketanji Brown Jackson", search_type="painless_scripting", space_type="cosineSimilarity", pre_filter=filter) print(docs[0].page_content) Using a preexisting OpenSearch instance# It’s also possible to use a preexisting OpenSearch instance with documents that already have vectors present. # this is just an example, you would need to change these values to point to another opensearch instance docsearch = OpenSearchVectorSearch(index_name="index-*", embedding_function=embeddings, opensearch_url="http://localhost:9200") # you can specify custom field names to match the fields you're using to store your embedding, document text value, and metadata docs = docsearch.similarity_search("Who was asking about getting lunch today?", search_type="script_scoring", space_type="cosinesimil", vector_field="message_embedding", text_field="message", metadata_field="message_metadata") previous MyScale next PGVector Contents Installation similarity_search using Approximate k-NN similarity_search using Script Scoring similarity_search using Painless Scripting Using a preexisting OpenSearch instance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/opensearch.html
59ad5acd8d1b-0
.ipynb .pdf Pinecone Pinecone# Pinecone is a vector database with broad functionality. This notebook shows how to use functionality related to the Pinecone vector database. To use Pinecone, you must have an API key. Here are the installation instructions. !pip install pinecone-client import os import getpass PINECONE_API_KEY = getpass.getpass('Pinecone API Key:') PINECONE_ENV = getpass.getpass('Pinecone Environment:') 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 OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Pinecone from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader 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() import pinecone # initialize pinecone pinecone.init( api_key=PINECONE_API_KEY, # find at app.pinecone.io environment=PINECONE_ENV # next to api key in console ) index_name = "langchain-demo" docsearch = Pinecone.from_documents(docs, embeddings, index_name=index_name) # if you already have an index, you can load it like this # docsearch = Pinecone.from_existing_index(index_name, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pinecone.html
59ad5acd8d1b-1
docs = docsearch.similarity_search(query) print(docs[0].page_content) previous PGVector next Qdrant By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pinecone.html
213f1b79bcfc-0
.ipynb .pdf Vectara Contents Connecting to Vectara from LangChain Similarity search Similarity search with score Vectara as a Retriever Vectara# Vectara is a API platform for building LLM-powered applications. It provides a simple to use API for document indexing and query that is managed by Vectara and is optimized for performance and accuracy. This notebook shows how to use functionality related to the Vectara vector database. See the Vectara API documentation for more information on how to use the API. We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') OpenAI API Key:········ from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Vectara from langchain.document_loaders import TextLoader 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() Connecting to Vectara from LangChain# The Vectara API provides simple API endpoints for indexing and querying. vectara = Vectara.from_documents(docs, embedding=None) Similarity search# The simplest scenario for using Vectara is to perform a similarity search. query = "What did the president say about Ketanji Brown Jackson" found_docs = vectara.similarity_search(query) print(found_docs[0].page_content)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/vectara.html
213f1b79bcfc-1
print(found_docs[0].page_content) 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. A former top litigator in private practice. A former federal public defender. 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. query = "What did the president say about Ketanji Brown Jackson" found_docs = vectara.similarity_search_with_score(query) document, score = found_docs[0] print(document.page_content) print(f"\nScore: {score}") 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. A former top litigator in private practice. A former federal public defender. Score: 1.0046461 Vectara as a Retriever#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/vectara.html
213f1b79bcfc-2
Score: 1.0046461 Vectara as a Retriever# Vectara, as all the other vector stores, is a LangChain Retriever, by using cosine similarity. retriever = vectara.as_retriever() retriever VectorStoreRetriever(vectorstore=<langchain.vectorstores.vectara.Vectara object at 0x156d3e830>, search_type='similarity', search_kwargs={}) query = "What did the president say about Ketanji Brown Jackson" retriever.get_relevant_documents(query)[0] Document(page_content='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. A former top litigator in private practice. A former federal public defender.', metadata={'source': '../../modules/state_of_the_union.txt'}) previous Typesense next Weaviate Contents Connecting to Vectara from LangChain Similarity search Similarity search with score Vectara as a Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/vectara.html
4891129fb2ba-0
.ipynb .pdf PGVector Contents Similarity search with score Similarity Search with Euclidean Distance (Default) Working with vectorstore in PG Uploading a vectorstore in PG Retrieving a vectorstore in PG PGVector# PGVector is an open-source vector similarity search for Postgres It supports: exact and approximate nearest neighbor search L2 distance, inner product, and cosine distance This notebook shows how to use the Postgres vector database (PGVector). See the installation instruction. # Pip install necessary package !pip install pgvector !pip install openai !pip install psycopg2-binary !pip 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 /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)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-1
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) 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)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-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) (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)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-3
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 os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') OpenAI API Key:········ ## Loading Environment Variables from typing import List, Tuple from dotenv import load_dotenv load_dotenv() False from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores.pgvector import PGVector from langchain.document_loaders import TextLoader from langchain.docstore.document import Document 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() ## PGVector needs the connection string to the database. ## We will load it from the environment variables. import os
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-4
## We will load it from the environment 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"), ) ## Example # postgresql+psycopg2://username:password@localhost:5432/database_name # ## PGVector needs the connection string to the database. # ## We will load it from the environment 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", "rd-embeddings"), # user=os.environ.get("PGVECTOR_USER", "admin"), # password=os.environ.get("PGVECTOR_PASSWORD", "password"), # ) # ## Example # # postgresql+psycopg2://username:password@localhost:5432/database_name Similarity search with score# 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. db = PGVector.from_documents( embedding=embeddings, documents=docs, collection_name="state_of_the_union",
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-5
documents=docs, collection_name="state_of_the_union", connection_string=CONNECTION_STRING, ) query = "What did the president say about Ketanji Brown Jackson" docs_with_score: List[Tuple[Document, float]] = 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.6076804864602984 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.6076804864602984 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-6
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.659062774389974 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. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Score: 0.659062774389974 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-7
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 in PG# Uploading a vectorstore in PG# data=docs api_key=os.environ['OPENAI_API_KEY'] db = PGVector.from_documents( documents=docs, embedding=embeddings, collection_name=collection_name, connection_string=connection_string, distance_strategy=DistanceStrategy.COSINE, openai_api_key=api_key, pre_delete_collection=False ) Retrieving a vectorstore in PG# connection_string = CONNECTION_STRING embedding=embeddings collection_name="state_of_the_union" from langchain.vectorstores.pgvector import DistanceStrategy store = PGVector( connection_string=connection_string, embedding_function=embedding, collection_name=collection_name, distance_strategy=DistanceStrategy.COSINE ) retriever = store.as_retriever() print(retriever) vectorstore=<langchain.vectorstores.pgvector.PGVector object at 0x7fe9a1b1c670> search_type='similarity' search_kwargs={} # When we have an existing PG VEctor DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.EUCLIDEAN db1 = PGVector.from_existing_index( embedding=embeddings,
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-8
db1 = PGVector.from_existing_index( embedding=embeddings, collection_name="state_of_the_union", distance_strategy=DEFAULT_DISTANCE_STRATEGY, pre_delete_collection = False, connection_string=CONNECTION_STRING, ) query = "What did the president say about Ketanji Brown Jackson" docs_with_score: List[Tuple[Document, float]] = db1.similarity_search_with_score(query) print(docs_with_score)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-9
[(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'}), 0.6075870262188066), (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'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-10
Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}), 0.6075870262188066), (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.6589478388546668), (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
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-11
\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.6589478388546668)]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-12
for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print(doc.page_content) print("-" * 80) -------------------------------------------------------------------------------- Score: 0.6075870262188066 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.6075870262188066 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-13
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.6589478388546668 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. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Score: 0.6589478388546668 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
4891129fb2ba-14
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. -------------------------------------------------------------------------------- previous OpenSearch next Pinecone Contents Similarity search with score Similarity Search with Euclidean Distance (Default) Working with vectorstore in PG Uploading a vectorstore in PG Retrieving a vectorstore in PG By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html
04de58da73ec-0
.ipynb .pdf DocArrayInMemorySearch Contents Setup Using DocArrayInMemorySearch Similarity search Similarity search with score DocArrayInMemorySearch# DocArrayInMemorySearch is a document index provided by Docarray that stores documents in memory. It is a great starting point for small datasets, where you may not want to launch a database server. This notebook shows how to use functionality related to the DocArrayInMemorySearch. Setup# Uncomment the below cells to install docarray and get/set your OpenAI api key if you haven’t already done so. # !pip install "docarray" # Get an OpenAI token: https://platform.openai.com/account/api-keys # import os # from getpass import getpass # OPENAI_API_KEY = getpass() # os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY Using DocArrayInMemorySearch# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import DocArrayInMemorySearch from langchain.document_loaders import TextLoader documents = TextLoader('../../../state_of_the_union.txt').load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db = DocArrayInMemorySearch.from_documents(docs, embeddings) Similarity search# query = "What did the president say about Ketanji Brown Jackson" docs = db.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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/docarray_in_memory.html
04de58da73ec-1
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# The returned distance score is cosine distance. Therefore, a lower score is better. docs = db.similarity_search_with_score(query) docs[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={}), 0.8154190158347903) previous DocArrayHnswSearch next ElasticSearch Contents Setup Using DocArrayInMemorySearch Similarity search Similarity search with score By Harrison Chase
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/docarray_in_memory.html
04de58da73ec-2
Similarity search Similarity search with score By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/docarray_in_memory.html
f3d5bcc2d8b5-0
.ipynb .pdf Redis Contents Installing Example Redis as Retriever Redis# Redis (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. Installing# !pip install redis We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') Example# from langchain.embeddings import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores.redis import Redis from langchain.document_loaders import TextLoader 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() rds = Redis.from_documents(docs, embeddings, redis_url="redis://localhost:6379", index_name='link') rds.index_name 'link' query = "What did the president say about Ketanji Brown Jackson" results = rds.similarity_search(query) print(results[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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/redis.html
f3d5bcc2d8b5-1
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. print(rds.add_texts(["Ankush went to Princeton"])) ['doc:link:d7d02e3faf1b40bbbe29a683ff75b280'] query = "Princeton" results = rds.similarity_search(query) print(results[0].page_content) Ankush went to Princeton # Load from existing index rds = Redis.from_existing_index(embeddings, redis_url="redis://localhost:6379", index_name='link') query = "What did the president say about Ketanji Brown Jackson" results = rds.similarity_search(query) print(results[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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/redis.html
f3d5bcc2d8b5-2
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. Redis as Retriever# Here we go over different options for using the vector store as a retriever. There are three different search methods we can use to do retrieval. By default, it will use semantic similarity. retriever = rds.as_retriever() docs = retriever.get_relevant_documents(query) We can also use similarity_limit as a search method. This is only return documents if they are similar enough retriever = rds.as_retriever(search_type="similarity_limit") # Here we can see it doesn't return any results because there are no relevant documents retriever.get_relevant_documents("where did ankush go to college?") previous Qdrant next SKLearnVectorStore Contents Installing Example Redis as Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/redis.html
cefb6d5aa87a-0
.ipynb .pdf Atlas Atlas# Atlas 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 spacy !python3 -m spacy download en_core_web_sm !pip install nomic import time from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import SpacyTextSplitter from langchain.vectorstores import AtlasDB from langchain.document_loaders import TextLoader ATLAS_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 = 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 test_index_1677255228.136989 A description for your project 508 datums inserted. 1 index built. Projections test_index_1677255228.136989_index. Status Completed. view online Projection ID: db996d77-8981-48a0-897a-ff2c22bbf541 Hide embedded project
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/atlas.html
cefb6d5aa87a-1
Hide embedded project Explore on atlas.nomic.ai previous Annoy next Chroma By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/atlas.html
ff0e2a60016b-0
.ipynb .pdf Annoy Contents Create VectorStore from texts Create VectorStore from docs Create VectorStore via existing embeddings Search via embeddings Search via docstore id Save and load Construct from scratch Annoy# Annoy (Approximate Nearest Neighbors Oh Yeah) is a C++ library with Python bindings to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data. This notebook shows how to use functionality related to the Annoy vector database. Note NOTE: Annoy is read-only - once the index is built you cannot add any more emebddings! If you want to progressively add new entries to your VectorStore then better choose an alternative! #!pip install annoy Create VectorStore from texts# from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import Annoy embeddings_func = HuggingFaceEmbeddings() texts = ["pizza is great", "I love salad", "my car", "a dog"] # default metric is angular vector_store = Annoy.from_texts(texts, embeddings_func) # allows for custom annoy parameters, defaults are n_trees=100, n_jobs=-1, metric="angular" vector_store_v2 = Annoy.from_texts( texts, embeddings_func, metric="dot", n_trees=100, n_jobs=1 ) vector_store.similarity_search("food", k=3) [Document(page_content='pizza is great', metadata={}), Document(page_content='I love salad', metadata={}), Document(page_content='my car', metadata={})] # the score is a distance metric, so lower is better
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-1
# the score is a distance metric, so lower is better vector_store.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)] Create VectorStore from docs# from langchain.document_loaders import TextLoader from langchain.text_splitter import CharacterTextSplitter 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[:5]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-2
docs = text_splitter.split_documents(documents) docs[:5] [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, 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'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-3
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'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-4
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'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-5
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 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'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-6
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 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 Ac Create 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),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-7
(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 {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 0
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-8
Document(page_content='pizza is great', metadata={}) # same document has distance 0 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={}), 1.0734446048736572), (Document(page_content='my car', metadata={}), 1.2895267009735107)] Save and load# vector_store.save_local("my_annoy_index_and_docstore") saving config loaded_vector_store = Annoy.load_local( "my_annoy_index_and_docstore", embeddings=embeddings_func ) # same document has distance 0 loaded_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={}), 1.0734446048736572), (Document(page_content='my car', metadata={}), 1.2895267009735107)] Construct from scratch# import uuid from annoy import AnnoyIndex from langchain.docstore.document import Document from langchain.docstore.in_memory import InMemoryDocstore metadatas = [{"x": "food"}, {"x": "food"}, {"x": "stuff"}, {"x": "animal"}] # embeddings embeddings = embeddings_func.embed_documents(texts) # embedding dim f = len(embeddings[0]) # index metric = "angular" index = AnnoyIndex(f, metric=metric) for i, emb in enumerate(embeddings): index.add_item(i, emb) index.build(10) # docstore documents = []
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
ff0e2a60016b-9
index.build(10) # docstore documents = [] 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), (Document(page_content='my car', metadata={'x': 'stuff'}), 1.226445198059082)] previous AnalyticDB next Atlas Contents Create VectorStore from texts Create VectorStore from docs Create VectorStore via existing embeddings Search via embeddings Search via docstore id Save and load Construct from scratch By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
d2469c89bab4-0
.ipynb .pdf ElasticSearch Contents ElasticSearch ElasticVectorSearch class Installation Example ElasticKnnSearch Class Test adding vectors Test knn search using query vector builder Test knn search using pre generated vector Test source option Test fields option Test with es client connection rather than cloud_id ElasticSearch# Elasticsearch is a distributed, RESTful search and analytics engine. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. This notebook shows how to use functionality related to the Elasticsearch database. ElasticVectorSearch class# Installation# Check out Elasticsearch installation instructions. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Example: from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embedding = OpenAIEmbeddings() elastic_vector_search = ElasticVectorSearch( elasticsearch_url="http://localhost:9200", index_name="test_index", embedding=embedding ) To connect to an Elasticsearch instance that requires login credentials, including Elastic Cloud, use the Elasticsearch URL format https://username:password@es_host:9243. For example, to connect to Elastic Cloud, create the Elasticsearch URL with the required authentication details and pass it to the ElasticVectorSearch constructor as the named parameter elasticsearch_url. You can obtain your Elastic Cloud URL and login credentials by logging in to the Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and navigating to the “Deployments” page. To obtain your Elastic Cloud password for the default “elastic” user:
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
d2469c89bab4-1
To obtain your Elastic Cloud password for the default “elastic” user: Log in to the Elastic Cloud console at https://cloud.elastic.co Go to “Security” > “Users” Locate the “elastic” user and click “Edit” Click “Reset password” Follow the prompts to reset the password Format for Elastic Cloud URLs is https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. Example: from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embedding = OpenAIEmbeddings() elastic_host = "cluster_id.region_id.gcp.cloud.es.io" elasticsearch_url = f"https://username:password@{elastic_host}:9243" elastic_vector_search = ElasticVectorSearch( elasticsearch_url=elasticsearch_url, index_name="test_index", embedding=embedding ) !pip install elasticsearch import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') Example# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import ElasticVectorSearch from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader 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() db = ElasticVectorSearch.from_documents(docs, embeddings, elasticsearch_url="http://localhost:9200") query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
d2469c89bab4-2
docs = db.similarity_search(query) print(docs[0].page_content) In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. We cannot let this happen. 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. ElasticKnnSearch Class# The ElasticKnnSearch implements features allowing storing vectors and documents in Elasticsearch for use with approximate kNN search !pip install langchain elasticsearch from langchain.vectorstores.elastic_vector_search import ElasticKnnSearch from langchain.embeddings import ElasticsearchEmbeddings import elasticsearch # Initialize ElasticsearchEmbeddings model_id = "<model_id_from_es>" dims = dim_count es_cloud_id = "ESS_CLOUD_ID" es_user = "es_user" es_password = "es_pass" test_index = "<index_name>" #input_field = "your_input_field" # if different from 'text_field' # Generate embedding object embeddings = ElasticsearchEmbeddings.from_credentials( model_id, #input_field=input_field,
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
d2469c89bab4-3
model_id, #input_field=input_field, es_cloud_id=es_cloud_id, es_user=es_user, es_password=es_password, ) # Initialize ElasticKnnSearch knn_search = ElasticKnnSearch( es_cloud_id=es_cloud_id, es_user=es_user, es_password=es_password, index_name= test_index, embedding= embeddings ) Test adding vectors# # Test `add_texts` method texts = ["Hello, world!", "Machine learning is fun.", "I love Python."] knn_search.add_texts(texts) # Test `from_texts` method new_texts = ["This is a new text.", "Elasticsearch is powerful.", "Python is great for data analysis."] knn_search.from_texts(new_texts, dims=dims) Test knn search using query vector builder# # Test `knn_search` method with model_id and query_text query = "Hello" knn_result = knn_search.knn_search(query = query, model_id= model_id, k=2) print(f"kNN search results for query '{query}': {knn_result}") print(f"The 'text' field value from the top hit is: '{knn_result['hits']['hits'][0]['_source']['text']}'") # Test `hybrid_search` method query = "Hello" hybrid_result = knn_search.knn_hybrid_search(query = query, model_id= model_id, k=2) print(f"Hybrid search results for query '{query}': {hybrid_result}") print(f"The 'text' field value from the top hit is: '{hybrid_result['hits']['hits'][0]['_source']['text']}'") Test knn search using pre generated vector#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
d2469c89bab4-4
Test knn search using pre generated vector# # Generate embedding for tests query_text = 'Hello' query_embedding = embeddings.embed_query(query_text) print(f"Length of embedding: {len(query_embedding)}\nFirst two items in embedding: {query_embedding[:2]}") # Test knn Search knn_result = knn_search.knn_search(query_vector = query_embedding, k=2) print(f"The 'text' field value from the top hit is: '{knn_result['hits']['hits'][0]['_source']['text']}'") # Test hybrid search - Requires both query_text and query_vector knn_result = knn_search.knn_hybrid_search(query_vector = query_embedding, query=query_text, k=2) print(f"The 'text' field value from the top hit is: '{knn_result['hits']['hits'][0]['_source']['text']}'") Test source option# # Test `knn_search` method with model_id and query_text query = "Hello" knn_result = knn_search.knn_search(query = query, model_id= model_id, k=2, source=False) assert not '_source' in knn_result['hits']['hits'][0].keys() # Test `hybrid_search` method query = "Hello" hybrid_result = knn_search.knn_hybrid_search(query = query, model_id= model_id, k=2, source=False) assert not '_source' in hybrid_result['hits']['hits'][0].keys() Test fields option# # Test `knn_search` method with model_id and query_text query = "Hello" knn_result = knn_search.knn_search(query = query, model_id= model_id, k=2, fields=['text'])
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
d2469c89bab4-5
assert 'text' in knn_result['hits']['hits'][0]['fields'].keys() # Test `hybrid_search` method query = "Hello" hybrid_result = knn_search.knn_hybrid_search(query = query, model_id= model_id, k=2, fields=['text']) assert 'text' in hybrid_result['hits']['hits'][0]['fields'].keys() Test with es client connection rather than cloud_id# # Create Elasticsearch connection es_connection = Elasticsearch( hosts=['https://es_cluster_url:port'], basic_auth=('user', 'password') ) # Instantiate ElasticsearchEmbeddings using es_connection embeddings = ElasticsearchEmbeddings.from_es_connection( model_id, es_connection, ) # Initialize ElasticKnnSearch knn_search = ElasticKnnSearch( es_connection = es_connection, index_name= test_index, embedding= embeddings ) # Test `knn_search` method with model_id and query_text query = "Hello" knn_result = knn_search.knn_search(query = query, model_id= model_id, k=2) print(f"kNN search results for query '{query}': {knn_result}") print(f"The 'text' field value from the top hit is: '{knn_result['hits']['hits'][0]['_source']['text']}'") previous DocArrayInMemorySearch next FAISS Contents ElasticSearch ElasticVectorSearch class Installation Example ElasticKnnSearch Class Test adding vectors Test knn search using query vector builder Test knn search using pre generated vector Test source option Test fields option Test with es client connection rather than cloud_id By Harrison Chase © Copyright 2023, Harrison Chase.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
d2469c89bab4-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/elasticsearch.html
ded2a90cd6f6-0
.ipynb .pdf FAISS Contents Similarity Search with score Saving and loading Merging FAISS# Facebook AI Similarity Search (Faiss) is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning. Faiss documentation. This notebook shows how to use functionality related to the FAISS vector database. #!pip install faiss # OR !pip install faiss-cpu We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') # Uncomment the following line if you need to initialize FAISS with no AVX2 optimization # os.environ['FAISS_NO_AVX2'] = '1' OpenAI API Key: ········ from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import FAISS from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader 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() db = FAISS.from_documents(docs, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query) print(docs[0].page_content)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
ded2a90cd6f6-1
docs = db.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 Breyer’s legacy of excellence. Similarity Search with score# There are some FAISS specific methods. One of them is similarity_search_with_score, which allows you to return not only the documents but also the distance score of the query to them. The returned distance score is L2 distance. Therefore, a lower score is better. docs_and_scores = db.similarity_search_with_score(query) docs_and_scores[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
ded2a90cd6f6-2
docs_and_scores = db.similarity_search_with_score(query) docs_and_scores[0] (Document(page_content='In 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. \n\nTonight. 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.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0), 0.3914415) It is also possible to do a search for documents similar to a given embedding vector using similarity_search_by_vector which accepts an embedding vector as a parameter instead of a string. embedding_vector = embeddings.embed_query(query) docs_and_scores = db.similarity_search_by_vector(embedding_vector) Saving and loading# You can also save and load a FAISS index. This is useful so you don’t have to recreate it everytime you use it. db.save_local("faiss_index") new_db = FAISS.load_local("faiss_index", embeddings) docs = new_db.similarity_search(query) docs[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
ded2a90cd6f6-3
docs = new_db.similarity_search(query) docs[0] Document(page_content='In 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. \n\nTonight. 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.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0) Merging# You can also merge two FAISS vectorstores db1 = FAISS.from_texts(["foo"], embeddings) db2 = FAISS.from_texts(["bar"], embeddings) db1.docstore._dict {'e0b74348-6c93-4893-8764-943139ec1d17': Document(page_content='foo', lookup_str='', metadata={}, lookup_index=0)} db2.docstore._dict {'bdc50ae3-a1bb-4678-9260-1b0979578f40': Document(page_content='bar', lookup_str='', metadata={}, lookup_index=0)} db1.merge_from(db2) db1.docstore._dict
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
ded2a90cd6f6-4
db1.merge_from(db2) db1.docstore._dict {'e0b74348-6c93-4893-8764-943139ec1d17': Document(page_content='foo', lookup_str='', metadata={}, lookup_index=0), 'd5211050-c777-493d-8825-4800e74cfdb6': Document(page_content='bar', lookup_str='', metadata={}, lookup_index=0)} previous ElasticSearch next LanceDB Contents Similarity Search with score Saving and loading Merging By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
c770ca4c5f2f-0
.ipynb .pdf Typesense Contents Similarity Search Typesense as a Retriever Typesense# Typesense is an open source, in-memory search engine, that you can either self-host or run on Typesense Cloud. Typesense focuses on performance by storing the entire index in RAM (with a backup on disk) and also focuses on providing an out-of-the-box developer experience by simplifying available options and setting good defaults. It also lets you combine attribute-based filtering together with vector queries, to fetch the most relevant documents. This notebook shows you how to use Typesense as your VectorStore. Let’s first install our dependencies: !pip install typesense openapi-schema-pydantic openai tiktoken We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Typesense from langchain.document_loaders import TextLoader 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() docsearch = Typesense.from_documents(docs, embeddings, typesense_client_params={ 'host': 'localhost', # Use xxx.a1.typesense.net for Typesense Cloud 'port': '8108', # Use 443 for Typesense Cloud 'protocol': 'http', # Use https for Typesense Cloud 'typesense_api_key': 'xyz',
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/typesense.html
c770ca4c5f2f-1
'typesense_api_key': 'xyz', 'typesense_collection_name': 'lang-chain' }) Similarity Search# query = "What did the president say about Ketanji Brown Jackson" found_docs = docsearch.similarity_search(query) print(found_docs[0].page_content) Typesense as a Retriever# Typesense, as all the other vector stores, is a LangChain Retriever, by using cosine similarity. retriever = docsearch.as_retriever() retriever query = "What did the president say about Ketanji Brown Jackson" retriever.get_relevant_documents(query)[0] previous Tigris next Vectara Contents Similarity Search Typesense as a Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/typesense.html
84f065e92538-0
.ipynb .pdf Supabase (Postgres) Contents Similarity search with score Retriever options Maximal Marginal Relevance Searches Supabase (Postgres)# Supabase is an open source Firebase alternative. Supabase is built on top of PostgreSQL, which offers strong SQL querying capabilities and enables a simple interface with already-existing tools and frameworks. PostgreSQL also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. This notebook shows how to use Supabase and pgvector as your VectorStore. To run this notebook, please ensure: the pgvector extension is enabled you have installed the supabase-py package that you have created a match_documents function in your database that you have a documents table in your public schema similar to the one below. The following function determines cosine similarity, but you can adjust to your needs. -- Enable the pgvector extension to work with embedding vectors create extension vector; -- Create a table to store your documents create table documents ( id bigserial primary key, content text, -- corresponds to Document.pageContent metadata jsonb, -- corresponds to Document.metadata embedding vector(1536) -- 1536 works for OpenAI embeddings, change if needed ); CREATE FUNCTION match_documents(query_embedding vector(1536), match_count int) RETURNS TABLE( id bigint, content text, metadata jsonb, -- we return matched vectors to enable maximal marginal relevance searches embedding vector(1536), similarity float) LANGUAGE plpgsql AS $$ # variable_conflict use_column BEGIN RETURN query SELECT id, content, metadata, embedding,
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
84f065e92538-1
SELECT id, content, metadata, embedding, 1 -(documents.embedding <=> query_embedding) AS similarity FROM documents ORDER BY documents.embedding <=> query_embedding LIMIT match_count; END; $$; # with pip !pip install supabase # with conda # !conda install -c conda-forge supabase We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') os.environ['SUPABASE_URL'] = getpass.getpass('Supabase URL:') os.environ['SUPABASE_SERVICE_KEY'] = getpass.getpass('Supabase Service Key:') # If you're storing your Supabase and OpenAI API keys in a .env file, you can load them with dotenv from dotenv import load_dotenv load_dotenv() import os from supabase.client import Client, create_client supabase_url = os.environ.get("SUPABASE_URL") supabase_key = os.environ.get("SUPABASE_SERVICE_KEY") supabase: Client = create_client(supabase_url, supabase_key) from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import SupabaseVectorStore from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader 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)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
84f065e92538-2
docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() # We're using the default `documents` table here. You can modify this by passing in a `table_name` argument to the `from_documents` method. vector_store = SupabaseVectorStore.from_documents( docs, embeddings, client=supabase ) query = "What did the president say about Ketanji Brown Jackson" matched_docs = vector_store.similarity_search(query) print(matched_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# The returned distance score is cosine distance. Therefore, a lower score is better. matched_docs = vector_store.similarity_search_with_relevance_scores(query) matched_docs[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
84f065e92538-3
matched_docs[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'}), 0.802509746274066) Retriever options# This section goes over different options for how to use SupabaseVectorStore as a retriever. Maximal Marginal Relevance Searches# In addition to using similarity search in the retriever object, you can also use mmr. retriever = vector_store.as_retriever(search_type="mmr") matched_docs = retriever.get_relevant_documents(query) for i, d in enumerate(matched_docs): print(f"\n## Document {i}\n") print(d.page_content) ## Document 0 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
84f065e92538-4
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. ## Document 1 One was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. When they came home, many of the world’s fittest and best trained warriors were never the same. Headaches. Numbness. Dizziness. A cancer that would put them in a flag-draped coffin. I know. One of those soldiers was my son Major Beau Biden. We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. But I’m committed to finding out everything we can. Committed to military families like Danielle Robinson from Ohio. The widow of Sergeant First Class Heath Robinson. He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. Stationed near Baghdad, just yards from burn pits the size of football fields. Heath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter. ## Document 2
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
84f065e92538-5
## Document 2 And I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. These steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. But I want you to know that we are going to be okay. When the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. While it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly. ## Document 3 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 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
84f065e92538-6
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. previous SKLearnVectorStore next Tair Contents Similarity search with score Retriever options Maximal Marginal Relevance Searches By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
4716079a445d-0
.ipynb .pdf Chroma Contents Similarity search with score Persistance Initialize PeristedChromaDB Persist the Database Load the Database from disk, and create the chain Retriever options MMR Updating a Document Chroma# Chroma is a database for building AI applications with embeddings. This notebook shows how to use functionality related to the Chroma vector database. !pip install chromadb # get a token: https://platform.openai.com/account/api-keys from getpass import getpass OPENAI_API_KEY = getpass() ········ import os os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Chroma from langchain.document_loaders import TextLoader 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() db = Chroma.from_documents(docs, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query) Using embedded DuckDB without persistence: data will be transient 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
4716079a445d-1
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# The returned distance score is cosine distance. Therefore, a lower score is better. docs = db.similarity_search_with_score(query) docs[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'}), 0.3949805498123169) Persistance# The below steps cover how to persist a ChromaDB instance Initialize PeristedChromaDB#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
4716079a445d-2
Initialize PeristedChromaDB# Create embeddings for each chunk and insert into the Chroma vector database. The persist_directory argument tells ChromaDB where to store the database when it’s persisted. # Embed and store the texts # Supplying a persist_directory will store the embeddings on disk persist_directory = 'db' embedding = OpenAIEmbeddings() vectordb = Chroma.from_documents(documents=docs, embedding=embedding, persist_directory=persist_directory) Running Chroma using direct local API. No existing DB found in db, skipping load No existing DB found in db, skipping load Persist the Database# We should call persist() to ensure the embeddings are written to disk. vectordb.persist() vectordb = None Persisting DB to disk, putting it in the save folder db PersistentDuckDB del, about to run persist Persisting DB to disk, putting it in the save folder db Load the Database from disk, and create the chain# Be sure to pass the same persist_directory and embedding_function as you did when you instantiated the database. Initialize the chain we will use for question answering. # Now we can load the persisted database from disk, and use it as normal. vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding) Running Chroma using direct local API. loaded in 4 embeddings loaded in 1 collections Retriever options# This section goes over different options for how to use Chroma as a retriever. MMR# In addition to using similarity search in the retriever object, you can also use mmr. retriever = db.as_retriever(search_type="mmr") retriever.get_relevant_documents(query)[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
4716079a445d-3
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'}) Updating a Document# The update_document function allows you to modify the content of a document in the Chroma instance after it has been added. Let’s see an example of how to use this function. # Import Document class from langchain.docstore.document import Document # Initial document content and id initial_content = "This is an initial document content" document_id = "doc1" # Create an instance of Document with initial content and metadata original_doc = Document(page_content=initial_content, metadata={"page": "0"}) # Initialize a Chroma instance with the original document new_db = Chroma.from_documents( collection_name="test_collection", documents=[original_doc], embedding=OpenAIEmbeddings(), # using the same embeddings as before ids=[document_id], )
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
4716079a445d-4
ids=[document_id], ) At this point, we have a new Chroma instance with a single document “This is an initial document content” with id “doc1”. Now, let’s update the content of the document. # Updated document content updated_content = "This is the updated document content" # Create a new Document instance with the updated content updated_doc = Document(page_content=updated_content, metadata={"page": "1"}) # Update the document in the Chroma instance by passing the document id and the updated document new_db.update_document(document_id=document_id, document=updated_doc) # Now, let's retrieve the updated document using similarity search output = new_db.similarity_search(updated_content, k=1) # Print the content of the retrieved document print(output[0].page_content, output[0].metadata) This is the updated document content {'page': '1'} previous Atlas next ClickHouse Vector Search Contents Similarity search with score Persistance Initialize PeristedChromaDB Persist the Database Load the Database from disk, and create the chain Retriever options MMR Updating a Document By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
1e757c6ddb72-0
.ipynb .pdf Wikipedia Contents Installation Examples Running retriever Question Answering on facts Wikipedia# Wikipedia is a multilingual free online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and using a wiki-based editing system called MediaWiki. Wikipedia is the largest and most-read reference work in history. This notebook shows how to retrieve wiki pages from wikipedia.org into the Document format that is used downstream. Installation# First, you need to install wikipedia python package. #!pip install wikipedia WikipediaRetriever has these arguments: optional lang: default=”en”. Use it to search in a specific language part of Wikipedia optional load_max_docs: default=100. Use it to limit number of downloaded documents. It takes time to download all 100 documents, so use a small number for experiments. There is a hard limit of 300 for now. optional load_all_available_meta: default=False. By default only the most important fields downloaded: Published (date when document was published/last updated), title, Summary. If True, other fields also downloaded. get_relevant_documents() has one argument, query: free text which used to find documents in Wikipedia Examples# Running retriever# from langchain.retrievers import WikipediaRetriever retriever = WikipediaRetriever() docs = retriever.get_relevant_documents(query='HUNTER X HUNTER') docs[0].metadata # meta-information of the Document {'title': 'Hunter × Hunter',
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
1e757c6ddb72-1
'summary': 'Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The story focuses on a young boy named Gon Freecss who discovers that his father, who left him at a young age, is actually a world-renowned Hunter, a licensed professional who specializes in fantastical pursuits such as locating rare or unidentified animal species, treasure hunting, surveying unexplored enclaves, or hunting down lawless individuals. Gon departs on a journey to become a Hunter and eventually find his father. Along the way, Gon meets various other Hunters and encounters the paranormal.\nHunter × Hunter was adapted into a 62-episode anime television series produced by Nippon Animation and directed by Kazuhiro Furuhashi, which ran on Fuji Television from October 1999 to March 2001. Three separate original video animations (OVAs) totaling 30 episodes were subsequently produced by Nippon Animation and released in Japan from 2002 to 2004. A second anime television series by Madhouse aired on Nippon Television from October 2011 to September 2014, totaling 148 episodes, with two animated theatrical films released in 2013. There are also numerous audio albums, video games, musicals, and other media based on Hunter × Hunter.\nThe manga has been translated into English and released in North America by Viz Media since April 2005. Both television series have been also licensed by Viz Media, with the first series having aired on the Funimation Channel in 2009 and the second series broadcast
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
1e757c6ddb72-2
with the first series having aired on the Funimation Channel in 2009 and the second series broadcast on Adult Swim\'s Toonami programming block from April 2016 to June 2019.\nHunter × Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.\n\n'}
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
1e757c6ddb72-3
docs[0].page_content[:400] # a content of the Document 'Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The sto' Question Answering on facts# # get a token: https://platform.openai.com/account/api-keys from getpass import getpass OPENAI_API_KEY = getpass() ········ import os os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY from langchain.chat_models import ChatOpenAI from langchain.chains import ConversationalRetrievalChain model = ChatOpenAI(model_name='gpt-3.5-turbo') # switch to 'gpt-4' qa = ConversationalRetrievalChain.from_llm(model,retriever=retriever) questions = [ "What is Apify?", "When the Monument to the Martyrs of the 1830 Revolution was created?", "What is the Abhayagiri Vihāra?", # "How big is Wikipédia en français?", ] chat_history = [] for question in questions: result = qa({"question": question, "chat_history": chat_history}) chat_history.append((question, result['answer'])) print(f"-> **Question**: {question} \n") print(f"**Answer**: {result['answer']} \n") -> **Question**: What is Apify?
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
1e757c6ddb72-4
-> **Question**: What is Apify? **Answer**: Apify is a platform that allows you to easily automate web scraping, data extraction and web automation. It provides a cloud-based infrastructure for running web crawlers and other automation tasks, as well as a web-based tool for building and managing your crawlers. Additionally, Apify offers a marketplace for buying and selling pre-built crawlers and related services. -> **Question**: When the Monument to the Martyrs of the 1830 Revolution was created? **Answer**: Apify is a web scraping and automation platform that enables you to extract data from websites, turn unstructured data into structured data, and automate repetitive tasks. It provides a user-friendly interface for creating web scraping scripts without any coding knowledge. Apify can be used for various web scraping tasks such as data extraction, web monitoring, content aggregation, and much more. Additionally, it offers various features such as proxy support, scheduling, and integration with other tools to make web scraping and automation tasks easier and more efficient. -> **Question**: What is the Abhayagiri Vihāra? **Answer**: Abhayagiri Vihāra was a major monastery site of Theravada Buddhism that was located in Anuradhapura, Sri Lanka. It was founded in the 2nd century BCE and is considered to be one of the most important monastic complexes in Sri Lanka. previous Self-querying with Weaviate next Zep Contents Installation Examples Running retriever Question Answering on facts By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
5a60b94d46c8-0
.ipynb .pdf Pinecone Hybrid Search Contents Setup Pinecone Get embeddings and sparse encoders Load Retriever Add texts (if necessary) Use Retriever Pinecone Hybrid Search# Pinecone is a vector database with broad functionality. This notebook goes over how to use a retriever that under the hood uses Pinecone and Hybrid Search. The logic of this retriever is taken from this documentaion To use Pinecone, you must have an API key and an Environment. Here are the installation instructions. #!pip install pinecone-client pinecone-text import os import getpass os.environ['PINECONE_API_KEY'] = getpass.getpass('Pinecone API Key:') from langchain.retrievers import PineconeHybridSearchRetriever os.environ['PINECONE_ENVIRONMENT'] = getpass.getpass('Pinecone Environment:') We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') Setup Pinecone# You should only have to do this part once. Note: it’s important to make sure that the “context” field that holds the document text in the metadata is not indexed. Currently you need to specify explicitly the fields you do want to index. For more information checkout Pinecone’s docs. import os import pinecone api_key = os.getenv("PINECONE_API_KEY") or "PINECONE_API_KEY" # find environment next to your API key in the Pinecone console env = os.getenv("PINECONE_ENVIRONMENT") or "PINECONE_ENVIRONMENT" index_name = "langchain-pinecone-hybrid-search" pinecone.init(api_key=api_key, enviroment=env)
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
5a60b94d46c8-1
pinecone.init(api_key=api_key, enviroment=env) pinecone.whoami() WhoAmIResponse(username='load', user_label='label', projectname='load-test') # create the index pinecone.create_index( name = index_name, dimension = 1536, # dimensionality of dense model metric = "dotproduct", # sparse values supported only for dotproduct pod_type = "s1", metadata_config={"indexed": []} # see explaination above ) Now that its created, we can use it index = pinecone.Index(index_name) Get embeddings and sparse encoders# Embeddings are used for the dense vectors, tokenizer is used for the sparse vector from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() To encode the text to sparse values you can either choose SPLADE or BM25. For out of domain tasks we recommend using BM25. For more information about the sparse encoders you can checkout pinecone-text library docs. from pinecone_text.sparse import BM25Encoder # or from pinecone_text.sparse import SpladeEncoder if you wish to work with SPLADE # use default tf-idf values bm25_encoder = BM25Encoder().default() The above code is using default tfids values. It’s highly recommended to fit the tf-idf values to your own corpus. You can do it as follow: corpus = ["foo", "bar", "world", "hello"] # fit tf-idf values on your corpus bm25_encoder.fit(corpus) # store the values to a json file bm25_encoder.dump("bm25_values.json") # load to your BM25Encoder object bm25_encoder = BM25Encoder().load("bm25_values.json") Load Retriever#
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
5a60b94d46c8-2
Load Retriever# We can now construct the retriever! retriever = PineconeHybridSearchRetriever(embeddings=embeddings, sparse_encoder=bm25_encoder, index=index) Add texts (if necessary)# We can optionally add texts to the retriever (if they aren’t already in there) retriever.add_texts(["foo", "bar", "world", "hello"]) 100%|██████████| 1/1 [00:02<00:00, 2.27s/it] Use Retriever# We can now use the retriever! result = retriever.get_relevant_documents("foo") result[0] Document(page_content='foo', metadata={}) previous Metal next PubMed Retriever Contents Setup Pinecone Get embeddings and sparse encoders Load Retriever Add texts (if necessary) Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
f753387f45cc-0
.ipynb .pdf VectorStore Contents Maximum Marginal Relevance Retrieval Similarity Score Threshold Retrieval Specifying top k VectorStore# The index - and therefore the retriever - that LangChain has the most support for is the VectorStoreRetriever. As the name suggests, this retriever is backed heavily by a VectorStore. Once you construct a VectorStore, its very easy to construct a retriever. Let’s walk through an example. from langchain.document_loaders import TextLoader loader = TextLoader('../../../state_of_the_union.txt') from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import FAISS from langchain.embeddings import OpenAIEmbeddings documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db = FAISS.from_documents(texts, embeddings) Exiting: Cleaning up .chroma directory retriever = db.as_retriever() docs = retriever.get_relevant_documents("what did he say about ketanji brown jackson") Maximum Marginal Relevance Retrieval# By default, the vectorstore retriever uses similarity search. If the underlying vectorstore support maximum marginal relevance search, you can specify that as the search type. retriever = db.as_retriever(search_type="mmr") docs = retriever.get_relevant_documents("what did he say abotu ketanji brown jackson") Similarity Score Threshold Retrieval# You can also a retrieval method that sets a similarity score threshold and only returns documents with a score above that threshold retriever = db.as_retriever(search_type="similarity_score_threshold", search_kwargs={"score_threshold": .5})
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html
f753387f45cc-1
docs = retriever.get_relevant_documents("what did he say abotu ketanji brown jackson") Specifying top k# You can also specify search kwargs like k to use when doing retrieval. retriever = db.as_retriever(search_kwargs={"k": 1}) docs = retriever.get_relevant_documents("what did he say abotu ketanji brown jackson") len(docs) 1 previous Time Weighted VectorStore next Vespa Contents Maximum Marginal Relevance Retrieval Similarity Score Threshold Retrieval Specifying top k By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html
ace199ba603c-0
.ipynb .pdf kNN Contents Create New Retriever with Texts Use Retriever kNN# In statistics, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method first developed by Evelyn Fix and Joseph Hodges in 1951, and later expanded by Thomas Cover. It is used for classification and regression. This notebook goes over how to use a retriever that under the hood uses an kNN. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb from langchain.retrievers import KNNRetriever from langchain.embeddings import OpenAIEmbeddings Create New Retriever with Texts# retriever = KNNRetriever.from_texts(["foo", "bar", "world", "hello", "foo bar"], OpenAIEmbeddings()) Use Retriever# We can now use the retriever! result = retriever.get_relevant_documents("foo") result [Document(page_content='foo', metadata={}), Document(page_content='foo bar', metadata={}), Document(page_content='hello', metadata={}), Document(page_content='bar', metadata={})] previous ElasticSearch BM25 next Metal Contents Create New Retriever with Texts Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/knn.html
e9690631498a-0
.ipynb .pdf Contextual Compression Contents Contextual Compression Using a vanilla vector store retriever Adding contextual compression with an LLMChainExtractor More built-in compressors: filters LLMChainFilter EmbeddingsFilter Stringing compressors and document transformers together Contextual Compression# This notebook introduces the concept of DocumentCompressors and the ContextualCompressionRetriever. The core idea is simple: given a specific query, we should be able to return only the documents relevant to that query, and only the parts of those documents that are relevant. The ContextualCompressionsRetriever is a wrapper for another retriever that iterates over the initial output of the base retriever and filters and compresses those initial documents, so that only the most relevant information is returned. # Helper function for printing docs def pretty_print_docs(docs): print(f"\n{'-' * 100}\n".join([f"Document {i+1}:\n\n" + d.page_content for i, d in enumerate(docs)])) Using a vanilla vector store retriever# Let’s start by initializing a simple vector store retriever and storing the 2023 State of the Union speech (in chunks). We can see that given an example question our retriever returns one or two relevant docs and a few irrelevant docs. And even the relevant docs have a lot of irrelevant information in them. from langchain.text_splitter import CharacterTextSplitter from langchain.embeddings import OpenAIEmbeddings from langchain.document_loaders import TextLoader from langchain.vectorstores import FAISS documents = TextLoader('../../../state_of_the_union.txt').load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents)
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-1
texts = text_splitter.split_documents(documents) retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever() docs = retriever.get_relevant_documents("What did the president say about Ketanji Brown Jackson") pretty_print_docs(docs) Document 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. ---------------------------------------------------------------------------------------------------- Document 2: 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.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-2
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. ---------------------------------------------------------------------------------------------------- Document 3: And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. First, beat the opioid epidemic. ---------------------------------------------------------------------------------------------------- Document 4: Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. That ends on my watch. Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-3
Let’s pass the Paycheck Fairness Act and paid leave. Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges. Adding contextual compression with an LLMChainExtractor# Now let’s wrap our base retriever with a ContextualCompressionRetriever. We’ll add an LLMChainExtractor, which will iterate over the initially returned documents and extract from each only the content that is relevant to the query. from langchain.llms import OpenAI from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import LLMChainExtractor llm = OpenAI(temperature=0) compressor = LLMChainExtractor.from_llm(llm) compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever) compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brown") pretty_print_docs(compressed_docs) Document 1: "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." ---------------------------------------------------------------------------------------------------- Document 2:
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-4
---------------------------------------------------------------------------------------------------- Document 2: "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." More built-in compressors: filters# LLMChainFilter# The LLMChainFilter is slightly simpler but more robust compressor that uses an LLM chain to decide which of the initially retrieved documents to filter out and which ones to return, without manipulating the document contents. from langchain.retrievers.document_compressors import LLMChainFilter _filter = LLMChainFilter.from_llm(llm) compression_retriever = ContextualCompressionRetriever(base_compressor=_filter, base_retriever=retriever) compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brown") pretty_print_docs(compressed_docs) Document 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. EmbeddingsFilter#
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-5
EmbeddingsFilter# Making an extra LLM call over each retrieved document is expensive and slow. The EmbeddingsFilter provides a cheaper and faster option by embedding the documents and query and only returning those documents which have sufficiently similar embeddings to the query. from langchain.embeddings import OpenAIEmbeddings from langchain.retrievers.document_compressors import EmbeddingsFilter embeddings = OpenAIEmbeddings() embeddings_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76) compression_retriever = ContextualCompressionRetriever(base_compressor=embeddings_filter, base_retriever=retriever) compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brown") pretty_print_docs(compressed_docs) Document 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. ---------------------------------------------------------------------------------------------------- Document 2:
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-6
---------------------------------------------------------------------------------------------------- Document 2: 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. ---------------------------------------------------------------------------------------------------- Document 3: And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. First, beat the opioid epidemic. Stringing compressors and document transformers together#
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-7
First, beat the opioid epidemic. Stringing compressors and document transformers together# Using the DocumentCompressorPipeline we can also easily combine multiple compressors in sequence. Along with compressors we can add BaseDocumentTransformers to our pipeline, which don’t perform any contextual compression but simply perform some transformation on a set of documents. For example TextSplitters can be used as document transformers to split documents into smaller pieces, and the EmbeddingsRedundantFilter can be used to filter out redundant documents based on embedding similarity between documents. Below we create a compressor pipeline by first splitting our docs into smaller chunks, then removing redundant documents, and then filtering based on relevance to the query. from langchain.document_transformers import EmbeddingsRedundantFilter from langchain.retrievers.document_compressors import DocumentCompressorPipeline from langchain.text_splitter import CharacterTextSplitter splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0, separator=". ") redundant_filter = EmbeddingsRedundantFilter(embeddings=embeddings) relevant_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76) pipeline_compressor = DocumentCompressorPipeline( transformers=[splitter, redundant_filter, relevant_filter] ) compression_retriever = ContextualCompressionRetriever(base_compressor=pipeline_compressor, base_retriever=retriever) compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brown") pretty_print_docs(compressed_docs) Document 1: 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 ---------------------------------------------------------------------------------------------------- Document 2:
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e9690631498a-8
---------------------------------------------------------------------------------------------------- Document 2: As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year ---------------------------------------------------------------------------------------------------- Document 3: 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 previous Cohere Reranker next Databerry Contents Contextual Compression Using a vanilla vector store retriever Adding contextual compression with an LLMChainExtractor More built-in compressors: filters LLMChainFilter EmbeddingsFilter Stringing compressors and document transformers together By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 07, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
b43c1b8a4702-0
.ipynb .pdf Arxiv Contents Installation Examples Running retriever Question Answering on facts Arxiv# arXiv is an open-access archive for 2 million scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics. This notebook shows how to retrieve scientific articles from Arxiv.org into the Document format that is used downstream. Installation# First, you need to install arxiv python package. #!pip install arxiv ArxivRetriever has these arguments: optional load_max_docs: default=100. Use it to limit number of downloaded documents. It takes time to download all 100 documents, so use a small number for experiments. There is a hard limit of 300 for now. optional load_all_available_meta: default=False. By default only the most important fields downloaded: Published (date when document was published/last updated), Title, Authors, Summary. If True, other fields also downloaded. get_relevant_documents() has one argument, query: free text which used to find documents in Arxiv.org Examples# Running retriever# from langchain.retrievers import ArxivRetriever retriever = ArxivRetriever(load_max_docs=2) docs = retriever.get_relevant_documents(query='1605.08386') docs[0].metadata # meta-information of the Document {'Published': '2016-05-26', 'Title': 'Heat-bath random walks with Markov bases', 'Authors': 'Caprice Stanley, Tobias Windisch',
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html
b43c1b8a4702-1
'Authors': 'Caprice Stanley, Tobias Windisch', 'Summary': 'Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.'} docs[0].page_content[:400] # a content of the Document 'arXiv:1605.08386v1 [math.CO] 26 May 2016\nHEAT-BATH RANDOM WALKS WITH MARKOV BASES\nCAPRICE STANLEY AND TOBIAS WINDISCH\nAbstract. Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on fibers of a\nfixed integer matrix can be bounded from above by a constant. We then study the mixing\nbehaviour of heat-b' Question Answering on facts# # get a token: https://platform.openai.com/account/api-keys from getpass import getpass OPENAI_API_KEY = getpass() import os os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY from langchain.chat_models import ChatOpenAI from langchain.chains import ConversationalRetrievalChain model = ChatOpenAI(model_name='gpt-3.5-turbo') # switch to 'gpt-4' qa = ConversationalRetrievalChain.from_llm(model,retriever=retriever) questions = [
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html
b43c1b8a4702-2
questions = [ "What are Heat-bath random walks with Markov base?", "What is the ImageBind model?", "How does Compositional Reasoning with Large Language Models works?", ] chat_history = [] for question in questions: result = qa({"question": question, "chat_history": chat_history}) chat_history.append((question, result['answer'])) print(f"-> **Question**: {question} \n") print(f"**Answer**: {result['answer']} \n") -> **Question**: What are Heat-bath random walks with Markov base? **Answer**: I'm not sure, as I don't have enough context to provide a definitive answer. The term "Heat-bath random walks with Markov base" is not mentioned in the given text. Could you provide more information or context about where you encountered this term? -> **Question**: What is the ImageBind model? **Answer**: ImageBind is an approach developed by Facebook AI Research to learn a joint embedding across six different modalities, including images, text, audio, depth, thermal, and IMU data. The approach uses the binding property of images to align each modality's embedding to image embeddings and achieve an emergent alignment across all modalities. This enables novel multimodal capabilities, including cross-modal retrieval, embedding-space arithmetic, and audio-to-image generation, among others. The approach sets a new state-of-the-art on emergent zero-shot recognition tasks across modalities, outperforming specialist supervised models. Additionally, it shows strong few-shot recognition results and serves as a new way to evaluate vision models for visual and non-visual tasks. -> **Question**: How does Compositional Reasoning with Large Language Models works?
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html