id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
aba60852a6cb-3 | prompt = PromptTemplate(template="{text}", input_variables=["text"])
llm_chain = LLMChain(llm=OpenAI(temperature=0, model_name="text-davinci-002"), prompt=prompt)
text = """We are playing a game of repeat after me.
Person 1: Hi
Person 2: Hi
Person 1: How's your day
Person 2: How's your day
Person 1: I will kill you
Per... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/moderation.html |
aba60852a6cb-4 | chain(inputs, return_only_outputs=True)
{'sanitized_text': "Text was found that violates OpenAI's content policy."}
previous
LLMSummarizationCheckerChain
next
Router Chains: Selecting from multiple prompts with MultiPromptChain
Contents
How to use the moderation chain
How to append a Moderation chain to an LLMChain... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/moderation.html |
87e325338ccb-0 | .ipynb
.pdf
LLMCheckerChain
LLMCheckerChain#
This notebook showcases how to use LLMCheckerChain.
from langchain.chains import LLMCheckerChain
from langchain.llms import OpenAI
llm = OpenAI(temperature=0.7)
text = "What type of mammal lays the biggest eggs?"
checker_chain = LLMCheckerChain.from_llm(llm, verbose=True)
ch... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_checker.html |
9882cec73c8d-0 | .ipynb
.pdf
BashChain
Contents
Customize Prompt
Persistent Terminal
BashChain#
This notebook showcases using LLMs and a bash process to perform simple filesystem commands.
from langchain.chains import LLMBashChain
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
text = "Please write a bash script that pr... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_bash.html |
9882cec73c8d-1 | Do not use 'echo' when writing the script.
That is the format. Begin!
Question: {question}"""
PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE, output_parser=BashOutputParser())
bash_chain = LLMBashChain.from_llm(llm, prompt=PROMPT, verbose=True)
text = "Please write a bash script that pr... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_bash.html |
9882cec73c8d-2 | llm_requests.ipynb sqlite.ipynb
> Finished chain.
'api.ipynb\t\t\tllm_summarization_checker.ipynb\r\nconstitutional_chain.ipynb\tmoderation.ipynb\r\nllm_bash.ipynb\t\t\topenai_openapi.yaml\r\nllm_checker.ipynb\t\topenapi.ipynb\r\nllm_math.ipynb\t\t\tpal.ipynb\r\nllm_requests.ipynb\t\tsqlite.ipynb'
# Run the same comma... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_bash.html |
f25932d7dc08-0 | .ipynb
.pdf
LLMSummarizationCheckerChain
LLMSummarizationCheckerChain#
This notebook shows some examples of LLMSummarizationCheckerChain in use with different types of texts. It has a few distinct differences from the LLMCheckerChain, in that it doesn’t have any assumptions to the format of the input text (or summary)... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-1 | These discoveries can spark a child's imagination about the infinite wonders of the universe."""
checker_chain.run(text)
> Entering new LLMSummarizationCheckerChain chain...
> Entering new SequentialChain chain...
> Entering new LLMChain chain...
Prompt after formatting:
Given some text, extract a list of facts from th... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-2 | • These distant worlds are called "exoplanets."
"""
For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".
If the fact is false, explain why.
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatti... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-3 | """
Using these checked assertions, rewrite the original summary to be completely true.
The output should have the same structure and formatting as the original summary.
Summary:
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
Below are some assertions that have been fact checked and are lab... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-4 | • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas.
• The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion yea... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-5 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.
Here is a bullet point list of facts:
"""
• The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "gre... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-6 | • Exoplanets were first discovered in 1992. - True
• The JWST has allowed us to see exoplanets in greater detail. - Undetermined. The JWST has not yet been launched, so it is not yet known how much detail it will be able to provide.
"""
Original Summary:
"""
Your 9-year old might like these recent discoveries made by ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-7 | Result: False
===
Checked Assertions: """
- The sky is blue: True
- Water is wet: True
- The sun is a star: True
"""
Result: True
===
Checked Assertions: """
- The sky is blue - True
- Water is made of lava- False
- The sun is a star - True
"""
Result: False
===
Checked Assertions:"""
• The James Webb Space Telescope (... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-8 | • Exoplanets, which are planets outside of our own solar system, were first discovered in 1992. The JWST will allow us to see them in greater detail when it is launched in 2023.
These discoveries can spark a child's imagination about the infinite wonders of the universe.
> Finished chain.
'Your 9-year old might like th... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-9 | text = "The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. It is the smalle... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-10 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.
Here is a bullet point list of facts:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean located between Icel... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-11 | - It has an area of 465,000 square miles. True
- It is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean.
- It is the smallest of the five oceans. False - The Greenland Sea is no... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-12 | Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: Tr... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-13 | """
Result:
> Finished chain.
> Finished chain.
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-14 | - It has an area of 465,000 square miles.
- It is an arm of the Arctic Ocean.
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs.
- It is named after the island of Greenland.
- It is the Arctic Ocean's main outlet to the Atlantic.
- It is often frozen over so navigati... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-15 | """
Original Summary:
"""
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glacier... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-16 | - It has an area of 465,000 square miles. True
- It is an arm of the Arctic Ocean. True
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True
- It is named after the island of Greenland. False - It is named after the country of Greenland.
- It is the Arctic Ocean's... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-17 | Format your output as a bulleted list.
Text:
"""
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-18 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction.
Checked Assertions:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean loca... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-19 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-20 | """
Result:
> Finished chain.
> Finished chain.
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is covered almost entirely by water, some of which is frozen in the form of glaciers and iceber... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-21 | Format your output as a bulleted list.
Text:
"""
Mammals can lay eggs, birds can lay eggs, therefore birds are mammals.
"""
Facts:
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important s... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-22 | Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: Tr... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-23 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.
Here is a bullet point list of facts:
"""
- Birds and mammals are both capable of laying eggs.
- Birds are not mammals.
- Bir... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
f25932d7dc08-24 | Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: True
"""
Result: False
===
Checked Assertions: """
- The sky is blue: True
- Water is wet: True
- The sun is a star: True
"""
Result: True
===
Checked Assertions: """
- The sky is blue - True
... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/llm_summarization_checker.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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.... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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 = (
... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
78382f0bee9e-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.', '... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/qa_with_sources.html |
e94bb72b09ef-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/analyze_document.html |
e94bb72b09ef-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
Transformat... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/analyze_document.html |
d4728bae3bf0-0 | .ipynb
.pdf
Retrieval Question Answering with Sources
Contents
Chain Type
Retrieval Question Answering with Sources#
This notebook goes over how to do question-answering with sources over an Index. It does this by using the RetrievalQAWithSourcesChain, which does the lookup of the documents from an Index.
from langch... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa_with_sources.html |
d4728bae3bf0-1 | 'sources': '31-pl'}
Chain Type#
You can easily specify different chain types to load and use in the RetrievalQAWithSourcesChain 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_ch... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa_with_sources.html |
d4728bae3bf0-2 | {'answer': ' The president honored Justice Breyer for his service and mentioned his legacy of excellence.\n',
'sources': '31-pl'}
previous
Retrieval Question/Answering
next
Vector DB Text Generation
Contents
Chain Type
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa_with_sources.html |
4eff073d599b-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/graph_qa.html |
4eff073d599b-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/graph_qa.html |
4eff073d599b-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/graph_qa.html |
450c42119b51-0 | .ipynb
.pdf
Summarization
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The custom MapReduceChain
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. F... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-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=... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-7 | The custom MapReduceChain#
Multi input prompt
You can also use prompt with multi input. In this example, we will use a MapReduce chain to answer specifc question about our code.
from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain
from langchain.chains.combine_documents.stuff import StuffDo... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-8 | )
code = """
def bubblesort(list):
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
return list
##
def insertion_sort(InputList):
for i in range(1, len(I... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-9 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-10 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-11 | "\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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-12 | '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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-13 | "(only if needed) with some more context below.\n"
"------------\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"... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-14 | "\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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-15 | "\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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
450c42119b51-16 | '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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/summarize.html |
39c7810d9dcc-0 | .ipynb
.pdf
Retrieval Question/Answering
Contents
Chain Type
Custom Prompts
Return Source Documents
Retrieval Question/Answering#
This example showcases question answering over an index.
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter imp... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
39c7810d9dcc-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 = RetrievalQA.from_chain_type(llm=OpenAI(), chain_ty... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
39c7810d9dcc-2 | 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 said that she is a consensus builder and has received a broad rang... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
39c7810d9dcc-3 | qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever(), return_source_documents=True)
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"query": query})
result["result"]
" The president said that Ketanji Brown Jackson is one of the nation's top ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
39c7810d9dcc-4 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
39c7810d9dcc-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
39c7810d9dcc-6 | 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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_qa.html |
7a2fb4dcfa86-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/hyde.html |
7a2fb4dcfa86-1 | 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 prompt to generate text more similar to that.
In the example b... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/hyde.html |
7a2fb4dcfa86-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/hyde.html |
19314a402109-0 | .ipynb
.pdf
Chat Over Documents with Chat History
Contents
Pass in chat history
Using a different model for condensing the question
Return Source Documents
ConversationalRetrievalChain with search_distance
ConversationalRetrievalChain with map_reduce
ConversationalRetrievalChain with Question Answering with sources
C... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-1 | Using embedded DuckDB without persistence: data will be transient
We can now create a memory object, which is neccessary to track the inputs/outputs and hold a conversation.
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
We now in... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-2 | 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 public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad r... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-3 | )
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
chat_history = [(query, result["answer"])]
query = "Did he mention who she suceeded"
result = qa({"question": query, "chat_history": chat_history})
Return Source Documents#... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-4 | ConversationalRetrievalChain with search_distance#
If you are using a vector store that supports filtering by search distance, you can add a threshold value parameter.
vectordbkwargs = {"search_distance": 0.9}
qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever(), return_source_do... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-5 | 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 public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fra... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-6 | from langchain.chains.llm import LLMChain
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT, QA_PROMPT
from langchain.chains.question_answering import load_qa_chain
# Construct a ConversationalRetrievalC... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
19314a402109-7 | get_chat_history Function#
You can also specify a get_chat_history function, which can be used to format the chat_history string.
def get_chat_history(inputs) -> str:
res = []
for human, ai in inputs:
res.append(f"Human:{human}\nAI:{ai}")
return "\n".join(res)
qa = ConversationalRetrievalChain.from_... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/chat_vector_db.html |
d5e3c6f11c46-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
d5e3c6f11c46-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
d5e3c6f11c46-2 | 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(topic):
docs = search_index.similarit... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
d5e3c6f11c46-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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
d5e3c6f11c46-4 | will set the environment variable `VAR` to `hello` before running the command. We can then access this variable in our code using the `Deno.env.get()` function. For example, if we ran the following command:\n\n```\nVAR=hello && deno eval "console.log(\'Deno: \' + Deno.env.get(\'VAR'}, {'text': '\n\nEnvironment variable... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
d5e3c6f11c46-5 | added in Deno version 1.6.0, and it is now available for use in Deno applications.\n\nEnvironment variables are used to store information that can be used by programs. They are typically used to store configuration information, such as the location of a database or the name of a user. In Deno, environment variables are... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
d5e3c6f11c46-6 | previous
Retrieval Question Answering with Sources
next
API Chains
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/vector_db_text_generation.html |
b359e2c72fec-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, ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-1 | 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_chain(OpenAI(temperature=0), chain_type="stuff")
query = "What did the president say about Justice Breyer"
chain.run(input_documents=docs, question=query)
' The pre... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.