id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
35575b995100-4 | 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
OpenSearch
next
Pinecone
Contents
... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/pgvector.html |
2f7539fe40c0-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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-1 | embeddings = OpenAIEmbeddings()
Creates a dataset locally at ./deeplake/, then runs similiarity search
db = DeepLake(dataset_path="./my_deeplake/", embedding_function=embeddings, overwrite=True)
db.add_documents(docs)
# or shorter
# db = DeepLake.from_documents(docs, dataset_path="./my_deeplake/", embedding=embeddings,... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-2 | 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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-3 | Retrieval Question/Answering#
from langchain.chains import RetrievalQA
from langchain.llms import OpenAIChat
qa = RetrievalQA.from_chain_type(llm=OpenAIChat(model='gpt-3.5-turbo'), chain_type='stuff', retriever=db.as_retriever())
/media/sdb/davit/Git/experiments/langchain/langchain/llms/openai.py:672: UserWarning: You ... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-4 | Evaluating ingest: 100%|██████████| 1/1 [00:04<00:00
Dataset(path='./my_deeplake/', tensors=['embedding', 'ids', 'metadata', 'text'])
tensor htype shape dtype compression
------- ------- ------- ------- -------
embedding generic (4, 1536) float32 None
ids text (4, 1) ... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-5 | [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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-6 | 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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-7 | [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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-8 | 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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-9 | 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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-10 | 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 ... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-11 | [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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-12 | 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 ... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-13 | 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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-14 | 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... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-15 | By default deep lake datasets are stored in memory, in case you want to persist locally or to any object storage you can simply provide path to the dataset. You can retrieve token from app.activeloop.ai
os.environ['ACTIVELOOP_TOKEN'] = getpass.getpass('Activeloop Token:')
# Embed and store the texts
username = "<userna... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-16 | embedding generic (4, 1536) float32 None
ids text (4, 1) str None
metadata json (4, 1) str None
text text (4, 1) str None
['d6d6ccb4-e187-11ed-b66d-41c5f7b85421',
'd6d6ccb5-e187-11ed-b66d-41c5f7b85421',
'd6d6ccb6-e187-11ed-b66d-41c5f7b85421'... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-17 | Creating dataset on AWS S3#
dataset_path = f"s3://BUCKET/langchain_test" # could be also ./local/path (much faster locally), hub://bucket/path/to/dataset, gcs://path/to/dataset, etc.
embedding = OpenAIEmbeddings()
db = DeepLake.from_documents(docs, dataset_path=dataset_path, embedding=embeddings, overwrite=True, creds ... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-18 | # get structure of the dataset
db.ds.summary()
Dataset(path='hub://davitbun/langchain_test', tensors=['embedding', 'ids', 'metadata', 'text'])
tensor htype shape dtype compression
------- ------- ------- ------- -------
embedding generic (4, 1536) float32 None
ids text (4,... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-19 | The dataset is private so make sure you are logged in!
Dataset(path='hub://davitbun/langchain_test_copy', tensors=['embedding', 'ids', 'metadata', 'text'])
db = DeepLake(dataset_path=destination, embedding_function=embeddings)
db.add_documents(docs)
This dataset can be visualized in Jupyter Notebook by ds.visualize()... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
2f7539fe40c0-20 | ids text (8, 1) str None
metadata json (8, 1) str None
text text (8, 1) str None
['ad42f3fe-e188-11ed-b66d-41c5f7b85421',
'ad42f3ff-e188-11ed-b66d-41c5f7b85421',
'ad42f400-e188-11ed-b66d-41c5f7b85421',
'ad42f401-e188-11ed-b66d-41c5f7b85421']
previous... | /content/https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/deeplake.html |
7d8985a87e12-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate-hybrid.html |
cb1c07c78b40-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html |
cb1c07c78b40-1 | Document(page_content='foo1', metadata={'dist': '4.05311584473e-06', 'id': '642738f67559b026b4430e3c', 'createdAt': '2023-03-31T19:48:06.769Z'})]
previous
ElasticSearch BM25
next
Pinecone Hybrid Search
Contents
Ingest Documents
Query
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updat... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/metal.html |
d9f4f63130e2-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html |
d9f4f63130e2-1 | 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
... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html |
d9f4f63130e2-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"])
10... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html |
94865f05ce44-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html |
94865f05ce44-1 | 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
Metal
Contents
Create New Retriever
Add texts (if necessary)
Use Retriever
By Harrison Chase
... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html |
aba9a978dfe4-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
# !... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/tf_idf_retriever.html |
8a72884aa1e1-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin-retriever.html |
8a72884aa1e1-1 | 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
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 thro... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin-retriever.html |
8a72884aa1e1-2 | 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}, l... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chatgpt-plugin-retriever.html |
798f658e4e7a-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/svm_retriever.html |
ccfac79b2e09-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html |
ccfac79b2e09-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")])
['5c9f7c06-c9eb-45f2-aea5-efce5fb9f2bd']
# "Hello World" is returned first because it is most salient, an... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html |
ccfac79b2e09-2 | 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 w... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/time_weighted_vectorstore.html |
6d8d9b01d0b6-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-1 | from langchain.embeddings import OpenAIEmbeddings
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS
documents = TextLoader('../../../state_of_the_union.txt').load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(docu... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-2 | ----------------------------------------------------------------------------------------------------
Document 2:
A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-3 | 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.
----------... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-4 | from langchain.llms import OpenAI
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor
llm = OpenAI(temperature=0)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=compre... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-5 | from langchain.retrievers.document_compressors import LLMChainFilter
_filter = LLMChainFilter.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=_filter, base_retriever=retriever)
compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji J... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-6 | from langchain.embeddings import OpenAIEmbeddings
from langchain.retrievers.document_compressors import EmbeddingsFilter
embeddings = OpenAIEmbeddings()
embeddings_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76)
compression_retriever = ContextualCompressionRetriever(base_compressor=embedding... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-7 | ----------------------------------------------------------------------------------------------------
Document 2:
A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-8 | And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things.
So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together.
First, beat the opioid epidemic.
Stringing ... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6d8d9b01d0b6-9 | pipeline_compressor = DocumentCompressorPipeline(
transformers=[splitter, redundant_filter, relevant_filter]
)
compression_retriever = ContextualCompressionRetriever(base_compressor=pipeline_compressor, base_retriever=retriever)
compressed_docs = compression_retriever.get_relevant_documents("What did the president ... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html |
6a5fae8e79ae-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore-retriever.html |
6a5fae8e79ae-1 | You can also specify search kwargs like k to use when doing retrieval.
retriever = db.as_retriever(search_kwargs={"k": 1})
docs = retriever.get_relevant_documents("what did he say abotu ketanji brown jackson")
len(docs)
1
previous
Time Weighted VectorStore Retriever
next
Weaviate Hybrid Search
By Harrison Chase
... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore-retriever.html |
0ab7cb210849-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html |
0ab7cb210849-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... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html |
0ab7cb210849-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 ... | /content/https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/databerry.html |
79054484ab5b-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html |
79054484ab5b-1 | print(texts[0])
print(texts[1])
page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and' lookup_str='' metadata={} lookup_index=0
page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.' lookup_str='' metadata={} lookup_index... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/getting_started.html |
26e044b2f8d8-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('../.... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html |
26e044b2f8d8-1 | Instead he met a wall of strength he never imagined.
He met the Ukrainian people.
From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world.
Groups of citizens blocking tanks with their bodies.
previous
Markdown Text Splitter
next
Python Code Text Splitter
B... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/nltk.html |
0475425c7328-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/markdown.html |
0475425c7328-1 | Document(page_content='As an open source project in a rapidly developing field, we are extremely open to contributions.', lookup_str='', metadata={}, lookup_index=0)]
previous
Latex Text Splitter
next
NLTK Text Splitter
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/markdown.html |
dfaca18870c4-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html |
dfaca18870c4-1 | page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.' lookup_str='' metadata={} lookup_index=0
previous
Python Code Text Splitter
next
Spacy Text Splitter
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/recursive_text_splitter.html |
878d7ea9dc6f-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken_splitter.html |
c1a98666e96b-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:
... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html |
c1a98666e96b-1 | previous
RecursiveCharacterTextSplitter
next
tiktoken (OpenAI) Length Function
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/spacy.html |
0364198c70d5-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/python.html |
f376d487348b-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 ... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html |
f376d487348b-1 | print(texts[0])
page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans a... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html |
f376d487348b-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/character_text_splitter.html |
17d13aedd2d3-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: ... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/huggingface_length_function.html |
17d13aedd2d3-1 | next
Latex Text Splitter
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/huggingface_length_function.html |
461215ce8e73-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... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/tiktoken.html |
8df45990319e-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 ... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/latex.html |
8df45990319e-1 | \end{document}
"""
latex_splitter = LatexTextSplitter(chunk_size=400, chunk_overlap=0)
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}\nLar... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/latex.html |
8df45990319e-2 | Document(page_content='Applications of LLMs}\nLLMs have many applications in industry, including chatbots, content creation, and virtual assistants. They can also be used in academia for research in linguistics, psychology, and computational linguistics.\n\n\\end{document}', lookup_str='', metadata={}, lookup_index=0)]... | /content/https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/latex.html |
0c19f3c95fbc-0 | .rst
.pdf
How-To Guides
How-To Guides#
A chain is made up of links, which can be either primitives or other chains.
Primitives can be either prompts, models, arbitrary functions, or other chains.
The examples here are broken up into three sections:
Generic Functionality
Covers both generic chains (that are useful in a ... | /content/https://python.langchain.com/en/latest/modules/chains/how_to_guides.html |
66d7e69b8479-0 | .ipynb
.pdf
Getting Started
Contents
Why do we need chains?
Quick start: Using LLMChain
Different ways of calling chains
Add memory to chains
Debug Chain
Combine chains with the SequentialChain
Create a custom chain with the Chain class
Getting Started#
In this tutorial, we will learn about creating simple chains in ... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-1 | from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
# Run the chain only specifying the input variable.
print(chain.run("colorful socks"))
SockSplash!
You can use a chat model in an LLMChain as well:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPro... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-2 | {'adjective': 'corny',
'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
By default, __call__ returns both the input and output key values. You can configure it to only return output key values by setting return_only_outputs to True.
llm_chain("corny", return_only_outputs=True)
{'text': 'Why d... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-3 | Add memory to chains#
Chain supports taking a BaseMemory object as its memory argument, allowing Chain object to persist data across multiple calls. In other words, it makes Chain a stateful object.
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
conversation = Conve... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-4 | > Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-5 | template="Write a catchphrase for the following company: {company_name}",
)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
Now we can combine the two LLMChains, so that we can create a company name and a catchphrase in a single step.
from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequenti... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-6 | # Union of the input keys of the two chains.
all_input_vars = set(self.chain_1.input_keys).union(set(self.chain_2.input_keys))
return list(all_input_vars)
@property
def output_keys(self) -> List[str]:
return ['concat_output']
def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
66d7e69b8479-7 | Socktastic Colors.
"Put Some Color in Your Step!"
That’s it! For more details about how to do cool things with Chains, check out the how-to guide for chains.
previous
Chains
next
How-To Guides
Contents
Why do we need chains?
Quick start: Using LLMChain
Different ways of calling chains
Add memory to chains
Debug Cha... | /content/https://python.langchain.com/en/latest/modules/chains/getting_started.html |
d4848c814a89-0 | .ipynb
.pdf
Sequential Chains
Contents
SimpleSequentialChain
Sequential Chain
Memory in Sequential Chains
Sequential Chains#
The next step after calling a language model is make a series of calls to a language model. This is particularly useful when you want to take the output from one call and use it as the input to... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-1 | Title: {title}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title"], template=template)
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)
# This is an LLMChain to write a review of a play given a synopsis.
llm = OpenAI(temperature=.7)
template = """Yo... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-2 | > Entering new SimpleSequentialChain chain...
Tragedy at Sunset on the Beach is a story of a young couple, Jack and Sarah, who are in love and looking forward to their future together. On the night of their anniversary, they decide to take a walk on the beach at sunset. As they are walking, they come across a mysteriou... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-3 | The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful.
> Finished... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-4 | Of particular importance is how we name the input/output variable names. In the above example we didn’t have to think about that because we were just passing the output of one chain directly as input to the next, but here we do have worry about that because we have multiple inputs.
# This is an LLMChain to write a syno... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-5 | # This is the overall chain where we run these two chains in sequence.
from langchain.chains import SequentialChain
overall_chain = SequentialChain(
chains=[synopsis_chain, review_chain],
input_variables=["era", "title"],
# Here we return multiple variables
output_variables=["synopsis", "review"],
v... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-6 | 'era': 'Victorian England',
'synopsis': "\n\nThe play follows the story of John, a young man from a wealthy Victorian family, who dreams of a better life for himself. He soon meets a beautiful young woman named Mary, who shares his dream. The two fall in love and decide to elope and start a new life together.\n\nOn th... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-7 | 'review': "\n\nThe latest production from playwright X is a powerful and heartbreaking story of love and loss set against the backdrop of 19th century England. The play follows John, a young man from a wealthy Victorian family, and Mary, a beautiful young woman with whom he falls in love. The two decide to elope and st... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-8 | For example, using the previous playwright SequentialChain, lets say you wanted to include some context about date, time and location of the play, and using the generated synopsis and review, create some social media post text. You could add these new context variables as input_variables, or we can add a SimpleMemory ... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d4848c814a89-9 | input_variables=["era", "title"],
# Here we return multiple variables
output_variables=["social_post_text"],
verbose=True)
overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"})
> Entering new SequentialChain chain...
> Finished chain.
{'title': 'Tragedy at sunset on the beach... | /content/https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
eb064df12fe2-0 | .ipynb
.pdf
Loading from LangChainHub
Loading from LangChainHub#
This notebook covers how to load chains from LangChainHub.
from langchain.chains import load_chain
chain = load_chain("lc://chains/llm-math/chain.json")
chain.run("whats 2 raised to .12")
> Entering new LLMMathChain chain...
whats 2 raised to .12
Answer: ... | /content/https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
eb064df12fe2-1 | Using DuckDB in-memory for database. Data will be transient.
chain = load_chain("lc://chains/vector-db-qa/stuff/chain.json", vectorstore=vectorstore)
query = "What did the president say about Ketanji Brown Jackson"
chain.run(query)
" The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one... | /content/https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
c952b8464cf1-0 | .ipynb
.pdf
Serialization
Contents
Saving a chain to disk
Loading a chain from disk
Saving components separately
Serialization#
This notebook covers how to serialize chains to and from disk. The serialization format we use is json or yaml. Currently, only some chains support this type of serialization. We will grow t... | /content/https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
c952b8464cf1-1 | "temperature": 0.0,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"n": 1,
"best_of": 1,
"request_timeout": null,
"logit_bias": {},
"_type": "openai"
},
"output_key": "text",
"_type": "llm_chain"
}
Loading... | /content/https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
c952b8464cf1-2 | "template_format": "f-string"
}
llm_chain.llm.save("llm.json")
!cat llm.json
{
"model_name": "text-davinci-003",
"temperature": 0.0,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"n": 1,
"best_of": 1,
"request_timeout": null,
"logit_bias": {},
... | /content/https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
c952b8464cf1-3 | Prompt after formatting:
Question: whats 2 + 2
Answer: Let's think step by step.
> Finished chain.
' 2 + 2 = 4'
previous
Sequential Chains
next
Transformation Chain
Contents
Saving a chain to disk
Loading a chain from disk
Saving components separately
By Harrison Chase
© Copyright 2023, Harrison Chase.
... | /content/https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
36e7b8c4770d-0 | .ipynb
.pdf
LLM Chain
Contents
LLM Chain
Additional ways of running LLM Chain
Parsing the outputs
Initialize from string
LLM Chain#
LLMChain is perhaps one of the most popular ways of querying an LLM object. It formats the prompt template using the input key values provided (and also memory key values, if available),... | /content/https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.