id stringlengths 14 16 | text stringlengths 45 2.05k | source stringlengths 53 111 |
|---|---|---|
f37c475f5146-0 | .ipynb
.pdf
Pinecone
Pinecone#
This notebook shows how to use functionality related to the Pinecone vector database.
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Pinecone
from langchain.document_loaders import TextL... | https://langchain.readthedocs.io/en/latest/modules/indexes/vectorstore_examples/pinecone.html |
732c4d325943-0 | .ipynb
.pdf
ElasticSearch
ElasticSearch#
This notebook shows how to use functionality related to the ElasticSearch database.
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import ElasticVectorSearch
from langchain.document_l... | https://langchain.readthedocs.io/en/latest/modules/indexes/vectorstore_examples/elasticsearch.html |
732c4d325943-1 | 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
Deep Lake
next
FAISS
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 22, 20... | https://langchain.readthedocs.io/en/latest/modules/indexes/vectorstore_examples/elasticsearch.html |
b6b30973a376-0 | .ipynb
.pdf
VectorStores
Contents
Add texts
From Documents
VectorStores#
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 yourse... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/vectorstores.html |
b6b30973a376-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://langchain.readthedocs.io/en/latest/modules/indexes/examples/vectorstores.html |
b6b30973a376-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://langchain.readthedocs.io/en/latest/modules/indexes/examples/vectorstores.html |
eb846bfd8f86-0 | .ipynb
.pdf
Hypothetical Document Embeddings
Contents
Multiple generations
Using our own prompts
Using HyDE
Hypothetical Document Embeddings#
This notebook goes over how to use Hypothetical Document Embeddings (HyDE), as described in this paper.
At a high level, HyDE is an embedding technique that takes queries, gene... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/hyde.html |
eb846bfd8f86-1 | result = embeddings.embed_query("Where is the Taj Mahal?")
Using our own prompts#
Besides using preconfigured prompts, we can also easily construct our own prompts and use those in the LLMChain that is generating the documents. This can be useful if we know the domain our queries will be in, as we can condition the pro... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/hyde.html |
eb846bfd8f86-2 | Using DuckDB in-memory for database. Data will be transient.
print(docs[0].page_content)
In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections.
We cannot let this happen.
Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Votin... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/hyde.html |
cb2147dc524f-0 | .ipynb
.pdf
Text Splitter
Contents
Generic Recursive Text Splitting
Markdown Text Splitter
Latex Text Splitter
Python Code Text Splitter
Character Text Splitting
HuggingFace Length Function
tiktoken (OpenAI) Length Function
NLTK Text Splitter
Spacy Text Splitter
Token Text Splitter
Text Splitter#
When you want to dea... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-1 | state_of_the_union = f.read()
Generic Recursive Text Splitting#
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 kee... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-2 | from langchain.text_splitter import MarkdownTextSplitter
markdown_text = """
# 🦜️🔗 LangChain
⚡ Building applications with LLMs through composability ⚡
## Quick Install
```bash
# Hopefully this code block isn't split
pip install langchain
```
As an open source project in a rapidly developing field, we are extremely op... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-3 | \begin{document}
\maketitle
\section{Introduction}
Large language models (LLMs) are a type of machine learning model that can be trained on vast amounts of text data to generate human-like language. In recent years, LLMs have made significant advances in a variety of natural language processing tasks, including languag... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-4 | def foo():
def testing_func():
def bar():
"""
python_splitter = PythonCodeTextSplitter(chunk_size=30, chunk_overlap=0)
docs = python_splitter.create_documents([python_text])
docs
[Document(page_content='Foo:\n\n def bar():', lookup_str='', metadata={}, lookup_index=0),
Document(page_content='foo():\n\ndef testing_f... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-5 | 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://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-6 | 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://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-7 | texts = text_splitter.split_text(state_of_the_union)
print(texts[0])
Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.
Last year COVID-19 kept us apart. This year we are finally together again.
Tonight, w... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-8 | text_splitter = NLTKTextSplitter(chunk_size=1000)
texts = text_splitter.split_text(state_of_the_union)
print(texts[0])
Madam Speaker, Madam Vice President, our First Lady and Second Gentleman.
Members of Congress and the Cabinet.
Justices of the Supreme Court.
My fellow Americans.
Last year COVID-19 kept us apart.
This... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
cb2147dc524f-9 | My fellow Americans.
Last year COVID-19 kept us apart.
This year we are finally together again.
Tonight, we meet as Democrats Republicans and Independents.
But most importantly as Americans.
With a duty to one another to the American people to the Constitution.
And with an unwavering resolve that freedom will always... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/textsplitter.html |
53477c3d057e-0 | .ipynb
.pdf
Embeddings
Contents
OpenAI
AzureOpenAI
Cohere
Hugging Face Hub
TensorflowHub
InstructEmbeddings
Self Hosted Embeddings
Fake Embeddings
SageMaker Endpoint Embeddings
Embeddings#
This notebook goes over how to use the Embedding class in LangChain.
The Embedding class is a class designed for interfacing with... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/embeddings.html |
53477c3d057e-1 | text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
AzureOpenAI#
Let’s load the OpenAI Embedding class with environment variables set to indicate to use Azure endpoints.
# set the environment variables needed for openai package to know to reach o... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/embeddings.html |
53477c3d057e-2 | embeddings = TensorflowHubEmbeddings()
2023-01-30 23:53:01.652176: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operati... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/embeddings.html |
53477c3d057e-3 | # For an on-demand A100 with GCP, Azure, or Lambda
gpu = rh.cluster(name="rh-a10x", instance_type="A100:1", use_spot=False)
# For an on-demand A10G with AWS (no single A100s on AWS)
# gpu = rh.cluster(name='rh-a10x', instance_type='g5.2xlarge', provider='aws')
# For an existing cluster
# gpu = rh.cluster(ips=['<ip of t... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/embeddings.html |
53477c3d057e-4 | model_load_fn=get_pipeline,
hardware=gpu,
model_reqs=["./", "torch", "transformers"],
inference_fn=inference_fn,
)
query_result = embeddings.embed_query(text)
Fake Embeddings#
LangChain also provides a fake embedding class. You can use this to test your pipelines.
from langchain.embeddings import FakeEmbedd... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/embeddings.html |
53477c3d057e-5 | region_name="us-east-1",
content_handler=content_handler
)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
doc_results
previous
How To Guides
next
Hypothetical Document Embeddings
Contents
OpenAI
AzureOpenAI
Cohere
Hugging Face Hub
TensorflowHub
InstructEmbeddings... | https://langchain.readthedocs.io/en/latest/modules/indexes/examples/embeddings.html |
f4c02895d130-0 | .ipynb
.pdf
Graph QA
Contents
Create the graph
Querying the graph
Save the graph
Graph QA#
This notebook goes over how to do question answering over a graph data structure.
Create the graph#
In this section, we construct an example graph. At the moment, this works best for small pieces of text.
from langchain.indexes... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/graph_qa.html |
f4c02895d130-1 | 'is the ground on which')]
Querying the graph#
We can now use the graph QA chain to ask question of the graph
from langchain.chains import GraphQAChain
chain = GraphQAChain.from_llm(OpenAI(temperature=0), graph=graph, verbose=True)
chain.run("what is Intel going to build?")
> Entering new GraphQAChain chain...
Entities... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/graph_qa.html |
95c4f7c73985-0 | .ipynb
.pdf
VectorDB Question Answering with Sources
Contents
Chain Type
VectorDB Question Answering with Sources#
This notebook goes over how to do question-answering with sources over a vector database. It does this by using the VectorDBQAWithSourcesChain, which does the lookup of the documents from a vector databa... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa_with_sources.html |
95c4f7c73985-1 | 'sources': '30-pl'}
Chain Type#
You can easily specify different chain types to load and use in the VectorDBQAWithSourcesChain chain. For a more detailed walkthrough of these types, please see this notebook.
There are two ways to load different chain types. First, you can specify the chain type argument in the from_cha... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa_with_sources.html |
95c4f7c73985-2 | next
Vector DB Text Generation
Contents
Chain Type
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 22, 2023. | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa_with_sources.html |
b6792bab5f8e-0 | .ipynb
.pdf
Chat Vector DB
Contents
Return Source Documents
Chat Vector DB with search_distance
Chat Vector DB with map_reduce
Chat Vector DB with Question Answering with sources
Chat Vector DB with streaming to stdout
get_chat_history Function
Chat Vector DB#
This notebook goes over how to set up a chain to chat wit... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
b6792bab5f8e-1 | qa = ChatVectorDBChain.from_llm(OpenAI(temperature=0), vectorstore)
Here’s an example of asking a question with no chat history
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
result["answer"]
" The president said that Ket... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
b6792bab5f8e-2 | result['source_documents'][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 the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
b6792bab5f8e-3 | from langchain.chains import LLMChain
from langchain.chains.question_answering import load_qa_chain
from langchain.chains.chat_vector_db.prompts import CONDENSE_QUESTION_PROMPT
llm = OpenAI(temperature=0)
question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
doc_chain = load_qa_chain(llm, chain_type="... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
b6792bab5f8e-4 | chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = chain({"question": query, "chat_history": chat_history})
result['answer']
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal publi... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
b6792bab5f8e-5 | chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
b6792bab5f8e-6 | previous
Analyze Document
next
Graph QA
Contents
Return Source Documents
Chat Vector DB with search_distance
Chat Vector DB with map_reduce
Chat Vector DB with Question Answering with sources
Chat Vector DB with streaming to stdout
get_chat_history Function
By Harrison Chase
© Copyright 2023, Harrison Ch... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/chat_vector_db.html |
a39fe77e394c-0 | .ipynb
.pdf
Question Answering with Sources
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
The map-rerank Chain
Question Answering with Sources#
This notebook walks through how to use LangChain for question answering with sources over a list of documents. It covers four differe... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-1 | from langchain.chains.qa_with_sources import load_qa_with_sources_chain
from langchain.llms import OpenAI
Quickstart#
If you just want to get started as quickly as possible, this is the recommended way to do it:
chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff")
query = "What did the presiden... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-2 | PROMPT = PromptTemplate(template=template, input_variables=["summaries", "question"])
chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff", prompt=PROMPT)
query = "What did the president say about Justice Breyer"
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'out... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-3 | ' None',
' None',
' None'],
'output_text': ' The president thanked Justice Breyer for his service.\nSOURCES: 30-pl'}
Custom Prompts
You can also use your own prompts with this chain. In this example, we will respond in Italian.
question_prompt_template = """Use the following portion of a long document to see if an... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-4 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ["\nStasera vorrei onorare qualcuno che ha dedicato la sua vita a servire questo paese: il giustizia Stephen Breyer - un veterano dell'esercito, uno studioso costituzionale e un giustizia in uscita della Corte Suprema d... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-5 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': "\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked him for his service and praised his c... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-6 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ['\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service.... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-7 | '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-8 | '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-9 | 'output_text': '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal publi... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-10 | "answer the question (in Italian)"
"If you do update it, please update the sources as well. "
"If the context isn't useful, return the original answer."
)
refine_prompt = PromptTemplate(
input_variables=["question", "existing_answer", "context_str"],
template=refine_template,
)
question_template = (
... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-11 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-12 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-13 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-14 | 'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sotto... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-15 | 'score': '100'},
{'answer': ' This document does not answer the question', 'score': '0'},
{'answer': ' This document does not answer the question', 'score': '0'},
{'answer': ' This document does not answer the question', 'score': '0'}]
Custom Prompts
You can also use your own prompts with this chain. In this example... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
a39fe77e394c-16 | result
{'source': 30,
'intermediate_steps': [{'answer': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.',
'score': '100'},
{'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.',
'score': '100'},
{'answer': ' Non so.', '... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/qa_with_sources.html |
1bada55fce73-0 | .ipynb
.pdf
Analyze Document
Contents
Summarize
Question Answering
Analyze Document#
The AnalyzeDocumentChain is more of an end to chain. This chain takes in a single document, splits it up, and then runs it through a CombineDocumentsChain. This can be used as more of an end-to-end chain.
with open('../../state_of_th... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/analyze_document.html |
1bada55fce73-1 | qa_chain = load_qa_chain(llm, chain_type="map_reduce")
qa_document_chain = AnalyzeDocumentChain(combine_docs_chain=qa_chain)
qa_document_chain.run(input_document=state_of_the_union, question="what did the president say about justice breyer?")
' The president thanked Justice Breyer for his service.'
previous
Weaviate
ne... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/analyze_document.html |
52e143e51b52-0 | .ipynb
.pdf
Question Answering
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
The map-rerank Chain
Question Answering#
This notebook walks through how to use LangChain for question answering over a list of documents. It covers four different types of chains: stuff, map_reduce, ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-1 | chain.run(input_documents=docs, question=query)
' The president said that he was honoring Justice Breyer for his service to the country and that he was a Constitutional scholar, Army veteran, and retiring Justice of the United States Supreme Court.'
If you want more control and understanding over what is happening, ple... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-2 | The map_reduce Chain#
This sections shows results of using the map_reduce Chain to do question answering.
chain = load_qa_chain(OpenAI(temperature=0), chain_type="map_reduce")
query = "What did the president say about Justice Breyer"
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-3 | template=question_prompt_template, input_variables=["context", "question"]
)
combine_prompt_template = """Given the following extracted parts of a long document and a question, create a final answer italian.
If you don't know the answer, just say that you don't know. Don't try to make up an answer.
QUESTION: {question... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-4 | '\nNella mia amministrazione, i guardiani sono stati accolti di nuovo. Stiamo andando dietro ai criminali che hanno rubato miliardi di dollari di aiuti di emergenza destinati alle piccole imprese e a milioni di americani. E stasera, annuncio che il Dipartimento di Giustizia nominerà un procuratore capo per la frode pan... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-5 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': '\n\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his commitment to protecti... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-6 | '\n\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his commitment to protecting the rights of LGBTQ+ Americans and his support for the bipartisan Equality Act. He also men... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-7 | input_variables=["question", "existing_answer", "context_str"],
template=refine_prompt_template,
)
initial_qa_template = (
"Context information is below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given the context information and not prior knowledge, "
"answe... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-8 | "\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livel... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-9 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto liv... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-10 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto liv... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-11 | 'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvoc... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-12 | 'score': '100'},
{'answer': " The president said that Justice Breyer is a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that since she's been nominated, she's received a broad range of support from the Fraterna... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
52e143e51b52-13 | input_variables=["context", "question"],
output_parser=output_parser,
)
chain = load_qa_chain(OpenAI(temperature=0), chain_type="map_rerank", return_intermediate_steps=True, prompt=PROMPT)
query = "What did the president say about Justice Breyer"
chain({"input_documents": docs, "question": query}, return_only_outpu... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/question_answering.html |
a4db2cc4fcc2-0 | .ipynb
.pdf
Summarization
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
Summarization#
This notebook walks through how to use LangChain for summarization over a list of documents. It covers three different chain types: stuff, map_reduce, and refine. For a more in depth explana... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-1 | chain.run(docs)
' In response to Russian aggression in Ukraine, the United States and its allies are taking action to hold Putin accountable, including economic sanctions, asset seizures, and military assistance. The US is also providing economic and humanitarian aid to Ukraine, and has passed the American Rescue Plan ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-2 | chain.run(docs)
"\n\nIn questa serata, il Presidente degli Stati Uniti ha annunciato una serie di misure per affrontare la crisi in Ucraina, causata dall'aggressione di Putin. Ha anche annunciato l'invio di aiuti economici, militari e umanitari all'Ucraina. Ha anche annunciato che gli Stati Uniti e i loro alleati stann... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-3 | chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True)
chain({"input_documents": docs}, return_only_outputs=True)
{'map_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sancti... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-4 | prompt_template = """Write a concise summary of the following:
{text}
CONCISE SUMMARY IN ITALIAN:"""
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-5 | "\n\nStiamo unendo le nostre forze con quelle dei nostri alleati europei per sequestrare yacht, appartamenti di lusso e jet privati di Putin. Abbiamo chiuso lo spazio aereo americano ai voli russi e stiamo fornendo più di un miliardo di dollari in assistenza all'Ucraina. Abbiamo anche mobilitato le nostre forze terrest... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-6 | "\n\nIl Presidente Biden ha lottato per passare l'American Rescue Plan per aiutare le persone che soffrivano a causa della pandemia. Il piano ha fornito sollievo economico immediato a milioni di americani, ha aiutato a mettere cibo sulla loro tavola, a mantenere un tetto sopra le loro teste e a ridurre il costo dell'as... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-7 | The refine Chain#
This sections shows results of using the refine Chain to do summarization.
chain = load_summarize_chain(llm, chain_type="refine")
chain.run(docs)
"\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Put... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-8 | chain({"input_documents": docs}, return_only_outputs=True)
{'refine_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-9 | "\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains. We are ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-10 | 'output_text': "\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-11 | "------------\n"
"{text}\n"
"------------\n"
"Given the new context, refine the original summary in Italian"
"If the context isn't useful, return the original summary."
)
refine_prompt = PromptTemplate(
input_variables=["existing_answer", "text"],
template=refine_template,
)
chain = load_summari... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-12 | "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-13 | "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
a4db2cc4fcc2-14 | 'output_text': "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagli... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/summarize.html |
3e9820eff9cd-0 | .ipynb
.pdf
Vector DB Question/Answering
Contents
Chain Type
Custom Prompts
Return Source Documents
Vector DB Question/Answering#
This example showcases question answering over a vector database.
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_spl... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-1 | There are two ways to load different chain types. First, you can specify the chain type argument in the from_chain_type method. This allows you to pass in the name of the chain type you want to use. For example, in the below we change the chain type to map_reduce.
qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_typ... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-2 | query = "What did the president say about Ketanji Brown Jackson"
qa.run(query)
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also s... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-3 | query = "What did the president say about Ketanji Brown Jackson"
qa.run(query)
" Il Presidente ha detto che Ketanji Brown Jackson è uno dei pensatori legali più importanti del nostro Paese, che continuerà l'eccellente eredità di giustizia Breyer. È un ex principale litigante in pratica privata, un ex difensore federale... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-4 | result["source_documents"]
[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 a... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-5 | 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://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-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... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
3e9820eff9cd-7 | Document(page_content='As I’ve told Xi Jinping, it is never a good bet to bet against the American people. \n\nWe’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America. \n\nAnd we’ll do it all to withstand the devastating effects of the climate crisis and pr... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_qa.html |
c04f843b7992-0 | .ipynb
.pdf
Vector DB Text Generation
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
Vector DB Text Generation#
This notebook walks through how to use LangChain for text generation over a vector index. This is useful if we want to generate text that is able to draw from a lar... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
c04f843b7992-1 | relative_path = markdown_file.relative_to(repo_path)
github_url = f"https://github.com/{repo_owner}/{repo_name}/blob/{git_sha}/{relative_path}"
yield Document(page_content=f.read(), metadata={"source": github_url})
sources = get_github_docs("yirenlu92", "deno-manual-forked")
source_chunk... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
c04f843b7992-2 | chain = LLMChain(llm=llm, prompt=PROMPT)
Generate Text#
Finally, we write a function to apply our inputs to the chain. The function takes an input parameter topic. We find the documents in the vector index that correspond to that topic, and use them as additional context in our simple LLM chain.
def generate_blog_post(... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
c04f843b7992-3 | [{'text': '\n\nEnvironment variables are a great way to store and access sensitive information in your Deno applications. Deno offers built-in support for environment variables with `Deno.env`, and you can also use a `.env` file to store and access environment variables.\n\nUsing `Deno.env` is simple. It has getter and... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
c04f843b7992-4 | into the code. This makes it easier to change settings without having to modify the code.\n\nIn Deno, environment variables can be set in a few different ways. The most common way is to use the `VAR=value` syntax. This will set the environment variable `VAR` to the value `value`. This can be used to set any number of e... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
c04f843b7992-5 | to hard-code it into their applications. In Deno, you can access environment variables using the `Deno.env.get()` function.\n\nFor example, if you wanted to access the `HOME` environment variable, you could do so like this:\n\n```js\n// env.js\nDeno.env.get("HOME");\n```\n\nWhen running this code, you\'ll need to grant... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
c04f843b7992-6 | variables are an important part of any programming language, and Deno is no exception. Deno is a secure JavaScript and TypeScript runtime built on the V8 JavaScript engine, and it recently added support for environment variables. This feature was added in Deno version 1.6.0, and it is now available for use in Deno appl... | https://langchain.readthedocs.io/en/latest/modules/indexes/chain_examples/vector_db_text_generation.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.