id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 117 |
|---|---|---|
a24347f528db-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_... | https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html |
e3500f3c9d0d-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://python.langchain.com/en/latest/modules/chains/index_examples/hyde.html |
e3500f3c9d0d-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/hyde.html |
e3500f3c9d0d-2 | print(docs[0].page_content)
In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections.
We cannot let this happen.
Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act s... | https://python.langchain.com/en/latest/modules/chains/index_examples/hyde.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
cf7c6f791025-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://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
bcec9d79ee93-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://python.langchain.com/en/latest/modules/chains/index_examples/analyze_document.html |
bcec9d79ee93-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/analyze_document.html |
c709884f50ec-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
c709884f50ec-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
c709884f50ec-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
c709884f50ec-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 ... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
c709884f50ec-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
c709884f50ec-5 | Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
c709884f50ec-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 ... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
a4bd8a7764e1-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa_with_sources.html |
a4bd8a7764e1-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa_with_sources.html |
a4bd8a7764e1-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 02, ... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa_with_sources.html |
f125eadb6076-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://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-2 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha ricevuto una vasta gamma di supporto.'}
The map_reduce Chain#
This sections shows results of using the map_reduce Chain to do ques... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-3 | ' None',
' None'],
'output_text': ' The president said that Justice Breyer is an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court, and thanked him for his service.'}
Custom Prompts
You can also use your own prompts with this chain. In this example, we will respond in Ital... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-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://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-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 support of the Equalit... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-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 support of the Equality Act and his commitment to protecting the rights of LGBTQ+ Americans. He also praised Justice... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-7 | 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, "
"answer the question: {question}\nYour answer should be in Italian.\n"
)
i... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-8 | "\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche. Ha anche sottol... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-9 | 'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-10 | {'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, we will respond ... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
f125eadb6076-11 | 'score': '100'},
{'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.',
'score': '100'},
{'answer': ' Non so.', 'score': '0'},
{'answer': ' Non so.', 'score': '0'}],
'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese.'}
previous
Question ... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
8045a3b8d3d9-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://python.langchain.com/en/latest/modules/chains/index_examples/graph_qa.html |
8045a3b8d3d9-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://python.langchain.com/en/latest/modules/chains/index_examples/graph_qa.html |
8045a3b8d3d9-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/modules/chains/index_examples/graph_qa.html |
592858c395a1-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://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
592858c395a1-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://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
592858c395a1-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
592858c395a1-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://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
592858c395a1-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
592858c395a1-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... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
592858c395a1-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 02, 2023. | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
9f5a70333887-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),... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
9f5a70333887-1 | llm_chain.generate(input_list)
LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
9f5a70333887-2 | template = """List all the colors in a rainbow"""
prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)
llm_chain = LLMChain(prompt=prompt, llm=llm)
llm_chain.predict()
'\n\nRed, orange, yellow, green, blue, indigo, violet'
With predict_and_parser:
llm_chain.predict_and_parse()
['R... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
38f0f3269226-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... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
38f0f3269226-1 | "best_of": 1,
"request_timeout": null,
"logit_bias": {},
"_type": "openai"
},
"output_key": "text",
"_type": "llm_chain"
}
Loading a chain from disk#
We can load a chain from disk by using the load_chain method.
from langchain.chains import load_chain
chain = load_chain("llm_chain.js... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
38f0f3269226-2 | "top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"n": 1,
"best_of": 1,
"request_timeout": null,
"logit_bias": {},
"_type": "openai"
}
config = {
"memory": None,
"verbose": True,
"prompt_path": "prompt.json",
"llm_path": "llm.json",
"output_key": "text",
"_ty... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
0605597c34c3-0 | .ipynb
.pdf
Async API for Chain
Async API for Chain#
LangChain provides async support for Chains by leveraging the asyncio library.
Async methods are currently supported in LLMChain (through arun, apredict, acall) and LLMMathChain (through arun and acall), ChatVectorDBChain, and QA chains. Async support for other chain... | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
0605597c34c3-1 | await generate_concurrently()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Concurrent executed in {elapsed:0.2f} seconds." + '\033[0m')
s = time.perf_counter()
generate_serially()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Serial executed in {elapsed:0.2f} seconds." + '\033[0m')
BrightSmile Toothpas... | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
d8ee421a14ff-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... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-1 | 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 = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
Play Synopsis:
{synopsis}
R... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-2 | The play follows the couple as they struggle to stay together and battle the forces that threaten to tear them apart. Despite the tragedy that awaits them, they remain devoted to one another and fight to keep their love alive. In the end, the couple must decide whether to take a chance on their future together or succu... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-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.
Sequential... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-4 | Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:"""
prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")
# This is the overall chain where we run these two chains in sequence.
... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-5 | '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... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-6 | '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... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-7 | from langchain.memory import SimpleMemory
llm = OpenAI(temperature=.7)
template = """You are a social media manager for a theater company. Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for tha... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
d8ee421a14ff-8 | 'location': 'Theater in the Park',
'social_post_text': "\nSpend your Christmas night with us at Theater in the Park and experience the heartbreaking story of love and loss that is 'A Walk on the Beach'. Set in Victorian England, this romantic tragedy follows the story of Frances and Edward, a young couple whose love i... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
866538c2f993-0 | .ipynb
.pdf
Creating a custom Chain
Creating a custom Chain#
To implement your own custom chain you can subclass Chain and implement the following methods:
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
fro... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
866538c2f993-1 | # Whenever you call a language model, or another chain, you should pass
# a callback manager to it. This allows the inner run to be tracked by
# any callbacks that are registered on the outer run.
# You can always obtain a callback manager for this by calling
# `run_manager.get_child()` ... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
866538c2f993-2 | callbacks=run_manager.get_child() if run_manager else None
)
# If you want to log something about this run, you can do so by calling
# methods on the `run_manager`, as shown below. This will trigger any
# callbacks that are registered for that event.
if run_manager:
a... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
da4b8d1af448-0 | .ipynb
.pdf
Transformation Chain
Transformation Chain#
This notebook showcases using a generic transformation chain.
As an example, we will create a dummy transformation that takes in a super long text, filters the text to only the first 3 paragraphs, and then passes that into an LLMChain to summarize those.
from langc... | https://python.langchain.com/en/latest/modules/chains/generic/transformation.html |
f2ff302427cb-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: ... | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
f2ff302427cb-1 | chain.run(query)
" The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, has received a broad range of support from the Fraternal Order of Police to former judges appointed by ... | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
abf6937563de-0 | .ipynb
.pdf
Router Chains
Contents
LLMRouterChain
EmbeddingRouterChain
Router Chains#
This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the next chain to use for a given input.
Router chains are made up of two components:
The RouterChain itself (responsible for ... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
abf6937563de-1 | "description": "Good for answering math questions",
"prompt_template": math_template
}
]
llm = OpenAI()
destination_chains = {}
for p_info in prompt_infos:
name = p_info["name"]
prompt_template = p_info["prompt_template"]
prompt = PromptTemplate(template=prompt_template, input_variables=["input... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
abf6937563de-2 | physics: {'input': 'What is black body radiation?'}
> Finished chain.
Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radi... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
abf6937563de-3 | ("math", ["for questions about math"]),
]
router_chain = EmbeddingRouterChain.from_names_and_descriptions(
names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"]
)
Using embedded DuckDB without persistence: data will be transient
chain = MultiPromptChain(router_chain=router_chain, destination_ch... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
bfcdf6d59365-0 | .rst
.pdf
How-To Guides
Contents
Types
Usage
How-To Guides#
Types#
The first set of examples all highlight different types of memory.
ConversationBufferMemory
ConversationBufferWindowMemory
Entity Memory
Conversation Knowledge Graph Memory
ConversationSummaryMemory
ConversationSummaryBufferMemory
ConversationTokenBuf... | https://python.langchain.com/en/latest/modules/memory/how_to_guides.html |
302dcc2ccaac-0 | .ipynb
.pdf
Getting Started
Contents
ChatMessageHistory
ConversationBufferMemory
Using in a chain
Saving Message History
Getting Started#
This notebook walks through how LangChain thinks about memory.
Memory involves keeping a concept of state around throughout a user’s interactions with an language model. A user’s i... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
302dcc2ccaac-1 | history.messages
[HumanMessage(content='hi!', additional_kwargs={}),
AIMessage(content='whats up?', additional_kwargs={})]
ConversationBufferMemory#
We now show how to use this simple concept in a chain. We first showcase ConversationBufferMemory which is just a wrapper around ChatMessageHistory that extracts the mess... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
302dcc2ccaac-2 | Current conversation:
Human: Hi there!
AI:
> Finished chain.
" Hi there! It's nice to meet you. How can I help you today?"
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation betw... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
302dcc2ccaac-3 | Human: Tell me about yourself.
AI:
> Finished chain.
" Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers."
Saving ... | https://python.langchain.com/en/latest/modules/memory/getting_started.html |
53e000fed432-0 | .ipynb
.pdf
How to add Memory to an LLMChain
How to add Memory to an LLMChain#
This notebook goes over how to use the Memory class with an LLMChain. For the purposes of this walkthrough, we will add the ConversationBufferMemory class, although this can be any memory class.
from langchain.memory import ConversationBuff... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html |
53e000fed432-1 | Human: Hi there my friend
AI: Hi there, how are you doing today?
Human: Not to bad - how are you?
Chatbot:
> Finished LLMChain chain.
" I'm doing great, thank you for asking!"
previous
VectorStore-Backed Memory
next
How to add memory to a Multi-Input Chain
By Harrison Chase
© Copyright 2023, Harrison Chase.... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html |
544b5e00c11a-0 | .ipynb
.pdf
How to customize conversational memory
Contents
AI Prefix
Human Prefix
How to customize conversational memory#
This notebook walks through a few ways to customize conversational memory.
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import Conversati... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
544b5e00c11a-1 | Current conversation:
Human: Hi there!
AI: Hi there! It's nice to meet you. How can I help you today?
Human: What's the weather?
AI:
> Finished ConversationChain chain.
' The current weather is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the next few days is sunny with temperatures in ... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
544b5e00c11a-2 | > 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:
... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
544b5e00c11a-3 | memory=ConversationBufferMemory(human_prefix="Friend")
)
conversation.predict(input="Hi there!")
> 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 do... | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html |
df8d26d5aa2f-0 | .ipynb
.pdf
Motörhead Memory (Managed)
Contents
Setup
Motörhead Memory (Managed)#
Motörhead is a memory server implemented in Rust. It automatically handles incremental summarization in the background and allows for stateless applications.
Setup#
See instructions at Motörhead for running the managed version of Motorh... | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory_managed.html |
df8d26d5aa2f-1 | You are a chatbot having a conversation with a human.
Human: hi im bob
AI: Hi Bob, nice to meet you! How are you doing today?
Human: whats my name?
AI:
> Finished chain.
' You said your name is Bob. Is that correct?'
llm_chain.run("whats for dinner?")
> Entering new LLMChain chain...
Prompt after formatting:
You are a... | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory_managed.html |
950be21a1aa1-0 | .ipynb
.pdf
How to use multiple memory classes in the same chain
How to use multiple memory classes in the same chain#
It is also possible to use multiple memory classes in the same chain. To combine multiple memory classes, we can initialize the CombinedMemory class, and then use that.
from langchain.llms import OpenA... | https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html |
950be21a1aa1-1 | Summary of conversation:
Current conversation:
Human: Hi!
AI:
> Finished chain.
' Hi there! How can I help you?'
conversation.run("Can you tell me a joke?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and prov... | https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html |
909c238cb09c-0 | .ipynb
.pdf
How to add memory to a Multi-Input Chain
How to add memory to a Multi-Input Chain#
Most memory objects assume a single input. In this notebook, we go over how to add memory to a chain that has multiple inputs. As an example of such a chain, we will add memory to a question/answering chain. This chain takes ... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
909c238cb09c-1 | {context}
{chat_history}
Human: {human_input}
Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input", "context"],
template=template
)
memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff... | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html |
288269394a4e-0 | .ipynb
.pdf
Zep Memory
Contents
REACT Agent Chat Message History Example
Initialize the Zep Chat Message History Class and initialize the Agent
Add some history data
Run the agent
Inspect the Zep memory
Vector search over the Zep memory
Zep Memory#
REACT Agent Chat Message History Example#
This notebook demonstrates ... | https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.