id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
115
4e130836d26f-0
.ipynb .pdf PydanticOutputParser PydanticOutputParser# This output parser allows users to specify an arbitrary JSON schema and query LLMs for JSON outputs that conform to that schema. Keep in mind that large language models are leaky abstractions! You’ll have to use an LLM with sufficient capacity to generate well-form...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html
4e130836d26f-1
prompt = PromptTemplate( template="Answer the user query.\n{format_instructions}\n{query}\n", input_variables=["query"], partial_variables={"format_instructions": parser.get_format_instructions()} ) _input = prompt.format_prompt(query=joke_query) output = model(_input.to_string()) parser.parse(output) Joke(...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html
cbc1d632057a-0
.ipynb .pdf OutputFixingParser OutputFixingParser# This output parser wraps another output parser and tries to fix any mmistakes The Pydantic guardrail simply tries to parse the LLM response. If it does not parse correctly, then it errors. But we can do other things besides throw errors. Specifically, we can pass the m...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
cbc1d632057a-1
24 return self.pydantic_object.parse_obj(json_object) File ~/.pyenv/versions/3.9.1/lib/python3.9/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 343 if (cls is None and object_hook is None and 344 parse_int is None and parse_float is N...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
cbc1d632057a-2
Cell In[6], line 1 ----> 1 parser.parse(misformatted) File ~/workplace/langchain/langchain/output_parsers/pydantic.py:29, in PydanticOutputParser.parse(self, text) 27 name = self.pydantic_object.__name__ 28 msg = f"Failed to parse {name} from completion {text}. Got: {e}" ---> 29 raise OutputParserException(ms...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
9415f889af4a-0
.ipynb .pdf Structured Output Parser Structured Output Parser# While the Pydantic/JSON parser is more powerful, we initially experimented data structures having text fields only. from langchain.output_parsers import StructuredOutputParser, ResponseSchema from langchain.prompts import PromptTemplate, ChatPromptTemplate,...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html
9415f889af4a-1
], input_variables=["question"], partial_variables={"format_instructions": format_instructions} ) _input = prompt.format_prompt(question="what's the capital of france") output = chat_model(_input.to_messages()) output_parser.parse(output.content) {'answer': 'Paris', 'source': 'https://en.wikipedia.org/wiki/Pari...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html
025fd23f8ce2-0
.ipynb .pdf RetryOutputParser RetryOutputParser# While in some cases it is possible to fix any parsing mistakes by only looking at the output, in other cases it can’t. An example of this is when the output is not just in the incorrect format, but is partially complete. Consider the below example. from langchain.prompts...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
025fd23f8ce2-1
23 json_object = json.loads(json_str) ---> 24 return self.pydantic_object.parse_obj(json_object) 26 except (json.JSONDecodeError, ValidationError) as e: File ~/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pydantic/main.py:527, in pydantic.main.BaseModel.parse_obj() File ~/.pyenv/version...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
025fd23f8ce2-2
fix_parser.parse(bad_response) Action(action='search', action_input='') Instead, we can use the RetryOutputParser, which passes in the prompt (as well as the original output) to try again to get a better response. from langchain.output_parsers import RetryWithErrorOutputParser retry_parser = RetryWithErrorOutputParser....
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
5222aaa53712-0
.rst .pdf Text Splitters Text Splitters# Note Conceptual Guide When you want to deal with long pieces of text, it is necessary to split up that text into chunks. As simple as this sounds, there is a lot of potential complexity here. Ideally, you want to keep the semantically related pieces of text together. What “seman...
https://python.langchain.com/en/latest/modules/indexes/text_splitters.html
67bab73a3312-0
.rst .pdf Retrievers Retrievers# Note Conceptual Guide The retriever interface is a generic interface that makes it easy to combine documents with language models. This interface exposes a get_relevant_documents method which takes in a query (a string) and returns a list of documents. Please see below for a list of all...
https://python.langchain.com/en/latest/modules/indexes/retrievers.html
83b2a0fabe45-0
.rst .pdf Document Loaders Document Loaders# Note Conceptual Guide Combining language models with your own text data is a powerful way to differentiate them. The first step in doing this is to load the data into “documents” - a fancy way of say some pieces of text. This module is aimed at making this easy. A primary dr...
https://python.langchain.com/en/latest/modules/indexes/document_loaders.html
83b2a0fabe45-1
YouTube previous Getting Started next CoNLL-U By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/document_loaders.html
338dd6ff601c-0
.ipynb .pdf Getting Started Contents One Line Index Creation Walkthrough Getting Started# LangChain primary focuses on constructing indexes with the goal of using them as a Retriever. In order to best understand what this means, it’s worth highlighting what the base Retriever interface is. The BaseRetriever class in ...
https://python.langchain.com/en/latest/modules/indexes/getting_started.html
338dd6ff601c-1
Create a Retriever from that index Create a question answering chain Ask questions! Each of the steps has multiple sub steps and potential configurations. In this notebook we will primarily focus on (1). We will start by showing the one-liner for doing so, but then break down what is actually going on. First, let’s imp...
https://python.langchain.com/en/latest/modules/indexes/getting_started.html
338dd6ff601c-2
index.query_with_sources(query) {'question': 'What did the president say about Ketanji Brown Jackson', 'answer': " The president said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson, one of the nation's top legal minds, to continue Justice Breyer's legacy of excellence, and that she has received...
https://python.langchain.com/en/latest/modules/indexes/getting_started.html
338dd6ff601c-3
We will then select which embeddings we want to use. from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() We now create the vectorstore to use as the index. from langchain.vectorstores import Chroma db = Chroma.from_documents(texts, embeddings) Running Chroma using direct local API. Using D...
https://python.langchain.com/en/latest/modules/indexes/getting_started.html
338dd6ff601c-4
) Hopefully this highlights what is going on under the hood of VectorstoreIndexCreator. While we think it’s important to have a simple way to create indexes, we also think it’s important to understand what’s going on under the hood. previous Indexes next Document Loaders Contents One Line Index Creation Walkthrough...
https://python.langchain.com/en/latest/modules/indexes/getting_started.html
218cf920a44d-0
.rst .pdf Vectorstores Vectorstores# Note Conceptual Guide Vectorstores are one of the most important components of building indexes. For an introduction to vectorstores and generic functionality see: Getting Started We also have documentation for all the types of vectorstores that are supported. Please see below for t...
https://python.langchain.com/en/latest/modules/indexes/vectorstores.html
1321fbc6d008-0
.ipynb .pdf Getting Started Getting Started# The default recommended text splitter is the RecursiveCharacterTextSplitter. This text splitter takes a list of characters. It tries to create chunks based on splitting on the first character, but if any chunks are too large it then moves onto the next character, and so fort...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html
1321fbc6d008-1
previous Text Splitters next Character Text Splitter By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html
f485da5a0b1d-0
.ipynb .pdf Markdown Text Splitter Markdown Text Splitter# MarkdownTextSplitter splits text along Markdown headings, code blocks, or horizontal rules. It’s implemented as a simple subclass of RecursiveCharacterSplitter with Markdown-specific separators. See the source code to see the Markdown syntax expected by default...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/markdown.html
06ee0da3eb9f-0
.ipynb .pdf Python Code Text Splitter Python Code Text Splitter# PythonCodeTextSplitter splits text along python class and method definitions. It’s implemented as a simple subclass of RecursiveCharacterSplitter with Python-specific separators. See the source code to see the Python syntax expected by default. How the te...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/python.html
f66cba0054aa-0
.ipynb .pdf TiktokenText Splitter TiktokenText Splitter# How the text is split: by tiktoken tokens How the chunk size is measured: by tiktoken tokens # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: state_of_the_union = f.read() from langchain.text_splitter import TokenT...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken_splitter.html
3e281f8c0aec-0
.ipynb .pdf Hugging Face Length Function Hugging Face Length Function# Most LLMs are constrained by the number of tokens that you can pass in, which is not the same as the number of characters. In order to get a more accurate estimate, we can use Hugging Face tokenizers to count the text length. How the text is split: ...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/huggingface_length_function.html
22c678844507-0
.ipynb .pdf tiktoken (OpenAI) Length Function tiktoken (OpenAI) Length Function# You can also use tiktoken, a open source tokenizer package from OpenAI to estimate tokens used. Will probably be more accurate for their models. How the text is split: by character passed in How the chunk size is measured: by tiktoken toke...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken.html
7f5c0c86b3e9-0
.ipynb .pdf NLTK Text Splitter NLTK Text Splitter# Rather than just splitting on “\n\n”, we can use NLTK to split based on tokenizers. How the text is split: by NLTK How the chunk size is measured: by length function passed in (defaults to number of characters) # This is a long document we can split up. with open('../....
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html
7f5c0c86b3e9-1
previous Markdown Text Splitter next Python Code Text Splitter By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html
24c942a7f65d-0
.ipynb .pdf Latex Text Splitter Latex Text Splitter# LatexTextSplitter splits text along Latex headings, headlines, enumerations and more. It’s implemented as a simple subclass of RecursiveCharacterSplitter with Latex-specific separators. See the source code to see the Latex syntax expected by default. How the text is ...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/latex.html
24c942a7f65d-1
docs = latex_splitter.create_documents([latex_text]) docs [Document(page_content='\\documentclass{article}\n\n\x08egin{document}\n\n\\maketitle', lookup_str='', metadata={}, lookup_index=0), Document(page_content='Introduction}\nLarge language models (LLMs) are a type of machine learning model that can be trained on v...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/latex.html
1eb19e20b148-0
.ipynb .pdf Spacy Text Splitter Spacy Text Splitter# Another alternative to NLTK is to use Spacy. How the text is split: by Spacy How the chunk size is measured: by length function passed in (defaults to number of characters) # This is a long document we can split up. with open('../../../state_of_the_union.txt') as f: ...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html
1eb19e20b148-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html
540a164a308e-0
.ipynb .pdf RecursiveCharacterTextSplitter RecursiveCharacterTextSplitter# 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 tr...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html
e3a0b2171a15-0
.ipynb .pdf Character Text Splitter Character Text Splitter# This is a more simple 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 length function passed in (defaults to number of ...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
e3a0b2171a15-1
texts = text_splitter.create_documents([state_of_the_union]) print(texts[0]) page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally to...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
e3a0b2171a15-2
print(documents[0]) page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republica...
https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html
fbd55459a0f9-0
.ipynb .pdf Contextual Compression Retriever Contents Contextual Compression Retriever 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 C...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-1
texts = text_splitter.split_documents(documents) retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever() docs = retriever.get_relevant_documents("What did the president say about Ketanji Brown Jackson") pretty_print_docs(docs) Document 1: Tonight. I call on the Senate to: Pass the Freedom to Vote Act...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-2
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...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-3
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...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-4
More built-in compressors: filters# LLMChainFilter# The LLMChainFilter is slightly simpler but more robust compressor that uses an LLM chain to decide which of the initially retrieved documents to filter out and which ones to return, without manipulating the document contents. from langchain.retrievers.document_compres...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-5
from langchain.retrievers.document_compressors import EmbeddingsFilter embeddings = OpenAIEmbeddings() embeddings_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76) compression_retriever = ContextualCompressionRetriever(base_compressor=embeddings_filter, base_retriever=retriever) compressed_doc...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-6
We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have th...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-7
Below we create a compressor pipeline by first splitting our docs into smaller chunks, then removing redundant documents, and then filtering based on relevance to the query. from langchain.document_transformers import EmbeddingsRedundantFilter from langchain.retrievers.document_compressors import DocumentCompressorPipe...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
fbd55459a0f9-8
previous ChatGPT Plugin Retriever next Databerry Contents Contextual Compression Retriever Using a vanilla vector store retriever Adding contextual compression with an LLMChainExtractor More built-in compressors: filters LLMChainFilter EmbeddingsFilter Stringing compressors and document transformers together By Har...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html
dfe8b106f7bc-0
.ipynb .pdf Weaviate Hybrid Search Weaviate Hybrid Search# This notebook shows how to use Weaviate hybrid search as a LangChain retriever. import weaviate import os WEAVIATE_URL = "..." client = weaviate.Client( url=WEAVIATE_URL, ) from langchain.retrievers.weaviate_hybrid_search import WeaviateHybridSearchRetrieve...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html
0369f76595d2-0
.ipynb .pdf Metal Contents Ingest Documents Query Metal# 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...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html
0369f76595d2-1
previous ElasticSearch BM25 next Pinecone Hybrid Search Contents Ingest Documents Query By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html
370a13813106-0
.ipynb .pdf Self-querying retriever Contents Self-querying retriever Creating a Pinecone index Creating our self-querying retriever Testing it out Self-querying retriever# In the notebook we’ll demo the SelfQueryRetriever, which, as the name suggests, has the ability to query itself. Specifically, given any natural l...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query_retriever.html
370a13813106-1
from langchain.vectorstores import Pinecone embeddings = OpenAIEmbeddings() # create new index pinecone.create_index("langchain-self-retriever-demo", dimension=1536) docs = [ Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": [...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query_retriever.html
370a13813106-2
) Creating our self-querying retriever# Now we can instantiate our retriever. To do this we’ll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents. from langchain.llms import OpenAI from langchain.retrievers.self_query.base impor...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query_retriever.html
370a13813106-3
Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'year': 1995.0}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'director': 'Satoshi Kon', 'rating': 8.6, 'year': 2...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query_retriever.html
370a13813106-4
[Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'director': 'Greta Gerwig', 'rating': 8.3, 'year': 2019.0})] # This example specifies a composite filter retriever.get_relevant_documents("What's a highly rated (above 8.5) science fiction film?") quer...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query_retriever.html
370a13813106-5
next SVM Retriever Contents Self-querying retriever Creating a Pinecone index Creating our self-querying retriever Testing it out By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query_retriever.html
dee9e29a7301-0
.ipynb .pdf ChatGPT Plugin Retriever Contents Create Using the ChatGPT Retriever Plugin ChatGPT Plugin Retriever# This notebook shows how to use the ChatGPT Retriever Plugin within LangChain. Create# First, let’s go over how to create the ChatGPT Retriever Plugin. To set up the ChatGPT Retriever Plugin, please follow...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin-retriever.html
dee9e29a7301-1
The below code walks through how to do that. 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=...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin-retriever.html
dee9e29a7301-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': Non...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin-retriever.html
8adaca1bc052-0
.ipynb .pdf SVM Retriever Contents Create New Retriever with Texts Use Retriever SVM Retriever# This notebook goes over how to use a retriever that under the hood uses an SVM using scikit-learn. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb from langchain.retrievers import SVMRet...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/svm_retriever.html
4062c1f7833f-0
.ipynb .pdf VectorStore Retriever VectorStore Retriever# The index - and therefore the retriever - that LangChain has the most support for is a VectorStoreRetriever. As the name suggests, this retriever is backed heavily by a VectorStore. Once you construct a VectorStore, its very easy to construct a retriever. Let’s w...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore-retriever.html
4062c1f7833f-1
next Weaviate Hybrid Search By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore-retriever.html
436f9afb0ac5-0
.ipynb .pdf Time Weighted VectorStore Retriever Contents Low Decay Rate High Decay Rate Time Weighted VectorStore Retriever# This retriever uses a combination of semantic similarity and recency. The algorithm for scoring them is: semantic_similarity + (1.0 - decay_rate) ** hours_passed Notably, hours_passed refers to...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
436f9afb0ac5-1
retriever.add_documents([Document(page_content="hello foo")]) ['5c9f7c06-c9eb-45f2-aea5-efce5fb9f2bd'] # "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', m...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
436f9afb0ac5-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})]...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html
c815fa5fdd09-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# 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...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
c815fa5fdd09-1
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...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
c815fa5fdd09-2
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 retriever Contents Setup Pinecone Get embeddings and sparse encoders Load Retriever Add texts (if necessary) Use Retriever By Harrison C...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html
c8da80059294-0
.ipynb .pdf Databerry Contents Query Databerry# 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 Query# Now that our index is set up, we can set up a retriever and start querying it. from lang...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
c8da80059294-1
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...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
c8da80059294-2
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 ...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html
36b5ec6cd578-0
.ipynb .pdf ElasticSearch BM25 Contents Create New Retriever Add texts (if necessary) Use Retriever ElasticSearch BM25# This notebook goes over how to use a retriever that under the hood uses ElasticSearcha and BM25. For more information on the details of BM25 see this blog post. from langchain.retrievers import Elas...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html
36b5ec6cd578-1
result = retriever.get_relevant_documents("foo") result [Document(page_content='foo', metadata={}), Document(page_content='foo bar', metadata={})] previous Databerry next Metal Contents Create New Retriever Add texts (if necessary) Use Retriever By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html
b34ec7c1ecff-0
.ipynb .pdf TF-IDF Retriever Contents Create New Retriever with Texts Use Retriever TF-IDF Retriever# This notebook goes over how to use a retriever that under the hood uses TF-IDF using scikit-learn. For more information on the details of TF-IDF see this blog post. from langchain.retrievers import TFIDFRetriever # !...
https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/tf_idf_retriever.html
1cdc500e8690-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 ...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html
1cdc500e8690-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 h...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html
1cdc500e8690-2
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 s...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/getting_started.html
0d016b73d178-0
.ipynb .pdf FAISS Contents Similarity Search with score Saving and loading Merging FAISS# This notebook shows how to use functionality related to the FAISS vector database. from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores im...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
0d016b73d178-1
Similarity Search with score# There are some FAISS specific methods. One of them is similarity_search_with_score, which allows you to return not only the documents but also the similarity score of the query to them. docs_and_scores = db.similarity_search_with_score(query) docs_and_scores[0] (Document(page_content='In s...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
0d016b73d178-2
db.save_local("faiss_index") new_db = FAISS.load_local("faiss_index", embeddings) docs = new_db.similarity_search(query) docs[0] Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n\nWe cannot let this happen. \n\nTonight. I call on t...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
0d016b73d178-3
db2.docstore._dict {'bdc50ae3-a1bb-4678-9260-1b0979578f40': Document(page_content='bar', lookup_str='', metadata={}, lookup_index=0)} db1.merge_from(db2) db1.docstore._dict {'e0b74348-6c93-4893-8764-943139ec1d17': Document(page_content='foo', lookup_str='', metadata={}, lookup_index=0), 'd5211050-c777-493d-8825-4800e7...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html
f0fb4bf5fdf9-0
.ipynb .pdf LanceDB LanceDB# This notebook shows how to use functionality related to the LanceDB vector database based on the Lance data format. #!pip install lancedb from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import LanceDB from langchain.document_loaders import TextLoader from langc...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/lanecdb.html
f0fb4bf5fdf9-1
So let’s not abandon our streets. Or choose between safety and equal justice. Let’s come together to protect our communities, restore trust, and hold law enforcement accountable. That’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers. That’s why ...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/lanecdb.html
f0fb4bf5fdf9-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: Justi...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/lanecdb.html
34e3b7713c96-0
.ipynb .pdf Deep Lake Contents Retrieval Question/Answering Attribute based filtering in metadata Choosing distance function Maximal Marginal relevance Delete dataset Deep Lake datasets on cloud (Activeloop, AWS, GCS, etc.) or local Creating dataset on AWS S3 Deep Lake API Transfer local dataset to cloud Deep Lake# T...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-1
query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query) ./my_deeplake/ loaded successfully. Evaluating ingest: 100%|██████████| 1/1 [00:04<00:00 Dataset(path='./my_deeplake/', tensors=['embedding', 'ids', 'metadata', 'text']) tensor htype shape dtype compressio...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-2
docs = db.similarity_search(query) ./my_deeplake/ loaded successfully. Deep Lake Dataset in ./my_deeplake/ already exists, loading from the storage Dataset(path='./my_deeplake/', read_only=True, tensors=['embedding', 'ids', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- -...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-3
Attribute based filtering in metadata# import random for d in docs: d.metadata['year'] = random.randint(2012, 2014) db = DeepLake.from_documents(docs, embeddings, dataset_path="./my_deeplake/", overwrite=True) ./my_deeplake/ loaded successfully. Evaluating ingest: 100%|██████████| 1/1 [00:04<00:00 Dataset(path='./m...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-4
[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: Justic...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-5
Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-6
[Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justic...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-7
Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-8
Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-9
Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards ...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-10
[Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justic...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-11
Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards ...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-12
Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-13
Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-14
username = "<username>" # your username on app.activeloop.ai dataset_path = f"hub://{username}/langchain_test" # could be also ./local/path (much faster locally), s3://bucket/path/to/dataset, gcs://path/to/dataset, etc. embedding = OpenAIEmbeddings() db = DeepLake(dataset_path=dataset_path, embedding_function=embedd...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-15
'd6d6ccb7-e187-11ed-b66d-41c5f7b85421'] query = "What did the president say about Ketanji Brown Jackson" docs = db.similarity_search(query) print(docs[0].page_content) Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so ...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html
34e3b7713c96-16
}) s3://hub-2.0-datasets-n/langchain_test loaded successfully. Evaluating ingest: 100%|██████████| 1/1 [00:10<00:00 \ Dataset(path='s3://hub-2.0-datasets-n/langchain_test', tensors=['embedding', 'ids', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- ------- ------- ----...
https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html