id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
b7cf6a48a1bb-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | "role": "ai",
"content": (
"Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur"
" Fellowship."
),
},
{
"role": "human",
"content": "Which other women sci-fi writers might I want to read?",
},
{
"role": "ai",
"con... |
b7cf6a48a1bb-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | session_id=session_id, # Ensure that you provide the session_id when instantiating the Retriever
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-... |
b7cf6a48a1bb-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | 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... |
b7cf6a48a1bb-5 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | 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 Butl... |
b7cf6a48a1bb-6 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | 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
Initializ... |
495f79c9a9ba-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html | .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 MediaWik... |
495f79c9a9ba-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html | '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 sin... |
495f79c9a9ba-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html | on Adult Swim\'s Toonami programming block from April 2016 to June 2019.\nHunter × Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.\n\n'} |
495f79c9a9ba-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html | 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 mang... |
495f79c9a9ba-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html | **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... |
a7b5f49a7a75-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html | .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... |
a7b5f49a7a75-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html | 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... |
a7b5f49a7a75-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html | 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... |
a7b5f49a7a75-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html | 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")
qu... |
a7b5f49a7a75-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html | 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(p... |
a7b5f49a7a75-5 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html | 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
Filt... |
027788864ac4-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/azure_cognitive_search.html | .ipynb
.pdf
Azure Cognitive Search
Contents
Set up Azure Cognitive Search
Using the Azure Cognitive Search Retriever
Azure Cognitive Search#
Azure Cognitive Search (formerly known as Azure Search) is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience ove... |
027788864ac4-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/azure_cognitive_search.html | 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 u... |
9c2450f79914-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pubmed.html | .ipynb
.pdf
PubMed Retriever
PubMed Retriever#
This notebook goes over how to use PubMed as a retriever
PubMed® comprises more than 35 million citations for biomedical literature from MEDLINE, life science journals, and online books. Citations may include links to full text content from PubMed Central and publisher web... |
9c2450f79914-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pubmed.html | previous
Pinecone Hybrid Search
next
Self-querying with Qdrant
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
2eecd6519d6b-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html | .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 do... |
2eecd6519d6b-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html | 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})
]... |
2eecd6519d6b-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html | 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='dinos... |
2eecd6519d6b-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html | 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 ... |
a649c4ad458a-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html | .ipynb
.pdf
Self-querying with Qdrant
Contents
Creating a Qdrant vectorstore
Creating our self-querying retriever
Testing it out
Filter k
Self-querying with Qdrant#
Qdrant (read: quadrant ) is a vector similarity search engine. It provides a production-ready service with a convenient API to store, search, and manage ... |
a649c4ad458a-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html | 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"... |
a649c4ad458a-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html | 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(... |
a649c4ad458a-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html | query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) limit=None
[Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'rating': 9.9, 'director': 'Andrei Tarkovsky', 'genre': 'science fiction'}),
Document(page_content='A ps... |
a649c4ad458a-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html | [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 th... |
a649c4ad458a-5 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/qdrant_self_query.html | Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]
previous
PubMed Retriever
next
Self-querying
Contents
Creating a Qdrant vectorstore
Creating our self-querying retriever
Testing it out
Filter k
By Harrison Chase
© Copyright 2023, Harrison C... |
e792015568f7-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html | .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.... |
e792015568f7-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html | # 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',
... |
2b47d248b597-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/knn.html | .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.
... |
cfb36faf07db-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/tf_idf.html | .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 d... |
c8ddad580103-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html | .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 La... |
c8ddad580103-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html | [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 g... |
c8ddad580103-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html | 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 ... |
264924be1dcc-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html | .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 ... |
264924be1dcc-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html | 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... |
264924be1dcc-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin.html | 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': Non... |
2ba3048e4b33-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html | .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 techn... |
2ba3048e4b33-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html | "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.",
... |
2ba3048e4b33-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html | 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-c2e3870... |
2ba3048e4b33-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html | 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(
... |
95e895131ff2-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html | .ipynb
.pdf
Arxiv
Contents
Installation
Examples
Running retriever
Question Answering on facts
Arxiv#
arXiv is an open-access archive for 2 million scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems sci... |
95e895131ff2-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html | 'Summary': 'Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs... |
95e895131ff2-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html | "What is the ImageBind model?",
"How does Compositional Reasoning with Large Language Models works?",
]
chat_history = []
for question in questions:
result = qa({"question": question, "chat_history": chat_history})
chat_history.append((question, result['answer']))
print(f"-> **Question**: {questio... |
95e895131ff2-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html | **Answer**: Compositional reasoning with large language models refers to the ability of these models to correctly identify and represent complex concepts by breaking them down into smaller, more basic parts and combining them in a structured way. This involves understanding the syntax and semantics of language and usin... |
95e895131ff2-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/arxiv.html | **Answer**: Heat-bath random walks with Markov base (HB-MB) is a class of stochastic processes that have been studied in the field of statistical mechanics and condensed matter physics. In these processes, a particle moves in a lattice by making a transition to a neighboring site, which is chosen according to a probabi... |
ff34b7e10d98-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | .ipynb
.pdf
Contextual Compression
Contents
Contextual Compression
Using a vanilla vector store retriever
Adding contextual compression with an LLMChainExtractor
More built-in compressors: filters
LLMChainFilter
EmbeddingsFilter
Stringing compressors and document transformers together
Contextual Compression#
This not... |
ff34b7e10d98-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever()
docs = retriever.get_relevant_documents("What did the president say about Ketanji Brown Jackson")
pretty_print_docs(docs)
Document 1:
Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And whil... |
ff34b7e10d98-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.
----------------------------------------------------------------------------------------------------
Document 3:
And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act... |
ff34b7e10d98-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.
Adding contextual compression with an LLMChainExtractor#
Now let’s wrap our base retriever with a ContextualCompressionRetriever. We’l... |
ff34b7e10d98-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | The LLMChainFilter is slightly simpler but more robust compressor that uses an LLM chain to decide which of the initially retrieved documents to filter out and which ones to return, without manipulating the document contents.
from langchain.retrievers.document_compressors import LLMChainFilter
_filter = LLMChainFilter.... |
ff34b7e10d98-5 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | embeddings_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76)
compression_retriever = ContextualCompressionRetriever(base_compressor=embeddings_filter, base_retriever=retriever)
compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brow... |
ff34b7e10d98-6 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster.
We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.
-------------------------------------------------------... |
ff34b7e10d98-7 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | from langchain.retrievers.document_compressors import DocumentCompressorPipeline
from langchain.text_splitter import CharacterTextSplitter
splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0, separator=". ")
redundant_filter = EmbeddingsRedundantFilter(embeddings=embeddings)
relevant_filter = EmbeddingsFil... |
ff34b7e10d98-8 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html | Stringing compressors and document transformers together
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
ac1efcc65159-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | .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 i... |
ac1efcc65159-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | 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... |
ac1efcc65159-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | 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 familie... |
ac1efcc65159-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | 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 Pr... |
ac1efcc65159-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | ----------------------------------------------------------------------------------------------------
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 ye... |
ac1efcc65159-5 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | 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 ... |
ac1efcc65159-6 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | 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.
---------------------------------------------------------... |
ac1efcc65159-7 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/cohere-reranker.html | 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... |
9d3cfdd4a9cf-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html | .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 = ... |
9d3cfdd4a9cf-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html | Pinecone Hybrid Search
Contents
Ingest Documents
Query
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
f6ac0121cfa0-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html | .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 t... |
f6ac0121cfa0-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html | ['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... |
f6ac0121cfa0-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html | 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 co... |
42bde46a339a-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html | .ipynb
.pdf
Getting Started
Getting Started#
The default recommended text splitter is the RecursiveCharacterTextSplitter. This text splitter takes a list of characters. It tries to create chunks based on splitting on the first character, but if any chunks are too large it then moves onto the next character, and so fort... |
42bde46a339a-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
965d5e8e88a2-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken.html | .ipynb
.pdf
tiktoken (OpenAI) tokenizer
tiktoken (OpenAI) tokenizer#
tiktoken is a fast BPE tokenizer created by OpenAI.
We can use it to estimate tokens used. It will probably be more accurate for the OpenAI models.
How the text is split: by character passed in
How the chunk size is measured: by tiktoken tokenizer
#!p... |
e42eda39b4df-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html | .ipynb
.pdf
spaCy
spaCy#
spaCy is an open-source software library for advanced natural language processing, written in the programming languages Python and Cython.
Another alternative to NLTK is to use Spacy tokenizer.
How the text is split: by spaCy tokenizer
How the chunk size is measured: by number of characters
#!p... |
e42eda39b4df-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
9a43c56d6a13-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken_splitter.html | .ipynb
.pdf
Tiktoken
Tiktoken#
tiktoken is a fast BPE tokeniser created by OpenAI.
How the text is split: by tiktoken tokens
How the chunk size is measured: by tiktoken tokens
#!pip install tiktoken
# This is a long document we can split up.
with open('../../../state_of_the_union.txt') as f:
state_of_the_union = f.... |
c574b669ab2e-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html | .ipynb
.pdf
Recursive Character
Recursive Character#
This text splitter is the recommended one for generic text. It is parameterized by a list of characters. It tries to split on them in order until the chunks are small enough. The default list is ["\n\n", "\n", " ", ""]. This has the effect of trying to keep all parag... |
c574b669ab2e-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
f30a7677f40b-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html | .ipynb
.pdf
Character
Character#
This is the simplest method. This splits based on characters (by default “\n\n”) and measure chunk length by number of characters.
How the text is split: by single character
How the chunk size is measured: by number of characters
# This is a long document we can split up.
with open('../... |
f30a7677f40b-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html | 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.... |
f30a7677f40b-2 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html | 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.... |
f30a7677f40b-3 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html | '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 imp... |
1e9ac5e9caf8-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/huggingface_length_function.html | .ipynb
.pdf
Hugging Face tokenizer
Hugging Face tokenizer#
Hugging Face has many tokenizers.
We use Hugging Face tokenizer, the GPT2TokenizerFast to count the text length in tokens.
How the text is split: by character passed in
How the chunk size is measured: by number of tokens calculated by the Hugging Face tokenizer... |
c6e8f9a1b48f-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html | .ipynb
.pdf
NLTK
NLTK#
The Natural Language Toolkit, or more commonly NLTK, is a suite of libraries and programs for symbolic and statistical natural language processing (NLP) for English written in the Python programming language.
Rather than just splitting on “\n\n”, we can use NLTK to split based on NLTK tokenizers.... |
c6e8f9a1b48f-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html | Groups of citizens blocking tanks with their bodies.
previous
CodeTextSplitter
next
Recursive Character
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
65239cddb5df-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html | .ipynb
.pdf
CodeTextSplitter
Contents
Python
JS
Markdown
Latex
HTML
CodeTextSplitter#
CodeTextSplitter allows you to split your code with multiple language support. Import enum Language and specify the language.
from langchain.text_splitter import (
RecursiveCharacterTextSplitter,
Language,
)
# Full list of s... |
65239cddb5df-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html | language=Language.JS, chunk_size=60, chunk_overlap=0
)
js_docs = js_splitter.create_documents([JS_CODE])
js_docs
[Document(page_content='function helloWorld() {\n console.log("Hello, World!");\n}', metadata={}),
Document(page_content='// Call the function\nhelloWorld();', metadata={})]
Markdown#
Here’s an example usi... |
65239cddb5df-2 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html | Large language models (LLMs) are a type of machine learning model that can be trained on vast amounts of text data to generate human-like language. In recent years, LLMs have made significant advances in a variety of natural language processing tasks, including language translation, text generation, and sentiment analy... |
65239cddb5df-3 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html | Document(page_content='generation, and sentiment analysis.', metadata={}),
Document(page_content='\\subsection{History of LLMs}', metadata={}),
Document(page_content='The earliest LLMs were developed in the 1980s and 1990s,', metadata={}),
Document(page_content='but they were limited by the amount of data that could... |
65239cddb5df-4 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html | <p>⚡ Building applications with LLMs through composability ⚡</p>
</div>
<div>
As an open source project in a rapidly developing field, we are extremely open to contributions.
</div>
</body>
</html>
"""
html_splitter = RecursiveCharacterTextSplitter.from_language(
language=Lan... |
65239cddb5df-5 | https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/code_splitter.html | Python
JS
Markdown
Latex
HTML
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
41e97a2f4de3-0 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html | .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 ... |
41e97a2f4de3-1 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html | 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 ... |
41e97a2f4de3-2 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html | 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 ve... |
fad083593a19-0 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html | .ipynb
.pdf
FAISS
Contents
Similarity Search with score
Saving and loading
Merging
FAISS#
Facebook AI Similarity Search (Faiss) is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. I... |
fad083593a19-1 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html | 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 ve... |
fad083593a19-2 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html | (Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n\nWe cannot let this happen. \n\nTonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act... |
fad083593a19-3 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html | Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n\nWe cannot let this happen. \n\nTonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act ... |
fad083593a19-4 | https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html | {'e0b74348-6c93-4893-8764-943139ec1d17': Document(page_content='foo', lookup_str='', metadata={}, lookup_index=0),
'd5211050-c777-493d-8825-4800e74cfdb6': Document(page_content='bar', lookup_str='', metadata={}, lookup_index=0)}
previous
ElasticSearch
next
LanceDB
Contents
Similarity Search with score
Saving and l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.