id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
af7149cb26dd-3
text text (42, 1) str None Deep Lake, for now, is single writer and multiple reader. Setting read_only=True helps to avoid acquring the writer lock. Retrieval Question/Answering# from langchain.chains import RetrievalQA from langchain.llms import OpenAIChat qa = RetrievalQA.from_chain_type(llm=OpenAIChat(model='gpt-3.5-turbo'), chain_type='stuff', retriever=db.as_retriever()) /home/leo/.local/lib/python3.10/site-packages/langchain/llms/openai.py:624: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn( query = 'What did the president say about Ketanji Brown Jackson' qa.run(query) 'The president nominated Ketanji Brown Jackson to serve on the United States Supreme Court. He described her as a former top litigator in private practice, a former federal public defender, a consensus builder, and from a family of public school educators and police officers. He also mentioned that she has received broad support from various groups since being nominated.' Attribute based filtering in metadata# import random for d in docs: d.metadata['year'] = random.randint(2012, 2014) db = DeepLake.from_documents(docs, embeddings, dataset_path="./my_deeplake/", overwrite=True) ./my_deeplake/ loaded successfully. Evaluating ingest: 100%|██████████| 1/1 [00:04<00:00 Dataset(path='./my_deeplake/', tensors=['embedding', 'ids', 'metadata', 'text'])
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
af7149cb26dd-4
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 db.similarity_search('What did the president say about Ketanji Brown Jackson', filter={'year': 2013}) 100%|██████████| 4/4 [00:00<00:00, 1080.24it/s] [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
af7149cb26dd-5
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})] Choosing distance function# Distance function L2 for Euclidean, L1 for Nuclear, Max l-infinity distnace, cos for cosine similarity, dot for dot product db.similarity_search('What did the president say about Ketanji Brown Jackson?', distance_metric='cos')
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
af7149cb26dd-6
[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
af7149cb26dd-7
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
af7149cb26dd-8
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}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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
af7149cb26dd-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 Chroma 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 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
3d20810c0eb5-0
.ipynb .pdf LanceDB LanceDB# LanceDB is an open-source database for vector-search built with persistent storage, which greatly simplifies retrevial, filtering and management of embeddings. Fully open source. This notebook shows how to use functionality related to the LanceDB vector database based on the Lance data format. !pip install lancedb 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 import OpenAIEmbeddings from langchain.vectorstores import LanceDB from langchain.document_loaders import TextLoader from langchain.text_splitter import CharacterTextSplitter loader = TextLoader('../../../state_of_the_union.txt') documents = loader.load() documents = CharacterTextSplitter().split_documents(documents) embeddings = OpenAIEmbeddings() import lancedb db = lancedb.connect('/tmp/lancedb') table = db.create_table("my_table", data=[ {"vector": embeddings.embed_query("Hello World"), "text": "Hello World", "id": "1"} ], mode="overwrite") docsearch = LanceDB.from_documents(documents, embeddings, connection=table) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) print(docs[0].page_content) 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.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/lancedb.html
3d20810c0eb5-1
I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. I’ve worked on these issues a long time. I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. So let’s not abandon our streets. Or choose between safety and equal justice. Let’s come together to protect our communities, restore trust, and hold law enforcement accountable. That’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers. That’s why the American Rescue Plan provided $350 Billion that cities, states, and counties can use to hire more police and invest in proven strategies like community violence interruption—trusted messengers breaking the cycle of violence and trauma and giving young people hope. We should all agree: The answer is not to Defund the police. The answer is to FUND the police with the resources and training they need to protect our communities. I ask Democrats and Republicans alike: Pass my budget and keep our neighborhoods safe. And I will keep doing everything in my power to crack down on gun trafficking and ghost guns you can buy online and make at home—they have no serial numbers and can’t be traced. And I ask Congress to pass proven measures to reduce gun violence. Pass universal background checks. Why should anyone on a terrorist list be able to purchase a weapon? Ban assault weapons and high-capacity magazines. Repeal the liability shield that makes gun manufacturers the only industry in America that can’t be sued. These laws don’t infringe on the Second Amendment. They save lives.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/lancedb.html
3d20810c0eb5-2
These laws don’t infringe on the Second Amendment. They save lives. The most fundamental right in America is the right to vote – and to have it counted. And it’s under assault. 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. 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/lancedb.html
3d20810c0eb5-3
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. previous FAISS next MatchingEngine By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/lancedb.html
d8f072b2b2a3-0
.ipynb .pdf SKLearnVectorStore Contents Basic usage Load a sample document corpus Create the SKLearnVectorStore, index the document corpus and run a sample query Saving and loading a vector store Clean-up SKLearnVectorStore# scikit-learn is an open source collection of machine learning algorithms, including some implementations of the k nearest neighbors. SKLearnVectorStore wraps this implementation and adds the possibility to persist the vector store in json, bson (binary json) or Apache Parquet format. This notebook shows how to use the SKLearnVectorStore vector database. %pip install scikit-learn # # if you plan to use bson serialization, install also: # %pip install bson # # if you plan to use parquet serialization, install also: %pip install pandas pyarrow To use OpenAI embeddings, you will need an OpenAI key. You can get one at https://platform.openai.com/account/api-keys or feel free to use any other embeddings. import os from getpass import getpass os.environ['OPENAI_API_KEY'] = getpass('Enter your OpenAI key:') Basic usage# Load a sample document corpus# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import SKLearnVectorStore 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() Create the SKLearnVectorStore, index the document corpus and run a sample query# import tempfile persist_path = os.path.join(tempfile.gettempdir(), 'union.parquet')
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/sklearn.html
d8f072b2b2a3-1
persist_path = os.path.join(tempfile.gettempdir(), 'union.parquet') vector_store = SKLearnVectorStore.from_documents( documents=docs, embedding=embeddings, persist_path=persist_path, # persist_path and serializer are optional serializer='parquet' ) query = "What did the president say about Ketanji Brown Jackson" docs = vector_store.similarity_search(query) print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Saving and loading a vector store# vector_store.persist() print('Vector store was persisted to', persist_path) Vector store was persisted to /var/folders/6r/wc15p6m13nl_nl_n_xfqpc5c0000gp/T/union.parquet vector_store2 = SKLearnVectorStore( embedding=embeddings, persist_path=persist_path, serializer='parquet' ) print('A new instance of vector store was loaded from', persist_path)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/sklearn.html
d8f072b2b2a3-2
) print('A new instance of vector store was loaded from', persist_path) A new instance of vector store was loaded from /var/folders/6r/wc15p6m13nl_nl_n_xfqpc5c0000gp/T/union.parquet docs = vector_store2.similarity_search(query) print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Clean-up# os.remove(persist_path) previous Redis next Supabase (Postgres) Contents Basic usage Load a sample document corpus Create the SKLearnVectorStore, index the document corpus and run a sample query Saving and loading a vector store Clean-up By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/sklearn.html
d37b069f0fbd-0
.ipynb .pdf Getting Started Getting Started# The default recommended text splitter is the RecursiveCharacterTextSplitter. This text splitter takes a list of characters. It tries to create chunks based on splitting on the first character, but if any chunks are too large it then moves onto the next character, and so forth. By default the characters it tries to split on are ["\n\n", "\n", " ", ""] In addition to controlling which characters you can split on, you can also control a few other things: length_function: how the length of chunks is calculated. Defaults to just counting number of characters, but it’s pretty common to pass a token counter here. chunk_size: the maximum size of your chunks (as measured by the length function). chunk_overlap: the maximum overlap between chunks. It can be nice to have some overlap to maintain some continuity between chunks (eg do a sliding window). # This is a long document we can split up. with open('../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter( # Set a really small chunk size, just to show. chunk_size = 100, chunk_overlap = 20, length_function = len, ) texts = text_splitter.create_documents([state_of_the_union]) print(texts[0]) print(texts[1]) page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and' lookup_str='' metadata={} lookup_index=0 page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.' lookup_str='' metadata={} lookup_index=0 previous Text Splitters next Character By Harrison Chase
https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html
d37b069f0fbd-1
previous Text Splitters next Character By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html
5dd940d4791b-0
.ipynb .pdf tiktoken (OpenAI) tokenizer tiktoken (OpenAI) tokenizer# tiktoken is a fast BPE tokenizer created by OpenAI. We can use it to estimate tokens used. It will probably be more accurate for the OpenAI models. How the text is split: by character passed in How the chunk size is measured: by tiktoken tokenizer #!pip install tiktoken # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import CharacterTextSplitter text_splitter = CharacterTextSplitter.from_tiktoken_encoder(chunk_size=100, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) 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. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. previous Hugging Face tokenizer next Vectorstores By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken.html
68132bbe2d9e-0
.ipynb .pdf Character Character# This is the simplest method. This splits based on characters (by default “\n\n”) and measure chunk length by number of characters. How the text is split: by single character How the chunk size is measured: by number of characters # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import CharacterTextSplitter text_splitter = CharacterTextSplitter( separator = "\n\n", chunk_size = 1000, chunk_overlap = 200, length_function = len, ) texts = text_splitter.create_documents([state_of_the_union]) print(texts[0])
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
68132bbe2d9e-1
print(texts[0]) 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.' lookup_str='' metadata={} lookup_index=0 Here’s an example of passing metadata along with the documents, notice that it is split along with the documents. metadatas = [{"document": 1}, {"document": 2}] documents = text_splitter.create_documents([state_of_the_union, state_of_the_union], metadatas=metadatas) print(documents[0])
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
68132bbe2d9e-2
print(documents[0]) 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.' lookup_str='' metadata={'document': 1} lookup_index=0 text_splitter.split_text(state_of_the_union)[0]
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
68132bbe2d9e-3
text_splitter.split_text(state_of_the_union)[0] '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.' previous Getting Started next CodeTextSplitter By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
7a7e0c794cdf-0
.ipynb .pdf spaCy spaCy# spaCy is an open-source software library for advanced natural language processing, written in the programming languages Python and Cython. Another alternative to NLTK is to use Spacy tokenizer. How the text is split: by spaCy tokenizer How the chunk size is measured: by number of characters #!pip install spacy # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import SpacyTextSplitter text_splitter = SpacyTextSplitter(chunk_size=1000) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) 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. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. And with an unwavering resolve that freedom will always triumph over tyranny. Six 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. He thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. He met the Ukrainian people. From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. previous Recursive Character next Tiktoken By Harrison Chase
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html
7a7e0c794cdf-1
previous Recursive Character next Tiktoken By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html
f37275476d02-0
.ipynb .pdf CodeTextSplitter Contents Python JS Markdown Latex HTML CodeTextSplitter# CodeTextSplitter allows you to split your code with multiple language support. Import enum Language and specify the language. from langchain.text_splitter import ( RecursiveCharacterTextSplitter, Language, ) # Full list of support languages [e.value for e in Language] ['cpp', 'go', 'java', 'js', 'php', 'proto', 'python', 'rst', 'ruby', 'rust', 'scala', 'swift', 'markdown', 'latex', 'html'] # You can also see the separators used for a given language RecursiveCharacterTextSplitter.get_separators_for_language(Language.PYTHON) ['\nclass ', '\ndef ', '\n\tdef ', '\n\n', '\n', ' ', ''] Python# Here’s an example using the PythonTextSplitter PYTHON_CODE = """ def hello_world(): print("Hello, World!") # Call the function hello_world() """ python_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.PYTHON, chunk_size=50, chunk_overlap=0 ) python_docs = python_splitter.create_documents([PYTHON_CODE]) python_docs [Document(page_content='def hello_world():\n print("Hello, World!")', metadata={}), Document(page_content='# Call the function\nhello_world()', metadata={})] JS# Here’s an example using the JS text splitter JS_CODE = """ function helloWorld() { console.log("Hello, World!"); } // Call the function helloWorld(); """ js_splitter = RecursiveCharacterTextSplitter.from_language(
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html
f37275476d02-1
helloWorld(); """ js_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.JS, chunk_size=60, chunk_overlap=0 ) js_docs = js_splitter.create_documents([JS_CODE]) js_docs [Document(page_content='function helloWorld() {\n console.log("Hello, World!");\n}', metadata={}), Document(page_content='// Call the function\nhelloWorld();', metadata={})] Markdown# Here’s an example using the Markdown text splitter. markdown_text = """ # 🦜️🔗 LangChain ⚡ Building applications with LLMs through composability ⚡ ## Quick Install ```bash # Hopefully this code block isn't split pip install langchain ``` As an open source project in a rapidly developing field, we are extremely open to contributions. """ md_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.MARKDOWN, chunk_size=60, chunk_overlap=0 ) md_docs = md_splitter.create_documents([markdown_text]) md_docs [Document(page_content='# 🦜️🔗 LangChain', metadata={}), Document(page_content='⚡ Building applications with LLMs through composability ⚡', metadata={}), Document(page_content='## Quick Install', metadata={}), Document(page_content="```bash\n# Hopefully this code block isn't split", metadata={}), Document(page_content='pip install langchain', metadata={}), Document(page_content='```', metadata={}), Document(page_content='As an open source project in a rapidly developing field, we', metadata={}), Document(page_content='are extremely open to contributions.', metadata={})] Latex# Here’s an example on Latex text latex_text = """ \documentclass{article}
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html
f37275476d02-2
latex_text = """ \documentclass{article} \begin{document} \maketitle \section{Introduction} Large language models (LLMs) are a type of machine learning model that can be trained on vast amounts of text data to generate human-like language. In recent years, LLMs have made significant advances in a variety of natural language processing tasks, including language translation, text generation, and sentiment analysis. \subsection{History of LLMs} The earliest LLMs were developed in the 1980s and 1990s, but they were limited by the amount of data that could be processed and the computational power available at the time. In the past decade, however, advances in hardware and software have made it possible to train LLMs on massive datasets, leading to significant improvements in performance. \subsection{Applications of LLMs} LLMs have many applications in industry, including chatbots, content creation, and virtual assistants. They can also be used in academia for research in linguistics, psychology, and computational linguistics. \end{document} """ latex_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.MARKDOWN, chunk_size=60, chunk_overlap=0 ) latex_docs = latex_splitter.create_documents([latex_text]) latex_docs [Document(page_content='\\documentclass{article}\n\n\x08egin{document}\n\n\\maketitle', metadata={}), Document(page_content='\\section{Introduction}', metadata={}), Document(page_content='Large language models (LLMs) are a type of machine learning', metadata={}), Document(page_content='model that can be trained on vast amounts of text data to', metadata={}), Document(page_content='generate human-like language. In recent years, LLMs have', metadata={}),
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html
f37275476d02-3
Document(page_content='made significant advances in a variety of natural language', metadata={}), Document(page_content='processing tasks, including language translation, text', metadata={}), Document(page_content='generation, and sentiment analysis.', metadata={}), Document(page_content='\\subsection{History of LLMs}', metadata={}), Document(page_content='The earliest LLMs were developed in the 1980s and 1990s,', metadata={}), Document(page_content='but they were limited by the amount of data that could be', metadata={}), Document(page_content='processed and the computational power available at the', metadata={}), Document(page_content='time. In the past decade, however, advances in hardware and', metadata={}), Document(page_content='software have made it possible to train LLMs on massive', metadata={}), Document(page_content='datasets, leading to significant improvements in', metadata={}), Document(page_content='performance.', metadata={}), Document(page_content='\\subsection{Applications of LLMs}', metadata={}), Document(page_content='LLMs have many applications in industry, including', metadata={}), Document(page_content='chatbots, content creation, and virtual assistants. They', metadata={}), Document(page_content='can also be used in academia for research in linguistics,', metadata={}), Document(page_content='psychology, and computational linguistics.', metadata={}), Document(page_content='\\end{document}', metadata={})] HTML# Here’s an example using an HTML text splitter html_text = """ <!DOCTYPE html> <html> <head> <title>🦜️🔗 LangChain</title> <style> body { font-family: Arial, sans-serif; } h1 { color: darkblue; } </style> </head>
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html
f37275476d02-4
color: darkblue; } </style> </head> <body> <div> <h1>🦜️🔗 LangChain</h1> <p>⚡ Building applications with LLMs through composability ⚡</p> </div> <div> As an open source project in a rapidly developing field, we are extremely open to contributions. </div> </body> </html> """ html_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.MARKDOWN, chunk_size=60, chunk_overlap=0 ) html_docs = html_splitter.create_documents([html_text]) html_docs [Document(page_content='<!DOCTYPE html>\n<html>\n <head>', metadata={}), Document(page_content='<title>🦜️🔗 LangChain</title>\n <style>', metadata={}), Document(page_content='body {', metadata={}), Document(page_content='font-family: Arial, sans-serif;', metadata={}), Document(page_content='}\n h1 {', metadata={}), Document(page_content='color: darkblue;\n }', metadata={}), Document(page_content='</style>\n </head>\n <body>\n <div>', metadata={}), Document(page_content='<h1>🦜️🔗 LangChain</h1>', metadata={}), Document(page_content='<p>⚡ Building applications with LLMs through', metadata={}), Document(page_content='composability ⚡</p>', metadata={}), Document(page_content='</div>\n <div>', metadata={}), Document(page_content='As an open source project in a rapidly', metadata={}),
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html
f37275476d02-5
Document(page_content='As an open source project in a rapidly', metadata={}), Document(page_content='developing field, we are extremely open to contributions.', metadata={}), Document(page_content='</div>\n </body>\n</html>', metadata={})] previous Character next NLTK Contents Python JS Markdown Latex HTML By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html
48462f38fd74-0
.ipynb .pdf Tiktoken Tiktoken# tiktoken is a fast BPE tokeniser created by OpenAI. How the text is split: by tiktoken tokens How the chunk size is measured: by tiktoken tokens #!pip install tiktoken # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import TokenTextSplitter text_splitter = TokenTextSplitter(chunk_size=10, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) Madam Speaker, Madam Vice President, our previous spaCy next Hugging Face tokenizer By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken_splitter.html
5eee34143928-0
.ipynb .pdf NLTK NLTK# The Natural Language Toolkit, or more commonly NLTK, is a suite of libraries and programs for symbolic and statistical natural language processing (NLP) for English written in the Python programming language. Rather than just splitting on “\n\n”, we can use NLTK to split based on NLTK tokenizers. How the text is split: by NLTK tokenizer. How the chunk size is measured:by number of characters #pip install nltk # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import NLTKTextSplitter text_splitter = NLTKTextSplitter(chunk_size=1000) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) 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. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. And with an unwavering resolve that freedom will always triumph over tyranny. Six 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. He thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. He met the Ukrainian people. From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html
5eee34143928-1
Groups of citizens blocking tanks with their bodies. previous CodeTextSplitter next Recursive Character By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html
3d497d4e2cfa-0
.ipynb .pdf Hugging Face tokenizer Hugging Face tokenizer# Hugging Face has many tokenizers. We use Hugging Face tokenizer, the GPT2TokenizerFast to count the text length in tokens. How the text is split: by character passed in How the chunk size is measured: by number of tokens calculated by the Hugging Face tokenizer from transformers import GPT2TokenizerFast tokenizer = GPT2TokenizerFast.from_pretrained("gpt2") # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import CharacterTextSplitter text_splitter = CharacterTextSplitter.from_huggingface_tokenizer(tokenizer, chunk_size=100, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) 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. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. previous Tiktoken next tiktoken (OpenAI) tokenizer By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/huggingface_length_function.html
e50487211f68-0
.ipynb .pdf Recursive Character Recursive Character# This text splitter is the recommended one for generic text. It is parameterized by a list of characters. It tries to split on them in order until the chunks are small enough. The default list is ["\n\n", "\n", " ", ""]. This has the effect of trying to keep all paragraphs (and then sentences, and then words) together as long as possible, as those would generically seem to be the strongest semantically related pieces of text. How the text is split: by list of characters How the chunk size is measured: by number of characters # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter( # Set a really small chunk size, just to show. chunk_size = 100, chunk_overlap = 20, length_function = len, ) texts = text_splitter.create_documents([state_of_the_union]) print(texts[0]) print(texts[1]) page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and' lookup_str='' metadata={} lookup_index=0 page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.' lookup_str='' metadata={} lookup_index=0 text_splitter.split_text(state_of_the_union)[:2] ['Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and', 'of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.'] previous NLTK next spaCy By Harrison Chase
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html
e50487211f68-1
previous NLTK next spaCy By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html
d45bf0c52292-0
.ipynb .pdf ChatGPT Plugin Contents Using the ChatGPT Retriever Plugin ChatGPT Plugin# OpenAI plugins connect ChatGPT to third-party applications. These plugins enable ChatGPT to interact with APIs defined by developers, enhancing ChatGPT’s capabilities and allowing it to perform a wide range of actions. Plugins can allow ChatGPT to do things like: Retrieve real-time information; e.g., sports scores, stock prices, the latest news, etc. Retrieve knowledge-base information; e.g., company docs, personal notes, etc. Perform actions on behalf of the user; e.g., booking a flight, ordering food, etc. This notebook shows how to use the ChatGPT Retriever Plugin within LangChain. # STEP 1: Load # Load documents using LangChain's DocumentLoaders # This is from https://langchain.readthedocs.io/en/latest/modules/document_loaders/examples/csv.html from langchain.document_loaders.csv_loader import CSVLoader loader = CSVLoader(file_path='../../document_loaders/examples/example_data/mlb_teams_2012.csv') data = loader.load() # STEP 2: Convert # Convert Document to format expected by https://github.com/openai/chatgpt-retrieval-plugin from typing import List from langchain.docstore.document import Document import json def write_json(path: str, documents: List[Document])-> None: results = [{"text": doc.page_content} for doc in documents] with open(path, "w") as f: json.dump(results, f, indent=2) write_json("foo.json", data) # STEP 3: Use # Ingest this as you would any other json file in https://github.com/openai/chatgpt-retrieval-plugin/tree/main/scripts/process_json
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html
d45bf0c52292-1
Using the ChatGPT Retriever Plugin# Okay, so we’ve created the ChatGPT Retriever Plugin, but how do we actually use it? The below code walks through how to do that. We want to use ChatGPTPluginRetriever 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.retrievers import ChatGPTPluginRetriever retriever = ChatGPTPluginRetriever(url="http://0.0.0.0:8000", bearer_token="foo") retriever.get_relevant_documents("alice's phone number") [Document(page_content="This is Alice's phone number: 123-456-7890", lookup_str='', metadata={'id': '456_0', 'metadata': {'source': 'email', 'source_id': '567', 'url': None, 'created_at': '1609592400.0', 'author': 'Alice', 'document_id': '456'}, 'embedding': None, 'score': 0.925571561}, lookup_index=0), Document(page_content='This is a document about something', lookup_str='', metadata={'id': '123_0', 'metadata': {'source': 'file', 'source_id': 'https://example.com/doc1', 'url': 'https://example.com/doc1', 'created_at': '1609502400.0', 'author': 'Alice', 'document_id': '123'}, 'embedding': None, 'score': 0.6987589}, lookup_index=0),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html
d45bf0c52292-2
Document(page_content='Team: Angels "Payroll (millions)": 154.49 "Wins": 89', lookup_str='', metadata={'id': '59c2c0c1-ae3f-4272-a1da-f44a723ea631_0', 'metadata': {'source': None, 'source_id': None, 'url': None, 'created_at': None, 'author': None, 'document_id': '59c2c0c1-ae3f-4272-a1da-f44a723ea631'}, 'embedding': None, 'score': 0.697888613}, lookup_index=0)] previous Azure Cognitive Search Retriever next Self-querying with Chroma Contents Using the ChatGPT Retriever Plugin By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html
71efb01e3d2c-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
71efb01e3d2c-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
71efb01e3d2c-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 Self-querying with Qdrant 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 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
9d6b31adff14-0
.ipynb .pdf Vespa Vespa# Vespa is a fully featured search engine and vector database. It supports vector search (ANN), lexical search, and search in structured data, all in the same query. This notebook shows how to use Vespa.ai as a LangChain retriever. In order to create a retriever, we use pyvespa to create a connection a Vespa service. #!pip install pyvespa from vespa.application import Vespa vespa_app = Vespa(url="https://doc-search.vespa.oath.cloud") This creates a connection to a Vespa service, here the Vespa documentation search service. Using pyvespa package, you can also connect to a Vespa Cloud instance or a local Docker instance. After connecting to the service, you can set up the retriever: from langchain.retrievers.vespa_retriever import VespaRetriever vespa_query_body = { "yql": "select content from paragraph where userQuery()", "hits": 5, "ranking": "documentation", "locale": "en-us" } vespa_content_field = "content" retriever = VespaRetriever(vespa_app, vespa_query_body, vespa_content_field) This sets up a LangChain retriever that fetches documents from the Vespa application. Here, up to 5 results are retrieved from the content field in the paragraph document type, using doumentation as the ranking method. The userQuery() is replaced with the actual query passed from LangChain. Please refer to the pyvespa documentation for more information. Now you can return the results and continue using the results in LangChain. retriever.get_relevant_documents("what is vespa?")
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html
9d6b31adff14-1
retriever.get_relevant_documents("what is vespa?") previous VectorStore next Weaviate Hybrid Search By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html
8426a36550df-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
8426a36550df-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
8426a36550df-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
8426a36550df-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
8426a36550df-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
8426a36550df-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
8426a36550df-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
8426a36550df-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
8426a36550df-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 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
e82e0605cbc5-0
.ipynb .pdf SVM Contents Create New Retriever with Texts Use Retriever SVM# Support vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection. This notebook goes over how to use a retriever that under the hood uses an SVM using scikit-learn package. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb #!pip install scikit-learn #!pip install lark 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.retrievers import SVMRetriever from langchain.embeddings import OpenAIEmbeddings Create New Retriever with Texts# retriever = SVMRetriever.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='world', metadata={})] previous Self-querying next TF-IDF Contents Create New Retriever with Texts Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/svm.html
c3d8ca1d2cda-0
.ipynb .pdf TF-IDF Contents Create New Retriever with Texts Create a New Retriever with Documents Use Retriever TF-IDF# TF-IDF means term-frequency times inverse document-frequency. This notebook goes over how to use a retriever that under the hood uses TF-IDF using scikit-learn package. For more information on the details of TF-IDF see this blog post. # !pip install scikit-learn from langchain.retrievers import TFIDFRetriever Create New Retriever with Texts# retriever = TFIDFRetriever.from_texts(["foo", "bar", "world", "hello", "foo bar"]) Create a New Retriever with Documents# You can now create a new retriever with the documents you created. from langchain.schema import Document retriever = TFIDFRetriever.from_documents([Document(page_content="foo"), Document(page_content="bar"), Document(page_content="world"), Document(page_content="hello"), Document(page_content="foo bar")]) 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='world', metadata={})] previous SVM next Time Weighted VectorStore Contents Create New Retriever with Texts Create a New Retriever with Documents Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/tf_idf.html
97a9a5836da4-0
.ipynb .pdf Self-querying with Qdrant Contents Creating a Qdrant vectorstore Creating our self-querying retriever Testing it out Filter k Self-querying with Qdrant# Qdrant (read: quadrant ) is a vector similarity search engine. It provides a production-ready service with a convenient API to store, search, and manage points - vectors with an additional payload. Qdrant is tailored to extended filtering support. It makes it useful In the notebook we’ll demo the SelfQueryRetriever wrapped around a Qdrant vector store. Creating a Qdrant vectorstore# First we’ll want to create a Chroma VectorStore and seed it with some data. We’ve created a small demo set of documents that contain summaries of movies. NOTE: The self-query retriever requires you to have lark installed (pip install lark). We also need the qdrant-client package. #!pip install lark qdrant-client 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.schema import Document from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Qdrant embeddings = OpenAIEmbeddings() docs = [ Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}), Document(page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html
97a9a5836da4-1
Document(page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}), Document(page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3}), Document(page_content="Toys come alive and have a blast doing so", metadata={"year": 1995, "genre": "animated"}), Document(page_content="Three men walk into the Zone, three men walk out of the Zone", metadata={"year": 1979, "rating": 9.9, "director": "Andrei Tarkovsky", "genre": "science fiction", "rating": 9.9}) ] vectorstore = Qdrant.from_documents( docs, embeddings, location=":memory:", # Local mode with in-memory storage only collection_name="my_documents", ) Creating our self-querying retriever# Now we can instantiate our retriever. To do this we’ll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents. from langchain.llms import OpenAI from langchain.retrievers.self_query.base import SelfQueryRetriever from langchain.chains.query_constructor.base import AttributeInfo metadata_field_info=[ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html
97a9a5836da4-2
type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", type="float" ), ] document_content_description = "Brief summary of a movie" llm = OpenAI(temperature=0) retriever = SelfQueryRetriever.from_llm(llm, vectorstore, document_content_description, metadata_field_info, verbose=True) Testing it out# And now we can try actually using our retriever! # This example only specifies a relevant query retriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None limit=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'}), Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'rating': 9.9, 'director': 'Andrei Tarkovsky', 'genre': 'science fiction'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6})] # This example only specifies a filter retriever.get_relevant_documents("I want to watch a movie rated higher than 8.5")
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html
97a9a5836da4-3
query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) limit=None [Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'rating': 9.9, 'director': 'Andrei Tarkovsky', 'genre': 'science fiction'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6})] # This example specifies a query and a filter retriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None [Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'year': 2019, 'director': 'Greta Gerwig', 'rating': 8.3})] # This example specifies a composite filter retriever.get_relevant_documents("What's a highly rated (above 8.5) science fiction film?") query=' ' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='science fiction')]) limit=None
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html
97a9a5836da4-4
[Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'rating': 9.9, 'director': 'Andrei Tarkovsky', 'genre': 'science fiction'})] # This example specifies a query and composite filter retriever.get_relevant_documents("What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated") query='toys' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GT: 'gt'>, attribute='year', value=1990), Comparison(comparator=<Comparator.LT: 'lt'>, attribute='year', value=2005), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated')]) limit=None [Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})] Filter k# We can also use the self query retriever to specify k: the number of documents to fetch. We can do this by passing enable_limit=True to the constructor. retriever = SelfQueryRetriever.from_llm( llm, vectorstore, document_content_description, metadata_field_info, enable_limit=True, verbose=True ) # This example only specifies a relevant query retriever.get_relevant_documents("what are two movies about dinosaurs") query='dinosaur' filter=None limit=2 [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html
97a9a5836da4-5
Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})] previous Pinecone Hybrid Search next Self-querying Contents Creating a Qdrant vectorstore Creating our self-querying retriever Testing it out Filter k By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html
a17616639ebd-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
a17616639ebd-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 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html
497b3d93f1e7-0
.ipynb .pdf Zep Memory Contents Retriever Example Initialize the Zep Chat Message History Class and add a chat message history to the memory store Use the Zep Retriever to vector search over the Zep memory Zep Memory# Retriever Example# This notebook demonstrates how to search historical chat message histories using the Zep Long-term Memory Store. We’ll demonstrate: Adding conversation history to the Zep memory store. Vector search over the conversation history. More on Zep: Zep stores, summarizes, embeds, indexes, and enriches conversational AI chat histories, and exposes them via simple, low-latency APIs. Key Features: Long-term memory persistence, with access to historical messages irrespective of your summarization strategy. Auto-summarization of memory messages based on a configurable message window. A series of summaries are stored, providing flexibility for future summarization strategies. Vector search over memories, with messages automatically embedded on creation. Auto-token counting of memories and summaries, allowing finer-grained control over prompt assembly. Python and JavaScript SDKs. Zep’s Go Extractor model is easily extensible, with a simple, clean interface available to build new enrichment functionality, such as summarizers, entity extractors, embedders, and more. Zep project: getzep/zep from langchain.memory.chat_message_histories import ZepChatMessageHistory from langchain.schema import HumanMessage, AIMessage from uuid import uuid4 # Set this to your Zep server URL ZEP_API_URL = "http://localhost:8000" Initialize the Zep Chat Message History Class and add a chat message history to the memory store# NOTE: Unlike other Retrievers, the content returned by the Zep Retriever is session/user specific. A session_id is required when instantiating the Retriever.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
497b3d93f1e7-1
session_id = str(uuid4()) # This is a unique identifier for the user/session # Set up Zep Chat History. We'll use this to add chat histories to the memory store zep_chat_history = ZepChatMessageHistory( session_id=session_id, url=ZEP_API_URL, ) # Preload some messages into the memory. The default message window is 12 messages. We want to push beyond this to demonstrate auto-summarization. test_history = [ {"role": "human", "content": "Who was Octavia Butler?"}, { "role": "ai", "content": ( "Octavia Estelle Butler (June 22, 1947 – February 24, 2006) was an American" " science fiction author." ), }, {"role": "human", "content": "Which books of hers were made into movies?"}, { "role": "ai", "content": ( "The most well-known adaptation of Octavia Butler's work is the FX series" " Kindred, based on her novel of the same name." ), }, {"role": "human", "content": "Who were her contemporaries?"}, { "role": "ai", "content": ( "Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R." " Delany, and Joanna Russ." ), }, {"role": "human", "content": "What awards did she win?"}, { "role": "ai", "content": ( "Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur" " Fellowship."
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
497b3d93f1e7-2
" Fellowship." ), }, { "role": "human", "content": "Which other women sci-fi writers might I want to read?", }, { "role": "ai", "content": "You might want to read Ursula K. Le Guin or Joanna Russ.", }, { "role": "human", "content": ( "Write a short synopsis of Butler's book, Parable of the Sower. What is it" " about?" ), }, { "role": "ai", "content": ( "Parable of the Sower is a science fiction novel by Octavia Butler," " published in 1993. It follows the story of Lauren Olamina, a young woman" " living in a dystopian future where society has collapsed due to" " environmental disasters, poverty, and violence." ), }, ] for msg in test_history: zep_chat_history.append( HumanMessage(content=msg["content"]) if msg["role"] == "human" else AIMessage(content=msg["content"]) ) Use the Zep Retriever to vector search over the Zep memory# Zep provides native vector search over historical conversation memory. Embedding happens automatically. NOTE: Embedding of messages occurs asynchronously, so the first query may not return results. Subsequent queries will return results as the embeddings are generated. from langchain.retrievers import ZepRetriever zep_retriever = ZepRetriever( session_id=session_id, # Ensure that you provide the session_id when instantiating the Retriever url=ZEP_API_URL,
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
497b3d93f1e7-3
url=ZEP_API_URL, top_k=5, ) await zep_retriever.aget_relevant_documents("Who wrote Parable of the Sower?") [Document(page_content='Who was Octavia Butler?', metadata={'score': 0.7759001673780126, 'uuid': '3a82a02f-056e-4c6a-b960-67ebdf3b2b93', 'created_at': '2023-05-25T15:03:30.2041Z', 'role': 'human', 'token_count': 8}), Document(page_content="Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.", metadata={'score': 0.7602262941130749, 'uuid': 'a2fc9c21-0897-46c8-bef7-6f5c0f71b04a', 'created_at': '2023-05-25T15:03:30.248065Z', 'role': 'ai', 'token_count': 27}), Document(page_content='Who were her contemporaries?', metadata={'score': 0.757553366415519, 'uuid': '41f9c41a-a205-41e1-b48b-a0a4cd943fc8', 'created_at': '2023-05-25T15:03:30.243995Z', 'role': 'human', 'token_count': 8}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
497b3d93f1e7-4
Document(page_content='Octavia Estelle Butler (June 22, 1947 – February 24, 2006) was an American science fiction author.', metadata={'score': 0.7546211059317948, 'uuid': '34678311-0098-4f1a-8fd4-5615ac692deb', 'created_at': '2023-05-25T15:03:30.231427Z', 'role': 'ai', 'token_count': 31}), Document(page_content='Which books of hers were made into movies?', metadata={'score': 0.7496714959247069, 'uuid': '18046c3a-9666-4d3e-b4f0-43d1394732b7', 'created_at': '2023-05-25T15:03:30.236837Z', 'role': 'human', 'token_count': 11})] We can also use the Zep sync API to retrieve results: zep_retriever.get_relevant_documents("Who wrote Parable of the Sower?") [Document(page_content='Parable of the Sower is a science fiction novel by Octavia Butler, published in 1993. It follows the story of Lauren Olamina, a young woman living in a dystopian future where society has collapsed due to environmental disasters, poverty, and violence.', metadata={'score': 0.8897321402776546, 'uuid': '1c09603a-52c1-40d7-9d69-29f26256029c', 'created_at': '2023-05-25T15:03:30.268257Z', 'role': 'ai', 'token_count': 56}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
497b3d93f1e7-5
Document(page_content="Write a short synopsis of Butler's book, Parable of the Sower. What is it about?", metadata={'score': 0.8857628682610436, 'uuid': 'f6706e8c-6c91-452f-8c1b-9559fd924657', 'created_at': '2023-05-25T15:03:30.265302Z', 'role': 'human', 'token_count': 23}), Document(page_content='Who was Octavia Butler?', metadata={'score': 0.7759670375149477, 'uuid': '3a82a02f-056e-4c6a-b960-67ebdf3b2b93', 'created_at': '2023-05-25T15:03:30.2041Z', 'role': 'human', 'token_count': 8}), Document(page_content="Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.", metadata={'score': 0.7602854653476563, 'uuid': 'a2fc9c21-0897-46c8-bef7-6f5c0f71b04a', 'created_at': '2023-05-25T15:03:30.248065Z', 'role': 'ai', 'token_count': 27}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
497b3d93f1e7-6
Document(page_content='You might want to read Ursula K. Le Guin or Joanna Russ.', metadata={'score': 0.7595293992240313, 'uuid': 'f22f2498-6118-4c74-8718-aa89ccd7e3d6', 'created_at': '2023-05-25T15:03:30.261198Z', 'role': 'ai', 'token_count': 18})] previous Wikipedia next Chains Contents Retriever Example Initialize the Zep Chat Message History Class and add a chat message history to the memory store Use the Zep Retriever to vector search over the Zep memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
23b99c2ceefa-0
.ipynb .pdf Time Weighted VectorStore Contents Low Decay Rate High Decay Rate Virtual Time Time Weighted VectorStore# This retriever uses a combination of semantic similarity and a time decay. The algorithm for scoring them is: semantic_similarity + (1.0 - decay_rate) ** hours_passed Notably, hours_passed refers to the hours passed since the object in the retriever was last accessed, not since it was created. This means that frequently accessed objects remain “fresh.” import faiss from datetime import datetime, timedelta from langchain.docstore import InMemoryDocstore from langchain.embeddings import OpenAIEmbeddings from langchain.retrievers import TimeWeightedVectorStoreRetriever from langchain.schema import Document from langchain.vectorstores import FAISS Low Decay Rate# A low decay rate (in this, to be extreme, we will set close to 0) means memories will be “remembered” for longer. A decay rate of 0 means memories never be forgotten, making this retriever equivalent to the vector lookup. # Define your embedding model embeddings_model = OpenAIEmbeddings() # Initialize the vectorstore as empty embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}) retriever = TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, decay_rate=.0000000000000000000000001, k=1) yesterday = datetime.now() - timedelta(days=1) retriever.add_documents([Document(page_content="hello world", metadata={"last_accessed_at": yesterday})]) retriever.add_documents([Document(page_content="hello foo")])
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
23b99c2ceefa-1
retriever.add_documents([Document(page_content="hello foo")]) ['d7f85756-2371-4bdf-9140-052780a0f9b3'] # "Hello World" is returned first because it is most salient, and the decay rate is close to 0., meaning it's still recent enough retriever.get_relevant_documents("hello world") [Document(page_content='hello world', metadata={'last_accessed_at': datetime.datetime(2023, 5, 13, 21, 0, 27, 678341), 'created_at': datetime.datetime(2023, 5, 13, 21, 0, 27, 279596), 'buffer_idx': 0})] High Decay Rate# With a high decay rate (e.g., several 9’s), the recency score quickly goes to 0! If you set this all the way to 1, recency is 0 for all objects, once again making this equivalent to a vector lookup. # Define your embedding model embeddings_model = OpenAIEmbeddings() # Initialize the vectorstore as empty embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}) retriever = TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, decay_rate=.999, k=1) yesterday = datetime.now() - timedelta(days=1) retriever.add_documents([Document(page_content="hello world", metadata={"last_accessed_at": yesterday})]) retriever.add_documents([Document(page_content="hello foo")]) ['40011466-5bbe-4101-bfd1-e22e7f505de2']
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
23b99c2ceefa-2
# "Hello Foo" is returned first because "hello world" is mostly forgotten retriever.get_relevant_documents("hello world") [Document(page_content='hello foo', metadata={'last_accessed_at': datetime.datetime(2023, 4, 16, 22, 9, 2, 494798), 'created_at': datetime.datetime(2023, 4, 16, 22, 9, 2, 178722), 'buffer_idx': 1})] Virtual Time# Using some utils in LangChain, you can mock out the time component from langchain.utils import mock_now import datetime # Notice the last access time is that date time with mock_now(datetime.datetime(2011, 2, 3, 10, 11)): print(retriever.get_relevant_documents("hello world")) [Document(page_content='hello world', metadata={'last_accessed_at': MockDateTime(2011, 2, 3, 10, 11), 'created_at': datetime.datetime(2023, 5, 13, 21, 0, 27, 279596), 'buffer_idx': 0})] previous TF-IDF next VectorStore Contents Low Decay Rate High Decay Rate Virtual Time By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
e6df33fa9f7a-0
.ipynb .pdf Azure Cognitive Search Retriever Contents Set up Azure Cognitive Search Using the Azure Cognitive Search Retriever Azure Cognitive Search Retriever# This notebook shows how to use Azure Cognitive Search (ACS) within LangChain. Set up Azure Cognitive Search# To set up ACS, please follow the instrcutions here. Please note the name of your ACS service, the name of your ACS index, your API key. Your API key can be either Admin or Query key, but as we only read data it is recommended to use a Query key. Using the Azure Cognitive Search Retriever# import os from langchain.retrievers import AzureCognitiveSearchRetriever Set Service Name, Index Name and API key as environment variables (alternatively, you can pass them as arguments to AzureCognitiveSearchRetriever). os.environ["AZURE_COGNITIVE_SEARCH_SERVICE_NAME"] = "<YOUR_ACS_SERVICE_NAME>" os.environ["AZURE_COGNITIVE_SEARCH_INDEX_NAME"] ="<YOUR_ACS_INDEX_NAME>" os.environ["AZURE_COGNITIVE_SEARCH_API_KEY"] = "<YOUR_API_KEY>" Create the Retriever retriever = AzureCognitiveSearchRetriever(content_key="content") Now you can use retrieve documents from Azure Cognitive Search retriever.get_relevant_documents("what is langchain") previous Arxiv next ChatGPT Plugin Contents Set up Azure Cognitive Search Using the Azure Cognitive Search Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/azure-cognitive-search-retriever.html
237e8a3fd5b0-0
.ipynb .pdf Metal Contents Ingest Documents Query Metal# Metal is a managed service for ML Embeddings. This notebook shows how to use Metal’s retriever. First, you will need to sign up for Metal and get an API key. You can do so here # !pip install metal_sdk from metal_sdk.metal import Metal API_KEY = "" CLIENT_ID = "" INDEX_ID = "" metal = Metal(API_KEY, CLIENT_ID, INDEX_ID); Ingest Documents# You only need to do this if you haven’t already set up an index metal.index( {"text": "foo1"}) metal.index( {"text": "foo"}) {'data': {'id': '642739aa7559b026b4430e42', 'text': 'foo', 'createdAt': '2023-03-31T19:51:06.748Z'}} Query# Now that our index is set up, we can set up a retriever and start querying it. from langchain.retrievers import MetalRetriever retriever = MetalRetriever(metal, params={"limit": 2}) retriever.get_relevant_documents("foo1") [Document(page_content='foo1', metadata={'dist': '1.19209289551e-07', 'id': '642739a17559b026b4430e40', 'createdAt': '2023-03-31T19:50:57.853Z'}), Document(page_content='foo1', metadata={'dist': '4.05311584473e-06', 'id': '642738f67559b026b4430e3c', 'createdAt': '2023-03-31T19:48:06.769Z'})] previous kNN next
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html
237e8a3fd5b0-1
previous kNN next Pinecone Hybrid Search Contents Ingest Documents Query By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html
b918f8934731-0
.ipynb .pdf Databerry Contents Query Databerry# Databerry platform brings data from anywhere (Datsources: Text, PDF, Word, PowerPpoint, Excel, Notion, Airtable, Google Sheets, etc..) into Datastores (container of multiple Datasources). Then your Datastores can be connected to ChatGPT via Plugins or any other Large Langue Model (LLM) via the Databerry API. This notebook shows how to use Databerry’s retriever. First, you will need to sign up for Databerry, create a datastore, add some data and get your datastore api endpoint url. You need the API Key. Query# Now that our index is set up, we can set up a retriever and start querying it. from langchain.retrievers import DataberryRetriever retriever = DataberryRetriever( datastore_url="https://clg1xg2h80000l708dymr0fxc.databerry.ai/query", # api_key="DATABERRY_API_KEY", # optional if datastore is public # top_k=10 # optional ) retriever.get_relevant_documents("What is Daftpage?")
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
b918f8934731-1
) retriever.get_relevant_documents("What is Daftpage?") [Document(page_content='✨ Made with DaftpageOpen main menuPricingTemplatesLoginSearchHelpGetting StartedFeaturesAffiliate ProgramGetting StartedDaftpage is a new type of website builder that works like a doc.It makes website building easy, fun and offers tons of powerful features for free. Just type / in your page to get started!DaftpageCopyright © 2022 Daftpage, Inc.All rights reserved.ProductPricingTemplatesHelp & SupportHelp CenterGetting startedBlogCompanyAboutRoadmapTwitterAffiliate Program👾 Discord', metadata={'source': 'https:/daftpage.com/help/getting-started', 'score': 0.8697265}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
b918f8934731-2
Document(page_content="✨ Made with DaftpageOpen main menuPricingTemplatesLoginSearchHelpGetting StartedFeaturesAffiliate ProgramHelp CenterWelcome to Daftpage’s help center—the one-stop shop for learning everything about building websites with Daftpage.Daftpage is the simplest way to create websites for all purposes in seconds. Without knowing how to code, and for free!Get StartedDaftpage is a new type of website builder that works like a doc.It makes website building easy, fun and offers tons of powerful features for free. Just type / in your page to get started!Start here✨ Create your first site🧱 Add blocks🚀 PublishGuides🔖 Add a custom domainFeatures🔥 Drops🎨 Drawings👻 Ghost mode💀 Skeleton modeCant find the answer you're looking for?mail us at support@daftpage.comJoin the awesome Daftpage community on: 👾 DiscordDaftpageCopyright © 2022 Daftpage, Inc.All rights reserved.ProductPricingTemplatesHelp & SupportHelp CenterGetting startedBlogCompanyAboutRoadmapTwitterAffiliate Program👾 Discord", metadata={'source': 'https:/daftpage.com/help', 'score': 0.86570895}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
b918f8934731-3
Document(page_content=" is the simplest way to create websites for all purposes in seconds. Without knowing how to code, and for free!Get StartedDaftpage is a new type of website builder that works like a doc.It makes website building easy, fun and offers tons of powerful features for free. Just type / in your page to get started!Start here✨ Create your first site🧱 Add blocks🚀 PublishGuides🔖 Add a custom domainFeatures🔥 Drops🎨 Drawings👻 Ghost mode💀 Skeleton modeCant find the answer you're looking for?mail us at support@daftpage.comJoin the awesome Daftpage community on: 👾 DiscordDaftpageCopyright © 2022 Daftpage, Inc.All rights reserved.ProductPricingTemplatesHelp & SupportHelp CenterGetting startedBlogCompanyAboutRoadmapTwitterAffiliate Program👾 Discord", metadata={'source': 'https:/daftpage.com/help', 'score': 0.8645384})] previous Contextual Compression next ElasticSearch BM25 Contents Query By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
e5f8fc12f635-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
e5f8fc12f635-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
e5f8fc12f635-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
e5f8fc12f635-3
-> **Question**: How does Compositional Reasoning with Large Language Models works? **Answer**: Compositional reasoning with large language models refers to the ability of these models to correctly identify and represent complex concepts by breaking them down into smaller, more basic parts and combining them in a structured way. This involves understanding the syntax and semantics of language and using that understanding to build up more complex meanings from simpler ones. In the context of the paper "Does CLIP Bind Concepts? Probing Compositionality in Large Image Models", the authors focus specifically on the ability of a large pretrained vision and language model (CLIP) to encode compositional concepts and to bind variables in a structure-sensitive way. They examine CLIP's ability to compose concepts in a single-object setting, as well as in situations where concept binding is needed. The authors situate their work within the tradition of research on compositional distributional semantics models (CDSMs), which seek to bridge the gap between distributional models and formal semantics by building architectures which operate over vectors yet still obey traditional theories of linguistic composition. They compare the performance of CLIP with several architectures from research on CDSMs to evaluate its ability to encode and reason about compositional concepts. questions = [ "What are Heat-bath random walks with Markov base? Include references to answer.", ] 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? Include references to answer.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html
e5f8fc12f635-4
**Answer**: Heat-bath random walks with Markov base (HB-MB) is a class of stochastic processes that have been studied in the field of statistical mechanics and condensed matter physics. In these processes, a particle moves in a lattice by making a transition to a neighboring site, which is chosen according to a probability distribution that depends on the energy of the particle and the energy of its surroundings. The HB-MB process was introduced by Bortz, Kalos, and Lebowitz in 1975 as a way to simulate the dynamics of interacting particles in a lattice at thermal equilibrium. The method has been used to study a variety of physical phenomena, including phase transitions, critical behavior, and transport properties. References: Bortz, A. B., Kalos, M. H., & Lebowitz, J. L. (1975). A new algorithm for Monte Carlo simulation of Ising spin systems. Journal of Computational Physics, 17(1), 10-18. Binder, K., & Heermann, D. W. (2010). Monte Carlo simulation in statistical physics: an introduction. Springer Science & Business Media. previous Retrievers next Azure Cognitive Search Retriever Contents Installation Examples Running retriever Question Answering on facts By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html
e9d2830392d1-0
.ipynb .pdf Self-querying with Weaviate Contents Creating a Weaviate vectorstore Creating our self-querying retriever Testing it out Filter k Self-querying with Weaviate# Creating a Weaviate vectorstore# First we’ll want to create a Weaviate VectorStore and seed it with some data. We’ve created a small demo set of documents that contain summaries of movies. NOTE: The self-query retriever requires you to have lark installed (pip install lark). We also need the weaviate-client package. #!pip install lark weaviate-client from langchain.schema import Document from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Weaviate import os embeddings = OpenAIEmbeddings() docs = [ Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}), Document(page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2}), Document(page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}), Document(page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html
e9d2830392d1-1
Document(page_content="Toys come alive and have a blast doing so", metadata={"year": 1995, "genre": "animated"}), Document(page_content="Three men walk into the Zone, three men walk out of the Zone", metadata={"year": 1979, "rating": 9.9, "director": "Andrei Tarkovsky", "genre": "science fiction", "rating": 9.9}) ] vectorstore = Weaviate.from_documents( docs, embeddings, weaviate_url="http://127.0.0.1:8080" ) Creating our self-querying retriever# Now we can instantiate our retriever. To do this we’ll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents. from langchain.llms import OpenAI from langchain.retrievers.self_query.base import SelfQueryRetriever from langchain.chains.query_constructor.base import AttributeInfo metadata_field_info=[ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", type="float" ), ] document_content_description = "Brief summary of a movie" llm = OpenAI(temperature=0)
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html
e9d2830392d1-2
llm = OpenAI(temperature=0) retriever = SelfQueryRetriever.from_llm(llm, vectorstore, document_content_description, metadata_field_info, verbose=True) Testing it out# And now we can try actually using our retriever! # This example only specifies a relevant query retriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None limit=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': 'science fiction', 'rating': 7.7, 'year': 1993}), Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'rating': None, 'year': 1995}), Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'genre': 'science fiction', 'rating': 9.9, 'year': 1979}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'genre': None, 'rating': 8.6, 'year': 2006})] # This example specifies a query and a filter retriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None [Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'genre': None, 'rating': 8.3, 'year': 2019})] Filter k# We can also use the self query retriever to specify k: the number of documents to fetch.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html
e9d2830392d1-3
We can do this by passing enable_limit=True to the constructor. retriever = SelfQueryRetriever.from_llm( llm, vectorstore, document_content_description, metadata_field_info, enable_limit=True, verbose=True ) # This example only specifies a relevant query retriever.get_relevant_documents("what are two movies about dinosaurs") query='dinosaur' filter=None limit=2 [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': 'science fiction', 'rating': 7.7, 'year': 1993}), Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'rating': None, 'year': 1995})] previous Weaviate Hybrid Search next Wikipedia Contents Creating a Weaviate vectorstore Creating our self-querying retriever Testing it out Filter k By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html
d70d254758ea-0
.ipynb .pdf Self-querying Contents Creating a Pinecone index Creating our self-querying retriever Testing it out Filter k Self-querying# In the notebook we’ll demo the SelfQueryRetriever, which, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses a query-constructing LLM chain to write a structured query and then applies that structured query to it’s underlying VectorStore. This allows the retriever to not only use the user-input query for semantic similarity comparison with the contents of stored documented, but to also extract filters from the user query on the metadata of stored documents and to execute those filters. Creating a Pinecone index# First we’ll want to create a Pinecone VectorStore and seed it with some data. We’ve created a small demo set of documents that contain summaries of movies. To use Pinecone, you to have pinecone package installed and you must have an API key and an Environment. Here are the installation instructions. NOTE: The self-query retriever requires you to have lark package installed. # !pip install lark #!pip install pinecone-client import os import pinecone pinecone.init(api_key=os.environ["PINECONE_API_KEY"], environment=os.environ["PINECONE_ENV"]) /Users/harrisonchase/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pinecone/index.py:4: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console) from tqdm.autonotebook import tqdm from langchain.schema import Document from langchain.embeddings.openai import OpenAIEmbeddings
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html
d70d254758ea-1
from langchain.schema import Document from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Pinecone embeddings = OpenAIEmbeddings() # create new index pinecone.create_index("langchain-self-retriever-demo", dimension=1536) docs = [ Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": ["action", "science fiction"]}), Document(page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2}), Document(page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}), Document(page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3}), Document(page_content="Toys come alive and have a blast doing so", metadata={"year": 1995, "genre": "animated"}), Document(page_content="Three men walk into the Zone, three men walk out of the Zone", metadata={"year": 1979, "rating": 9.9, "director": "Andrei Tarkovsky", "genre": ["science fiction", "thriller"], "rating": 9.9}) ] vectorstore = Pinecone.from_documents( docs, embeddings, index_name="langchain-self-retriever-demo" ) Creating our self-querying retriever#
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html
d70d254758ea-2
) Creating our self-querying retriever# Now we can instantiate our retriever. To do this we’ll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents. from langchain.llms import OpenAI from langchain.retrievers.self_query.base import SelfQueryRetriever from langchain.chains.query_constructor.base import AttributeInfo metadata_field_info=[ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", type="float" ), ] document_content_description = "Brief summary of a movie" llm = OpenAI(temperature=0) retriever = SelfQueryRetriever.from_llm(llm, vectorstore, document_content_description, metadata_field_info, verbose=True) Testing it out# And now we can try actually using our retriever! # This example only specifies a relevant query retriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': ['action', 'science fiction'], 'rating': 7.7, 'year': 1993.0}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html