id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
cb1e36183c0b-0
.ipynb .pdf ElasticSearch BM25 Contents Create New Retriever Add texts (if necessary) Use Retriever ElasticSearch BM25# Elasticsearch is a distributed, RESTful search and analytics engine. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. In information retrieval, Okapi BM25 (BM is an abbreviation of best matching) is a ranking function used by search engines to estimate the relevance of documents to a given search query. It is based on the probabilistic retrieval framework developed in the 1970s and 1980s by Stephen E. Robertson, Karen Spärck Jones, and others. The name of the actual ranking function is BM25. The fuller name, Okapi BM25, includes the name of the first system to use it, which was the Okapi information retrieval system, implemented at London’s City University in the 1980s and 1990s. BM25 and its newer variants, e.g. BM25F (a version of BM25 that can take document structure and anchor text into account), represent TF-IDF-like retrieval functions used in document retrieval. This notebook shows how to use a retriever that uses ElasticSearch and BM25. For more information on the details of BM25 see this blog post. #!pip install elasticsearch from langchain.retrievers import ElasticSearchBM25Retriever Create New Retriever# elasticsearch_url="http://localhost:9200" retriever = ElasticSearchBM25Retriever.create(elasticsearch_url, "langchain-index-4") # Alternatively, you can load an existing index # import elasticsearch # elasticsearch_url="http://localhost:9200"
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html
cb1e36183c0b-1
# import elasticsearch # elasticsearch_url="http://localhost:9200" # retriever = ElasticSearchBM25Retriever(elasticsearch.Elasticsearch(elasticsearch_url), "langchain-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", "foo bar"]) ['cbd4cb47-8d9f-4f34-b80e-ea871bc49856', 'f3bd2e24-76d1-4f9b-826b-ec4c0e8c7365', '8631bfc8-7c12-48ee-ab56-8ad5f373676e', '8be8374c-3253-4d87-928d-d73550a2ecf0', 'd79f457b-2842-4eab-ae10-77aa420b53d7'] 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={})] previous Databerry next kNN Contents Create New Retriever Add texts (if necessary) Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html
04432a389f8d-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
04432a389f8d-1
retriever.get_relevant_documents("what is vespa?") previous VectorStore next Weaviate Hybrid Search By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html
9e41fcf70f13-0
.ipynb .pdf Cohere Reranker Contents Set up the base vector store retriever Doing reranking with CohereRerank Cohere Reranker# Cohere is a Canadian startup that provides natural language processing models that help companies improve human-machine interactions. This notebook shows how to use Cohere’s rerank endpoint in a retriever. This builds on top of ideas in the ContextualCompressionRetriever. #!pip install cohere #!pip install faiss # OR (depending on Python version) #!pip install faiss-cpu # get a new token: https://dashboard.cohere.ai/ import os import getpass os.environ['COHERE_API_KEY'] = getpass.getpass('Cohere API Key:') os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') # 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)])) Set up the base 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 set up the retriever to retrieve a high number (20) of docs. from langchain.text_splitter import RecursiveCharacterTextSplitter 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 = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100) texts = text_splitter.split_documents(documents)
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-1
texts = text_splitter.split_documents(documents) retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever(search_kwargs={"k": 20}) query = "What did the president say about Ketanji Brown Jackson" docs = retriever.get_relevant_documents(query) pretty_print_docs(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: 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. ---------------------------------------------------------------------------------------------------- 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. 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. ---------------------------------------------------------------------------------------------------- Document 4: 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/retrievers/examples/cohere-reranker.html
9e41fcf70f13-2
Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. In this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight. ---------------------------------------------------------------------------------------------------- Document 5: 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. ---------------------------------------------------------------------------------------------------- Document 6: Vice President Harris and I ran for office with a new economic vision for America. Invest in America. Educate Americans. Grow the workforce. Build the economy from the bottom up and the middle out, not from the top down. Because we know that when the middle class grows, the poor have a ladder up and the wealthy do very well. America used to have the best roads, bridges, and airports on Earth. Now our infrastructure is ranked 13th in the world. ---------------------------------------------------------------------------------------------------- Document 7: And tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. By the end of this year, the deficit will be down to less than half what it was before I took office. The only president ever to cut the deficit by more than one trillion dollars in a single year. Lowering your costs also means demanding more competition. I’m a capitalist, but capitalism without competition isn’t capitalism. It’s exploitation—and it drives up prices. ----------------------------------------------------------------------------------------------------
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-3
It’s exploitation—and it drives up prices. ---------------------------------------------------------------------------------------------------- Document 8: For the past 40 years we were told that if we gave tax breaks to those at the very top, the benefits would trickle down to everyone else. But that trickle-down theory led to weaker economic growth, lower wages, bigger deficits, and the widest gap between those at the top and everyone else in nearly a century. Vice President Harris and I ran for office with a new economic vision for America. ---------------------------------------------------------------------------------------------------- Document 9: All told, we created 369,000 new manufacturing jobs in America just last year. Powered by people I’ve met like JoJo Burgess, from generations of union steelworkers from Pittsburgh, who’s here with us tonight. As Ohio Senator Sherrod Brown says, “It’s time to bury the label “Rust Belt.” It’s time. But with all the bright spots in our economy, record job growth and higher wages, too many families are struggling to keep up with the bills. ---------------------------------------------------------------------------------------------------- Document 10: I’m also calling on Congress: pass a law to make sure veterans devastated by toxic exposures in Iraq and Afghanistan finally get the benefits and comprehensive health care they deserve. And fourth, let’s end cancer as we know it. This is personal to me and Jill, to Kamala, and to so many of you. Cancer is the #2 cause of death in America–second only to heart disease. ---------------------------------------------------------------------------------------------------- Document 11: He will never extinguish their love of freedom. He will never weaken the resolve of the free world. We meet tonight in an America that has lived through two of the hardest years this nation has ever faced. The pandemic has been punishing.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-4
The pandemic has been punishing. And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more. I understand. ---------------------------------------------------------------------------------------------------- Document 12: 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. ---------------------------------------------------------------------------------------------------- Document 13: I know. One of those soldiers was my son Major Beau Biden. We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. But I’m committed to finding out everything we can. Committed to military families like Danielle Robinson from Ohio. The widow of Sergeant First Class Heath Robinson. He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. ---------------------------------------------------------------------------------------------------- Document 14: 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. There is so much we can do. Increase funding for prevention, treatment, harm reduction, and recovery. ---------------------------------------------------------------------------------------------------- Document 15: Third, support our veterans. Veterans are the best of us.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-5
Third, support our veterans. Veterans are the best of us. I’ve always believed that we have a sacred obligation to equip all those we send to war and care for them and their families when they come home. My administration is providing assistance with job training and housing, and now helping lower-income veterans get VA care debt-free. Our troops in Iraq and Afghanistan faced many dangers. ---------------------------------------------------------------------------------------------------- Document 16: When we invest in our workers, when we build the economy from the bottom up and the middle out together, we can do something we haven’t done in a long time: build a better America. For more than two years, COVID-19 has impacted every decision in our lives and the life of the nation. And I know you’re tired, frustrated, and exhausted. But I also know this. ---------------------------------------------------------------------------------------------------- Document 17: Now is the hour. Our moment of responsibility. Our test of resolve and conscience, of history itself. It is in this moment that our character is formed. Our purpose is found. Our future is forged. Well I know this nation. We will meet the test. To protect freedom and liberty, to expand fairness and opportunity. We will save democracy. As hard as these times have been, I am more optimistic about America today than I have been my whole life. ---------------------------------------------------------------------------------------------------- Document 18: He didn’t know how to stop fighting, and neither did she. Through her pain she found purpose to demand we do better. Tonight, Danielle—we are. The VA is pioneering new ways of linking toxic exposures to diseases, already helping more veterans get benefits. And tonight, I’m announcing we’re expanding eligibility to veterans suffering from nine respiratory cancers. ---------------------------------------------------------------------------------------------------- Document 19: I understand.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-6
---------------------------------------------------------------------------------------------------- Document 19: I understand. I remember when my Dad had to leave our home in Scranton, Pennsylvania to find work. I grew up in a family where if the price of food went up, you felt it. That’s why one of the first things I did as President was fight to pass the American Rescue Plan. Because people were hurting. We needed to act, and we did. Few pieces of legislation have done more in a critical moment in our history to lift us out of crisis. ---------------------------------------------------------------------------------------------------- Document 20: 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. Doing reranking with CohereRerank# Now let’s wrap our base retriever with a ContextualCompressionRetriever. We’ll add an CohereRerank, uses the Cohere rerank endpoint to rerank the returned results. from langchain.llms import OpenAI from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import CohereRerank llm = OpenAI(temperature=0) compressor = CohereRerank() 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.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-7
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: 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. ---------------------------------------------------------------------------------------------------- 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. 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. You can of course use this retriever within a QA pipeline from langchain.chains import RetrievalQA chain = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), retriever=compression_retriever) chain({"query": query}) {'query': 'What did the president say about Ketanji Brown Jackson', 'result': " The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she is a consensus builder who has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."} previous Self-querying with Chroma next Contextual Compression Contents
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
9e41fcf70f13-8
previous Self-querying with Chroma next Contextual Compression Contents Set up the base vector store retriever Doing reranking with CohereRerank By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html
831133cd157b-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
831133cd157b-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
831133cd157b-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 [email protected] 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
831133cd157b-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 [email protected] 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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
948f7985ea58-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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/tf_idf.html
6387256b88f4-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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/azure-cognitive-search-retriever.html
2e96248c5031-0
.ipynb .pdf Self-querying with Chroma Contents Creating a Chroma vectorstore Creating our self-querying retriever Testing it out Filter k Self-querying with Chroma# Chroma is a database for building AI applications with embeddings. In the notebook we’ll demo the SelfQueryRetriever wrapped around a Chroma vector store. Creating a Chroma 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 chromadb package. #!pip install lark #!pip install chromadb 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 Chroma 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}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html
2e96248c5031-1
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 = Chroma.from_documents( docs, embeddings ) Using embedded DuckDB without persistence: data will be transient 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" ), ]
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html
2e96248c5031-2
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={'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='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='Leo DiCaprio gets lost in a dream within a dream within a dream within a ...', metadata={'year': 2010, 'director': 'Christopher Nolan', 'rating': 8.2})] # This example only specifies a filter retriever.get_relevant_documents("I want to watch a movie rated higher than 8.5") query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) [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}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html
2e96248c5031-3
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 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') [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.EQ: 'eq'>, attribute='genre', value='science fiction'), Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5)]) [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")
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html
2e96248c5031-4
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')]) [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 [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='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}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html
2e96248c5031-5
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})] previous ChatGPT Plugin next Cohere Reranker Contents Creating a Chroma vectorstore Creating our self-querying retriever Testing it out Filter k By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html
11deee880015-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
11deee880015-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
11deee880015-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
11deee880015-3
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={'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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html
e4d1e4ff1b34-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
e4d1e4ff1b34-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
e4d1e4ff1b34-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, top_k=5,
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
e4d1e4ff1b34-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
e4d1e4ff1b34-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
e4d1e4ff1b34-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
e4d1e4ff1b34-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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html
f1bf99e6b536-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
f1bf99e6b536-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
f1bf99e6b536-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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
522387a6b332-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
522387a6b332-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
522387a6b332-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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html
93d1aff9ae56-0
.ipynb .pdf kNN Contents Create New Retriever with Texts Use Retriever kNN# In statistics, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method first developed by Evelyn Fix and Joseph Hodges in 1951, and later expanded by Thomas Cover. It is used for classification and regression. This notebook goes over how to use a retriever that under the hood uses an kNN. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb from langchain.retrievers import KNNRetriever from langchain.embeddings import OpenAIEmbeddings Create New Retriever with Texts# retriever = KNNRetriever.from_texts(["foo", "bar", "world", "hello", "foo bar"], OpenAIEmbeddings()) Use Retriever# We can now use the retriever! result = retriever.get_relevant_documents("foo") result [Document(page_content='foo', metadata={}), Document(page_content='foo bar', metadata={}), Document(page_content='hello', metadata={}), Document(page_content='bar', metadata={})] previous ElasticSearch BM25 next Metal Contents Create New Retriever with Texts Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/knn.html
552724666d34-0
.ipynb .pdf Wikipedia Contents Installation Examples Running retriever Question Answering on facts Wikipedia# Wikipedia is a multilingual free online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and using a wiki-based editing system called MediaWiki. Wikipedia is the largest and most-read reference work in history. This notebook shows how to retrieve wiki pages from wikipedia.org into the Document format that is used downstream. Installation# First, you need to install wikipedia python package. #!pip install wikipedia WikipediaRetriever has these arguments: optional lang: default=”en”. Use it to search in a specific language part of Wikipedia optional load_max_docs: default=100. Use it to limit number of downloaded documents. It takes time to download all 100 documents, so use a small number for experiments. There is a hard limit of 300 for now. optional load_all_available_meta: default=False. By default only the most important fields downloaded: Published (date when document was published/last updated), title, Summary. If True, other fields also downloaded. get_relevant_documents() has one argument, query: free text which used to find documents in Wikipedia Examples# Running retriever# from langchain.retrievers import WikipediaRetriever retriever = WikipediaRetriever() docs = retriever.get_relevant_documents(query='HUNTER X HUNTER') docs[0].metadata # meta-information of the Document {'title': 'Hunter × Hunter',
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
552724666d34-1
'summary': 'Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The story focuses on a young boy named Gon Freecss who discovers that his father, who left him at a young age, is actually a world-renowned Hunter, a licensed professional who specializes in fantastical pursuits such as locating rare or unidentified animal species, treasure hunting, surveying unexplored enclaves, or hunting down lawless individuals. Gon departs on a journey to become a Hunter and eventually find his father. Along the way, Gon meets various other Hunters and encounters the paranormal.\nHunter × Hunter was adapted into a 62-episode anime television
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
552724666d34-2
Hunter was adapted into a 62-episode anime television series produced by Nippon Animation and directed by Kazuhiro Furuhashi, which ran on Fuji Television from October 1999 to March 2001. Three separate original video animations (OVAs) totaling 30 episodes were subsequently produced by Nippon Animation and released in Japan from 2002 to 2004. A second anime television series by Madhouse aired on Nippon Television from October 2011 to September 2014, totaling 148 episodes, with two animated theatrical films released in 2013. There are also numerous audio albums, video games, musicals, and other media based on Hunter × Hunter.\nThe manga has been translated into English and released in North America by Viz Media since April 2005. Both television series have been also licensed by Viz Media, with the first series having aired on the Funimation Channel in 2009 and the second series broadcast on Adult Swim\'s Toonami programming block from April 2016 to June 2019.\nHunter × Hunter has been a huge critical and financial success and
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
552724666d34-3
Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.\n\n'}
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
552724666d34-4
docs[0].page_content[:400] # a content of the Document 'Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The sto' Question Answering on facts# # get a token: https://platform.openai.com/account/api-keys from getpass import getpass OPENAI_API_KEY = getpass() ········ import os os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY from langchain.chat_models import ChatOpenAI from langchain.chains import ConversationalRetrievalChain model = ChatOpenAI(model_name='gpt-3.5-turbo') # switch to 'gpt-4' qa = ConversationalRetrievalChain.from_llm(model,retriever=retriever) questions = [ "What is Apify?", "When the Monument to the Martyrs of the 1830 Revolution was created?", "What is the Abhayagiri Vihāra?", # "How big is Wikipédia en français?", ] chat_history = [] for question in questions: result = qa({"question": question, "chat_history": chat_history}) chat_history.append((question, result['answer'])) print(f"-> **Question**: {question} \n") print(f"**Answer**: {result['answer']} \n") -> **Question**: What is Apify?
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
552724666d34-5
-> **Question**: What is Apify? **Answer**: Apify is a platform that allows you to easily automate web scraping, data extraction and web automation. It provides a cloud-based infrastructure for running web crawlers and other automation tasks, as well as a web-based tool for building and managing your crawlers. Additionally, Apify offers a marketplace for buying and selling pre-built crawlers and related services. -> **Question**: When the Monument to the Martyrs of the 1830 Revolution was created? **Answer**: Apify is a web scraping and automation platform that enables you to extract data from websites, turn unstructured data into structured data, and automate repetitive tasks. It provides a user-friendly interface for creating web scraping scripts without any coding knowledge. Apify can be used for various web scraping tasks such as data extraction, web monitoring, content aggregation, and much more. Additionally, it offers various features such as proxy support, scheduling, and integration with other tools to make web scraping and automation tasks easier and more efficient. -> **Question**: What is the Abhayagiri Vihāra? **Answer**: Abhayagiri Vihāra was a major monastery site of Theravada Buddhism that was located in Anuradhapura, Sri Lanka. It was founded in the 2nd century BCE and is considered to be one of the most important monastic complexes in Sri Lanka. previous Self-querying with Weaviate next Zep Memory Contents Installation Examples Running retriever Question Answering on facts By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html
126efdb66006-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
126efdb66006-1
previous kNN next Pinecone Hybrid Search Contents Ingest Documents Query By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html
459b70d4daf4-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
459b70d4daf4-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
459b70d4daf4-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 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 May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
2a117d7a0620-0
.ipynb .pdf Weaviate Hybrid Search Weaviate Hybrid Search# Weaviate is an open source vector database. Hybrid search is a technique that combines multiple search algorithms to improve the accuracy and relevance of search results. It uses the best features of both keyword-based search algorithms with vector search techniques. The Hybrid search in Weaviate uses sparse and dense vectors to represent the meaning and context of search queries and documents. This notebook shows how to use Weaviate hybrid search as a LangChain retriever. Set up the retriever: #!pip install weaviate-client import weaviate import os WEAVIATE_URL = os.getenv("WEAVIATE_URL") client = weaviate.Client( url=WEAVIATE_URL, auth_client_secret=weaviate.AuthApiKey(api_key=os.getenv("WEAVIATE_API_KEY")), additional_headers={ "X-Openai-Api-Key": os.getenv("OPENAI_API_KEY"), }, ) # client.schema.delete_all() from langchain.retrievers.weaviate_hybrid_search import WeaviateHybridSearchRetriever from langchain.schema import Document /workspaces/langchain/langchain/vectorstores/analyticdb.py:20: MovedIn20Warning: The ``declarative_base()`` function is now available as sqlalchemy.orm.declarative_base(). (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9) Base = declarative_base() # type: Any retriever = WeaviateHybridSearchRetriever( client, index_name="LangChain", text_key="text" ) Add some data: docs = [ Document( metadata={
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html
2a117d7a0620-1
) Add some data: docs = [ Document( metadata={ "title": "Embracing The Future: AI Unveiled", "author": "Dr. Rebecca Simmons", }, page_content="A comprehensive analysis of the evolution of artificial intelligence, from its inception to its future prospects. Dr. Simmons covers ethical considerations, potentials, and threats posed by AI.", ), Document( metadata={ "title": "Symbiosis: Harmonizing Humans and AI", "author": "Prof. Jonathan K. Sterling", }, page_content="Prof. Sterling explores the potential for harmonious coexistence between humans and artificial intelligence. The book discusses how AI can be integrated into society in a beneficial and non-disruptive manner.", ), Document( metadata={"title": "AI: The Ethical Quandary", "author": "Dr. Rebecca Simmons"}, page_content="In her second book, Dr. Simmons delves deeper into the ethical considerations surrounding AI development and deployment. It is an eye-opening examination of the dilemmas faced by developers, policymakers, and society at large.", ), Document( metadata={ "title": "Conscious Constructs: The Search for AI Sentience", "author": "Dr. Samuel Cortez", }, page_content="Dr. Cortez takes readers on a journey exploring the controversial topic of AI consciousness. The book provides compelling arguments for and against the possibility of true AI sentience.", ), Document( metadata={ "title": "Invisible Routines: Hidden AI in Everyday Life", "author": "Prof. Jonathan K. Sterling", },
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html
2a117d7a0620-2
"author": "Prof. Jonathan K. Sterling", }, page_content="In his follow-up to 'Symbiosis', Prof. Sterling takes a look at the subtle, unnoticed presence and influence of AI in our everyday lives. It reveals how AI has become woven into our routines, often without our explicit realization.", ), ] retriever.add_documents(docs) ['eda16d7d-437d-4613-84ae-c2e38705ec7a', '04b501bf-192b-4e72-be77-2fbbe7e67ebf', '18a1acdb-23b7-4482-ab04-a6c2ed51de77', '88e82cc3-c020-4b5a-b3c6-ca7cf3fc6a04', 'f6abd9d5-32ed-46c4-bd08-f8d0f7c9fc95'] Do a hybrid search: retriever.get_relevant_documents("the ethical implications of AI") [Document(page_content='In her second book, Dr. Simmons delves deeper into the ethical considerations surrounding AI development and deployment. It is an eye-opening examination of the dilemmas faced by developers, policymakers, and society at large.', metadata={}), Document(page_content='A comprehensive analysis of the evolution of artificial intelligence, from its inception to its future prospects. Dr. Simmons covers ethical considerations, potentials, and threats posed by AI.', metadata={}), Document(page_content="In his follow-up to 'Symbiosis', Prof. Sterling takes a look at the subtle, unnoticed presence and influence of AI in our everyday lives. It reveals how AI has become woven into our routines, often without our explicit realization.", metadata={}),
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html
2a117d7a0620-3
Document(page_content='Prof. Sterling explores the potential for harmonious coexistence between humans and artificial intelligence. The book discusses how AI can be integrated into society in a beneficial and non-disruptive manner.', metadata={})] Do a hybrid search with where filter: retriever.get_relevant_documents( "AI integration in society", where_filter={ "path": ["author"], "operator": "Equal", "valueString": "Prof. Jonathan K. Sterling", }, ) [Document(page_content='Prof. Sterling explores the potential for harmonious coexistence between humans and artificial intelligence. The book discusses how AI can be integrated into society in a beneficial and non-disruptive manner.', metadata={}), Document(page_content="In his follow-up to 'Symbiosis', Prof. Sterling takes a look at the subtle, unnoticed presence and influence of AI in our everyday lives. It reveals how AI has become woven into our routines, often without our explicit realization.", metadata={})] previous Vespa next Self-querying with Weaviate By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html
7738e171f9f8-0
.ipynb .pdf Getting Started Contents Add texts From Documents Getting Started# This notebook showcases basic functionality related to VectorStores. A key part of working with vectorstores is creating the vector to put in them, which is usually created via embeddings. Therefore, it is recommended that you familiarize yourself with the embedding notebook before diving into this. This covers generic high level functionality related to all vector stores. from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Chroma with open('../../state_of_the_union.txt') as f: state_of_the_union = f.read() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_texts(texts, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. print(docs[0].page_content) In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. We cannot let this happen. Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html
7738e171f9f8-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. Add texts# You can easily add text to a vectorstore with the add_texts method. It will return a list of document IDs (in case you need to use them downstream). docsearch.add_texts(["Ankush went to Princeton"]) ['a05e3d0c-ab40-11ed-a853-e65801318981'] query = "Where did Ankush go to college?" docs = docsearch.similarity_search(query) docs[0] Document(page_content='Ankush went to Princeton', lookup_str='', metadata={}, lookup_index=0) From Documents# We can also initialize a vectorstore from documents directly. This is useful when we use the method on the text splitter to get documents directly (handy when the original documents have associated metadata). documents = text_splitter.create_documents([state_of_the_union], metadatas=[{"source": "State of the Union"}]) docsearch = Chroma.from_documents(documents, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = docsearch.similarity_search(query) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. print(docs[0].page_content) In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. We cannot let this happen.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html
7738e171f9f8-2
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. previous Vectorstores next AnalyticDB Contents Add texts From Documents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html
8f5a434f67a2-0
.ipynb .pdf Atlas Atlas# Atlas is a platform for interacting with both small and internet scale unstructured datasets by Nomic. This notebook shows you how to use functionality related to the AtlasDB vectorstore. !pip install spacy !python3 -m spacy download en_core_web_sm !pip install nomic import time from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import SpacyTextSplitter from langchain.vectorstores import AtlasDB from langchain.document_loaders import TextLoader ATLAS_TEST_API_KEY = '7xDPkYXSYDc1_ErdTPIcoAR9RNd8YDlkS3nVNXcVoIMZ6' loader = TextLoader('../../../state_of_the_union.txt') documents = loader.load() text_splitter = SpacyTextSplitter(separator='|') texts = [] for doc in text_splitter.split_documents(documents): texts.extend(doc.page_content.split('|')) texts = [e.strip() for e in texts] db = AtlasDB.from_texts(texts=texts, name='test_index_'+str(time.time()), # unique name for your vector store description='test_index', #a description for your vector store api_key=ATLAS_TEST_API_KEY, index_kwargs={'build_topic_model': True}) db.project.wait_for_project_lock() db.project test_index_1677255228.136989 A description for your project 508 datums inserted. 1 index built. Projections test_index_1677255228.136989_index. Status Completed. view online Projection ID: db996d77-8981-48a0-897a-ff2c22bbf541 Hide embedded project
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/atlas.html
8f5a434f67a2-1
Hide embedded project Explore on atlas.nomic.ai previous Annoy next Chroma By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/atlas.html
beb1b627dad9-0
.ipynb .pdf Supabase (Postgres) Contents Similarity search with score Retriever options Maximal Marginal Relevance Searches Supabase (Postgres)# Supabase is an open source Firebase alternative. Supabase is built on top of PostgreSQL, which offers strong SQL querying capabilities and enables a simple interface with already-existing tools and frameworks. PostgreSQL also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. This notebook shows how to use Supabase and pgvector as your VectorStore. To run this notebook, please ensure: the pgvector extension is enabled you have installed the supabase-py package that you have created a match_documents function in your database that you have a documents table in your public schema similar to the one below. The following function determines cosine similarity, but you can adjust to your needs. -- Enable the pgvector extension to work with embedding vectors create extension vector; -- Create a table to store your documents create table documents ( id bigserial primary key, content text, -- corresponds to Document.pageContent metadata jsonb, -- corresponds to Document.metadata embedding vector(1536) -- 1536 works for OpenAI embeddings, change if needed ); CREATE FUNCTION match_documents(query_embedding vector(1536), match_count int) RETURNS TABLE( id bigint, content text, metadata jsonb, -- we return matched vectors to enable maximal marginal relevance searches embedding vector(1536), similarity float) LANGUAGE plpgsql AS $$ # variable_conflict use_column BEGIN RETURN query SELECT id, content, metadata, embedding,
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
beb1b627dad9-1
SELECT id, content, metadata, embedding, 1 -(documents.embedding <=> query_embedding) AS similarity FROM documents ORDER BY documents.embedding <=> query_embedding LIMIT match_count; END; $$; # with pip !pip install supabase # with conda # !conda install -c conda-forge supabase We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') os.environ['SUPABASE_URL'] = getpass.getpass('Supabase URL:') os.environ['SUPABASE_SERVICE_KEY'] = getpass.getpass('Supabase Service Key:') # If you're storing your Supabase and OpenAI API keys in a .env file, you can load them with dotenv from dotenv import load_dotenv load_dotenv() import os from supabase.client import Client, create_client supabase_url = os.environ.get("SUPABASE_URL") supabase_key = os.environ.get("SUPABASE_SERVICE_KEY") supabase: Client = create_client(supabase_url, supabase_key) from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import SupabaseVectorStore from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader loader = TextLoader("../../../state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
beb1b627dad9-2
docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() # We're using the default `documents` table here. You can modify this by passing in a `table_name` argument to the `from_documents` method. vector_store = SupabaseVectorStore.from_documents( docs, embeddings, client=supabase ) query = "What did the president say about Ketanji Brown Jackson" matched_docs = vector_store.similarity_search(query) print(matched_docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Similarity search with score# matched_docs = vector_store.similarity_search_with_relevance_scores(query) matched_docs[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
beb1b627dad9-3
matched_docs = vector_store.similarity_search_with_relevance_scores(query) matched_docs[0] (Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}), 0.802509746274066) Retriever options# This section goes over different options for how to use SupabaseVectorStore as a retriever. Maximal Marginal Relevance Searches# In addition to using similarity search in the retriever object, you can also use mmr. retriever = vector_store.as_retriever(search_type="mmr") matched_docs = retriever.get_relevant_documents(query) for i, d in enumerate(matched_docs): print(f"\n## Document {i}\n") print(d.page_content) ## Document 0 Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
beb1b627dad9-4
Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. ## Document 1 One was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. When they came home, many of the world’s fittest and best trained warriors were never the same. Headaches. Numbness. Dizziness. A cancer that would put them in a flag-draped coffin. I know. One of those soldiers was my son Major Beau Biden. We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. But I’m committed to finding out everything we can. Committed to military families like Danielle Robinson from Ohio. The widow of Sergeant First Class Heath Robinson. He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. Stationed near Baghdad, just yards from burn pits the size of football fields. Heath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter. ## Document 2
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
beb1b627dad9-5
## Document 2 And I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. These steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. But I want you to know that we are going to be okay. When the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. While it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly. ## Document 3 We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. Officer Mora was 27 years old. Officer Rivera was 22. Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. I’ve worked on these issues a long time.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
beb1b627dad9-6
I’ve worked on these issues a long time. I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. previous Redis next Tair Contents Similarity search with score Retriever options Maximal Marginal Relevance Searches By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/supabase.html
a7c9febbf4f9-0
.ipynb .pdf Tair Tair# Tair is a cloud native in-memory database service developed by Alibaba Cloud. It provides rich data models and enterprise-grade capabilities to support your real-time online scenarios while maintaining full compatibility with open source Redis. Tair also introduces persistent memory-optimized instances that are based on the new non-volatile memory (NVM) storage medium. This notebook shows how to use functionality related to the Tair vector database. To run, you should have a Tair instance up and running. from langchain.embeddings.fake import FakeEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Tair 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 = FakeEmbeddings(size=128) Connect to Tair using the TAIR_URL environment variable export TAIR_URL="redis://{username}:{password}@{tair_address}:{tair_port}" or the keyword argument tair_url. Then store documents and embeddings into Tair. tair_url = "redis://localhost:6379" # drop first if index already exists Tair.drop_index(tair_url=tair_url) vector_store = Tair.from_documents( docs, embeddings, tair_url=tair_url ) Query similar documents. query = "What did the president say about Ketanji Brown Jackson" docs = vector_store.similarity_search(query) docs[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/tair.html
a7c9febbf4f9-1
docs = vector_store.similarity_search(query) docs[0] Document(page_content='We’re going after the criminals who stole billions in relief money meant for small businesses and millions of Americans. \n\nAnd tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. \n\nBy the end of this year, the deficit will be down to less than half what it was before I took office. \n\nThe only president ever to cut the deficit by more than one trillion dollars in a single year. \n\nLowering your costs also means demanding more competition. \n\nI’m a capitalist, but capitalism without competition isn’t capitalism. \n\nIt’s exploitation—and it drives up prices. \n\nWhen corporations don’t have to compete, their profits go up, your prices go up, and small businesses and family farmers and ranchers go under. \n\nWe see it happening with ocean carriers moving goods in and out of America. \n\nDuring the pandemic, these foreign-owned companies raised prices by as much as 1,000% and made record profits.', metadata={'source': '../../../state_of_the_union.txt'}) previous Supabase (Postgres) next Typesense By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/tair.html
f2cb58c1ad20-0
.ipynb .pdf Chroma Contents Similarity search with score Persistance Initialize PeristedChromaDB Persist the Database Load the Database from disk, and create the chain Retriever options MMR Chroma# Chroma is a database for building AI applications with embeddings. This notebook shows how to use functionality related to the Chroma vector database. !pip install chromadb # get a token: https://platform.openai.com/account/api-keys from getpass import getpass OPENAI_API_KEY = getpass() import os os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Chroma from langchain.document_loaders import TextLoader from langchain.document_loaders import TextLoader loader = TextLoader('../../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db = Chroma.from_documents(docs, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query) Using embedded DuckDB without persistence: data will be transient print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
f2cb58c1ad20-1
Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Similarity search with score# docs = db.similarity_search_with_score(query) docs[0] (Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}), 0.3949805498123169) Persistance# The below steps cover how to persist a ChromaDB instance Initialize PeristedChromaDB#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
f2cb58c1ad20-2
The below steps cover how to persist a ChromaDB instance Initialize PeristedChromaDB# Create embeddings for each chunk and insert into the Chroma vector database. The persist_directory argument tells ChromaDB where to store the database when it’s persisted. # Embed and store the texts # Supplying a persist_directory will store the embeddings on disk persist_directory = 'db' embedding = OpenAIEmbeddings() vectordb = Chroma.from_documents(documents=docs, embedding=embedding, persist_directory=persist_directory) Running Chroma using direct local API. No existing DB found in db, skipping load No existing DB found in db, skipping load Persist the Database# We should call persist() to ensure the embeddings are written to disk. vectordb.persist() vectordb = None Persisting DB to disk, putting it in the save folder db PersistentDuckDB del, about to run persist Persisting DB to disk, putting it in the save folder db Load the Database from disk, and create the chain# Be sure to pass the same persist_directory and embedding_function as you did when you instantiated the database. Initialize the chain we will use for question answering. # Now we can load the persisted database from disk, and use it as normal. vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding) Running Chroma using direct local API. loaded in 4 embeddings loaded in 1 collections Retriever options# This section goes over different options for how to use Chroma as a retriever. MMR# In addition to using similarity search in the retriever object, you can also use mmr. retriever = db.as_retriever(search_type="mmr") retriever.get_relevant_documents(query)[0]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
f2cb58c1ad20-3
retriever.get_relevant_documents(query)[0] Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}) previous Atlas next Deep Lake Contents Similarity search with score Persistance Initialize PeristedChromaDB Persist the Database Load the Database from disk, and create the chain Retriever options MMR By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/chroma.html
2da0f5dcb072-0
.ipynb .pdf Vectara Contents Connecting to Vectara from LangChain Similarity search Similarity search with score Vectara as a Retriever Vectara# Vectara is a API platform for building LLM-powered applications. It provides a simple to use API for document indexing and query that is managed by Vectara and is optimized for performance and accuracy. This notebook shows how to use functionality related to the Vectara vector database. See the Vectara API documentation for more information on how to use the API. We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. import os import getpass os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') OpenAI API Key:········ from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Vectara from langchain.document_loaders import TextLoader loader = TextLoader('../../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() Connecting to Vectara from LangChain# The Vectara API provides simple API endpoints for indexing and querying. vectara = Vectara.from_documents(docs, embedding=None) Similarity search# The simplest scenario for using Vectara is to perform a similarity search. query = "What did the president say about Ketanji Brown Jackson" found_docs = vectara.similarity_search(query) print(found_docs[0].page_content)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/vectara.html
2da0f5dcb072-1
found_docs = vectara.similarity_search(query) print(found_docs[0].page_content) Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. A former top litigator in private practice. A former federal public defender. Similarity search with score# Sometimes we might want to perform the search, but also obtain a relevancy score to know how good is a particular result. query = "What did the president say about Ketanji Brown Jackson" found_docs = vectara.similarity_search_with_score(query) document, score = found_docs[0] print(document.page_content) print(f"\nScore: {score}") Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. A former top litigator in private practice. A former federal public defender. Score: 1.0046461 Vectara as a Retriever#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/vectara.html
2da0f5dcb072-2
Score: 1.0046461 Vectara as a Retriever# Vectara, as all the other vector stores, is a LangChain Retriever, by using cosine similarity. retriever = vectara.as_retriever() retriever VectorStoreRetriever(vectorstore=<langchain.vectorstores.vectara.Vectara object at 0x156d3e830>, search_type='similarity', search_kwargs={}) query = "What did the president say about Ketanji Brown Jackson" retriever.get_relevant_documents(query)[0] Document(page_content='Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. A former top litigator in private practice. A former federal public defender.', metadata={'source': '../../modules/state_of_the_union.txt'}) previous Typesense next Weaviate Contents Connecting to Vectara from LangChain Similarity search Similarity search with score Vectara as a Retriever By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/vectara.html
df13302c5faa-0
.ipynb .pdf DocArrayHnswSearch Contents Setup Using DocArrayHnswSearch Similarity search Similarity search with score DocArrayHnswSearch# DocArrayHnswSearch is a lightweight Document Index implementation provided by Docarray that runs fully locally and is best suited for small- to medium-sized datasets. It stores vectors on disk in hnswlib, and stores all other data in SQLite. This notebook shows how to use functionality related to the DocArrayHnswSearch. Setup# Uncomment the below cells to install docarray and get/set your OpenAI api key if you haven’t already done so. # !pip install "docarray[hnswlib]" # Get an OpenAI token: https://platform.openai.com/account/api-keys # import os # from getpass import getpass # OPENAI_API_KEY = getpass() # os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY Using DocArrayHnswSearch# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import DocArrayHnswSearch from langchain.document_loaders import TextLoader documents = TextLoader('../../../state_of_the_union.txt').load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db = DocArrayHnswSearch.from_documents(docs, embeddings, work_dir='hnswlib_store/', n_dim=1536) Similarity search# query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query) print(docs[0].page_content)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/docarray_hnsw.html
df13302c5faa-1
docs = db.similarity_search(query) print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Similarity search with score# docs = db.similarity_search_with_score(query) docs[0] (Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={}), 0.36962226)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/docarray_hnsw.html
df13302c5faa-2
0.36962226) import shutil # delete the dir shutil.rmtree('hnswlib_store') previous Deep Lake next DocArrayInMemorySearch Contents Setup Using DocArrayHnswSearch Similarity search Similarity search with score By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/docarray_hnsw.html
5c7b192491a8-0
.ipynb .pdf Qdrant Contents Connecting to Qdrant from LangChain Local mode In-memory On-disk storage On-premise server deployment Qdrant Cloud Reusing the same collection Similarity search Similarity search with score Maximum marginal relevance search (MMR) Qdrant as a Retriever Customizing Qdrant 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 for all sorts of neural network or semantic-based matching, faceted search, and other applications. This notebook shows how to use functionality related to the Qdrant vector database. There are various modes of how to run Qdrant, and depending on the chosen one, there will be some subtle differences. The options include: Local mode, no server required On-premise server deployment Qdrant Cloud See the installation instructions. !pip install 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.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import Qdrant 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()
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-1
docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() Connecting to Qdrant from LangChain# Local mode# Python client allows you to run the same code in local mode without running the Qdrant server. That’s great for testing things out and debugging or if you plan to store just a small amount of vectors. The embeddings might be fully kepy in memory or persisted on disk. In-memory# For some testing scenarios and quick experiments, you may prefer to keep all the data in memory only, so it gets lost when the client is destroyed - usually at the end of your script/notebook. qdrant = Qdrant.from_documents( docs, embeddings, location=":memory:", # Local mode with in-memory storage only collection_name="my_documents", ) On-disk storage# Local mode, without using the Qdrant server, may also store your vectors on disk so they’re persisted between runs. qdrant = Qdrant.from_documents( docs, embeddings, path="/tmp/local_qdrant", collection_name="my_documents", ) On-premise server deployment# No matter if you choose to launch Qdrant locally with a Docker container, or select a Kubernetes deployment with the official Helm chart, the way you’re going to connect to such an instance will be identical. You’ll need to provide a URL pointing to the service. url = "<---qdrant url here --->" qdrant = Qdrant.from_documents( docs, embeddings, url, prefer_grpc=True, collection_name="my_documents", ) Qdrant Cloud#
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-2
collection_name="my_documents", ) Qdrant Cloud# If you prefer not to keep yourself busy with managing the infrastructure, you can choose to set up a fully-managed Qdrant cluster on Qdrant Cloud. There is a free forever 1GB cluster included for trying out. The main difference with using a managed version of Qdrant is that you’ll need to provide an API key to secure your deployment from being accessed publicly. url = "<---qdrant cloud cluster url here --->" api_key = "<---api key here--->" qdrant = Qdrant.from_documents( docs, embeddings, url, prefer_grpc=True, api_key=api_key, collection_name="my_documents", ) Reusing the same collection# Both Qdrant.from_texts and Qdrant.from_documents methods are great to start using Qdrant with LangChain, but they are going to destroy the collection and create it from scratch! If you want to reuse the existing collection, you can always create an instance of Qdrant on your own and pass the QdrantClient instance with the connection details. del qdrant import qdrant_client client = qdrant_client.QdrantClient( path="/tmp/local_qdrant", prefer_grpc=True ) qdrant = Qdrant( client=client, collection_name="my_documents", embeddings=embeddings ) Similarity search# The simplest scenario for using Qdrant vector store is to perform a similarity search. Under the hood, our query will be encoded with the embedding_function and used to find similar documents in Qdrant collection. query = "What did the president say about Ketanji Brown Jackson" found_docs = qdrant.similarity_search(query)
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-3
found_docs = qdrant.similarity_search(query) print(found_docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Similarity search with score# Sometimes we might want to perform the search, but also obtain a relevancy score to know how good is a particular result. query = "What did the president say about Ketanji Brown Jackson" found_docs = qdrant.similarity_search_with_score(query) document, score = found_docs[0] print(document.page_content) print(f"\nScore: {score}") Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-4
One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. Score: 0.8153784913324512 Maximum marginal relevance search (MMR)# If you’d like to look up for some similar documents, but you’d also like to receive diverse results, MMR is method you should consider. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. query = "What did the president say about Ketanji Brown Jackson" found_docs = qdrant.max_marginal_relevance_search(query, k=2, fetch_k=10) for i, doc in enumerate(found_docs): print(f"{i + 1}.", doc.page_content, "\n") 1. Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-5
2. We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. Officer Mora was 27 years old. Officer Rivera was 22. Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. I’ve worked on these issues a long time. I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. Qdrant as a Retriever# Qdrant, as all the other vector stores, is a LangChain Retriever, by using cosine similarity. retriever = qdrant.as_retriever() retriever VectorStoreRetriever(vectorstore=<langchain.vectorstores.qdrant.Qdrant object at 0x7fc4e5720a00>, search_type='similarity', search_kwargs={}) It might be also specified to use MMR as a search strategy, instead of similarity. retriever = qdrant.as_retriever(search_type="mmr") retriever VectorStoreRetriever(vectorstore=<langchain.vectorstores.qdrant.Qdrant object at 0x7fc4e5720a00>, search_type='mmr', search_kwargs={})
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-6
query = "What did the president say about Ketanji Brown Jackson" retriever.get_relevant_documents(query)[0] Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}) Customizing Qdrant# Qdrant stores your vector embeddings along with the optional JSON-like payload. Payloads are optional, but since LangChain assumes the embeddings are generated from the documents, we keep the context data, so you can extract the original texts as well. By default, your document is going to be stored in the following payload structure: { "page_content": "Lorem ipsum dolor sit amet", "metadata": { "foo": "bar" } } You can, however, decide to use different keys for the page content and metadata. That’s useful if you already have a collection that you’d like to reuse. You can always change the Qdrant.from_documents( docs, embeddings, location=":memory:", collection_name="my_documents_2",
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
5c7b192491a8-7
location=":memory:", collection_name="my_documents_2", content_payload_key="my_page_content_key", metadata_payload_key="my_meta", ) <langchain.vectorstores.qdrant.Qdrant at 0x7fc4e2baa230> previous Pinecone next Redis Contents Connecting to Qdrant from LangChain Local mode In-memory On-disk storage On-premise server deployment Qdrant Cloud Reusing the same collection Similarity search Similarity search with score Maximum marginal relevance search (MMR) Qdrant as a Retriever Customizing Qdrant By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/qdrant.html
8dff15d10a23-0
.ipynb .pdf Annoy Contents Create VectorStore from texts Create VectorStore from docs Create VectorStore via existing embeddings Search via embeddings Search via docstore id Save and load Construct from scratch Annoy# Annoy (Approximate Nearest Neighbors Oh Yeah) is a C++ library with Python bindings to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data. This notebook shows how to use functionality related to the Annoy vector database. Note NOTE: Annoy is read-only - once the index is built you cannot add any more emebddings! If you want to progressively add new entries to your VectorStore then better choose an alternative! #!pip install annoy Create VectorStore from texts# from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import Annoy embeddings_func = HuggingFaceEmbeddings() texts = ["pizza is great", "I love salad", "my car", "a dog"] # default metric is angular vector_store = Annoy.from_texts(texts, embeddings_func) # allows for custom annoy parameters, defaults are n_trees=100, n_jobs=-1, metric="angular" vector_store_v2 = Annoy.from_texts( texts, embeddings_func, metric="dot", n_trees=100, n_jobs=1 ) vector_store.similarity_search("food", k=3) [Document(page_content='pizza is great', metadata={}), Document(page_content='I love salad', metadata={}), Document(page_content='my car', metadata={})] # the score is a distance metric, so lower is better
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-1
# the score is a distance metric, so lower is better vector_store.similarity_search_with_score("food", k=3) [(Document(page_content='pizza is great', metadata={}), 1.0944390296936035), (Document(page_content='I love salad', metadata={}), 1.1273186206817627), (Document(page_content='my car', metadata={}), 1.1580758094787598)] Create VectorStore from docs# from langchain.document_loaders import TextLoader from langchain.text_splitter import CharacterTextSplitter loader = TextLoader("../../../state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) docs[:5]
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-2
docs = text_splitter.split_documents(documents) docs[:5] [Document(page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world.', metadata={'source': '../../../state_of_the_union.txt'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-3
Document(page_content='Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. \n\nIn this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight. \n\nLet each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world. \n\nPlease rise if you are able and show that, Yes, we the United States of America stand with the Ukrainian people. \n\nThroughout our history we’ve learned this lesson when dictators do not pay a price for their aggression they cause more chaos. \n\nThey keep moving. \n\nAnd the costs and the threats to America and the world keep rising. \n\nThat’s why the NATO Alliance was created to secure peace and stability in Europe after World War 2. \n\nThe United States is a member along with 29 other nations. \n\nIt matters. American diplomacy matters. American resolve matters.', metadata={'source': '../../../state_of_the_union.txt'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-4
Document(page_content='Putin’s latest attack on Ukraine was premeditated and unprovoked. \n\nHe rejected repeated efforts at diplomacy. \n\nHe thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready. Here is what we did. \n\nWe prepared extensively and carefully. \n\nWe spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. \n\nI spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression. \n\nWe countered Russia’s lies with truth. \n\nAnd now that he has acted the free world is holding him accountable. \n\nAlong with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.', metadata={'source': '../../../state_of_the_union.txt'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-5
Document(page_content='We are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than ever. \n\nTogether with our allies –we are right now enforcing powerful economic sanctions. \n\nWe are cutting off Russia’s largest banks from the international financial system. \n\nPreventing Russia’s central bank from defending the Russian Ruble making Putin’s $630 Billion “war fund” worthless. \n\nWe are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come. \n\nTonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. \n\nThe U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs. \n\nWe are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains.', metadata={'source': '../../../state_of_the_union.txt'}),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-6
Document(page_content='And tonight I am announcing that we will join our allies in closing off American air space to all Russian flights – further isolating Russia – and adding an additional squeeze –on their economy. The Ruble has lost 30% of its value. \n\nThe Russian stock market has lost 40% of its value and trading remains suspended. Russia’s economy is reeling and Putin alone is to blame. \n\nTogether with our allies we are providing support to the Ukrainians in their fight for freedom. Military assistance. Economic assistance. Humanitarian assistance. \n\nWe are giving more than $1 Billion in direct assistance to Ukraine. \n\nAnd we will continue to aid the Ukrainian people as they defend their country and to help ease their suffering. \n\nLet me be clear, our forces are not engaged and will not engage in conflict with Russian forces in Ukraine. \n\nOur forces are not going to Europe to fight in Ukraine, but to defend our NATO Allies – in the event that Putin decides to keep moving west.', metadata={'source': '../../../state_of_the_union.txt'})] vector_store_from_docs = Annoy.from_documents(docs, embeddings_func) query = "What did the president say about Ketanji Brown Jackson" docs = vector_store_from_docs.similarity_search(query) print(docs[0].page_content[:100]) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Ac Create VectorStore via existing embeddings# embs = embeddings_func.embed_documents(texts) data = list(zip(texts, embs)) vector_store_from_embeddings = Annoy.from_embeddings(data, embeddings_func) vector_store_from_embeddings.similarity_search_with_score("food", k=3) [(Document(page_content='pizza is great', metadata={}), 1.0944390296936035),
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-7
(Document(page_content='I love salad', metadata={}), 1.1273186206817627), (Document(page_content='my car', metadata={}), 1.1580758094787598)] Search via embeddings# motorbike_emb = embeddings_func.embed_query("motorbike") vector_store.similarity_search_by_vector(motorbike_emb, k=3) [Document(page_content='my car', metadata={}), Document(page_content='a dog', metadata={}), Document(page_content='pizza is great', metadata={})] vector_store.similarity_search_with_score_by_vector(motorbike_emb, k=3) [(Document(page_content='my car', metadata={}), 1.0870471000671387), (Document(page_content='a dog', metadata={}), 1.2095637321472168), (Document(page_content='pizza is great', metadata={}), 1.3254905939102173)] Search via docstore id# vector_store.index_to_docstore_id {0: '2d1498a8-a37c-4798-acb9-0016504ed798', 1: '2d30aecc-88e0-4469-9d51-0ef7e9858e6d', 2: '927f1120-985b-4691-b577-ad5cb42e011c', 3: '3056ddcf-a62f-48c8-bd98-b9e57a3dfcae'} some_docstore_id = 0 # texts[0] vector_store.docstore._dict[vector_store.index_to_docstore_id[some_docstore_id]] Document(page_content='pizza is great', metadata={}) # same document has distance 0
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-8
Document(page_content='pizza is great', metadata={}) # same document has distance 0 vector_store.similarity_search_with_score_by_index(some_docstore_id, k=3) [(Document(page_content='pizza is great', metadata={}), 0.0), (Document(page_content='I love salad', metadata={}), 1.0734446048736572), (Document(page_content='my car', metadata={}), 1.2895267009735107)] Save and load# vector_store.save_local("my_annoy_index_and_docstore") saving config loaded_vector_store = Annoy.load_local( "my_annoy_index_and_docstore", embeddings=embeddings_func ) # same document has distance 0 loaded_vector_store.similarity_search_with_score_by_index(some_docstore_id, k=3) [(Document(page_content='pizza is great', metadata={}), 0.0), (Document(page_content='I love salad', metadata={}), 1.0734446048736572), (Document(page_content='my car', metadata={}), 1.2895267009735107)] Construct from scratch# import uuid from annoy import AnnoyIndex from langchain.docstore.document import Document from langchain.docstore.in_memory import InMemoryDocstore metadatas = [{"x": "food"}, {"x": "food"}, {"x": "stuff"}, {"x": "animal"}] # embeddings embeddings = embeddings_func.embed_documents(texts) # embedding dim f = len(embeddings[0]) # index metric = "angular" index = AnnoyIndex(f, metric=metric) for i, emb in enumerate(embeddings): index.add_item(i, emb) index.build(10) # docstore documents = []
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html
8dff15d10a23-9
index.build(10) # docstore documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Document(page_content=text, metadata=metadata)) index_to_docstore_id = {i: str(uuid.uuid4()) for i in range(len(documents))} docstore = InMemoryDocstore( {index_to_docstore_id[i]: doc for i, doc in enumerate(documents)} ) db_manually = Annoy( embeddings_func.embed_query, index, metric, docstore, index_to_docstore_id ) db_manually.similarity_search_with_score("eating!", k=3) [(Document(page_content='pizza is great', metadata={'x': 'food'}), 1.1314140558242798), (Document(page_content='I love salad', metadata={'x': 'food'}), 1.1668788194656372), (Document(page_content='my car', metadata={'x': 'stuff'}), 1.226445198059082)] previous AnalyticDB next Atlas Contents Create VectorStore from texts Create VectorStore from docs Create VectorStore via existing embeddings Search via embeddings Search via docstore id Save and load Construct from scratch By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/annoy.html