id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
5d97bfd0cb46-159
inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property input_keys: List[str] Input keys this chain expects. property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-160
property lc_serializable: bool Return whether or not the class is serializable. property output_keys: List[str] Output keys this chain expects. class langchain.chains.QAWithSourcesChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_documents_chain, question_key='question', input_docs_key='docs', answer_key='answer', sources_answer_key='sources', return_source_documents=False)[source] Bases: langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain Question answering with sources over documents. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – combine_documents_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) – question_key (str) – input_docs_key (str) – answer_key (str) – sources_answer_key (str) – return_source_documents (bool) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute combine_documents_chain: BaseCombineDocumentsChain [Required] Chain to use to combine documents.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-161
Chain to use to combine documents. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute return_source_documents: bool = False Return the source documents. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-162
use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict classmethod from_chain_type(llm, chain_type='stuff', chain_type_kwargs=None, **kwargs) Load chain from chain type. Parameters llm (langchain.base_language.BaseLanguageModel) – chain_type (str) – chain_type_kwargs (Optional[dict]) – kwargs (Any) – Return type langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-163
classmethod from_llm(llm, document_prompt=PromptTemplate(input_variables=['page_content', 'source'], output_parser=None, partial_variables={}, template='Content: {page_content}\nSource: {source}', template_format='f-string', validate_template=True), question_prompt=PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \nReturn any relevant text verbatim.\n{context}\nQuestion: {question}\nRelevant text, if any:', template_format='f-string', validate_template=True), combine_prompt=PromptTemplate(input_variables=['summaries', 'question'], output_parser=None, partial_variables={}, template='Given the following extracted parts of a long document and a question, create a final answer with references ("SOURCES"). \nIf you don\'t know the answer, just say that you don\'t know. Don\'t try to make up an answer.\nALWAYS return a "SOURCES" part in your answer.\n\nQUESTION: Which state/country\'s law governs the interpretation of the contract?\n=========\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in  relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an  injunction or other relief to protect its Intellectual Property Rights.\nSource: 28-pl\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)  right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation  in force of the remainder of the term (if
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-164
of this Agreement shall not affect the continuation  in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any  kind between the parties.\n\n11.9 No Third-Party Beneficiaries.\nSource: 30-pl\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as  defined in Clause 8.5) or that such a violation is reasonably likely to occur,\nSource: 4-pl\n=========\nFINAL ANSWER: This Agreement is governed by English law.\nSOURCES: 28-pl\n\nQUESTION: What did the president say about Michael Jackson?\n=========\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.  \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-165
their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\nSource: 0-pl\nContent: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.  \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.  \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\nSource: 24-pl\nContent: And a proud Ukrainian people, who have known 30 years  of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.  \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-166
you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions  is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.  \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.  \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay.\nSource: 5-pl\nContent: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more.  \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-167
\n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation.\nSource: 34-pl\n=========\nFINAL ANSWER: The president did not mention Michael Jackson.\nSOURCES:\n\nQUESTION: {question}\n=========\n{summaries}\n=========\nFINAL ANSWER:', template_format='f-string', validate_template=True), **kwargs)
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-168
Construct the chain from an LLM. Parameters llm (langchain.base_language.BaseLanguageModel) – document_prompt (langchain.prompts.base.BasePromptTemplate) – question_prompt (langchain.prompts.base.BasePromptTemplate) – combine_prompt (langchain.prompts.base.BasePromptTemplate) – kwargs (Any) – Return type langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-169
Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.RetrievalQA(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_documents_chain, input_key='query', output_key='result', return_source_documents=False, retriever)[source] Bases: langchain.chains.retrieval_qa.base.BaseRetrievalQA Chain for question-answering against an index. Example from langchain.llms import OpenAI from langchain.chains import RetrievalQA from langchain.faiss import FAISS from langchain.vectorstores.base import VectorStoreRetriever retriever = VectorStoreRetriever(vectorstore=FAISS(...)) retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever) Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-170
verbose (bool) – tags (Optional[List[str]]) – combine_documents_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) – input_key (str) – output_key (str) – return_source_documents (bool) – retriever (langchain.schema.BaseRetriever) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute combine_documents_chain: BaseCombineDocumentsChain [Required] Chain to use to combine the documents. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute retriever: BaseRetriever [Required] attribute return_source_documents: bool = False Return the source documents. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional]
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-171
attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-172
tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict classmethod from_chain_type(llm, chain_type='stuff', chain_type_kwargs=None, **kwargs) Load chain from chain type. Parameters llm (langchain.base_language.BaseLanguageModel) – chain_type (str) – chain_type_kwargs (Optional[dict]) – kwargs (Any) – Return type langchain.chains.retrieval_qa.base.BaseRetrievalQA classmethod from_llm(llm, prompt=None, **kwargs) Initialize from LLM. Parameters llm (langchain.base_language.BaseLanguageModel) – prompt (Optional[langchain.prompts.prompt.PromptTemplate]) – kwargs (Any) – Return type langchain.chains.retrieval_qa.base.BaseRetrievalQA prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-173
tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.RetrievalQAWithSourcesChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_documents_chain, question_key='question', input_docs_key='docs', answer_key='answer', sources_answer_key='sources', return_source_documents=False, retriever, reduce_k_below_max_tokens=False, max_tokens_limit=3375)[source] Bases: langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain Question-answering with sources over an index. Parameters memory (Optional[langchain.schema.BaseMemory]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-174
Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – combine_documents_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) – question_key (str) – input_docs_key (str) – answer_key (str) – sources_answer_key (str) – return_source_documents (bool) – retriever (langchain.schema.BaseRetriever) – reduce_k_below_max_tokens (bool) – max_tokens_limit (int) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute combine_documents_chain: BaseCombineDocumentsChain [Required] Chain to use to combine documents. attribute max_tokens_limit: int = 3375 Restrict the docs to return from store based on tokens, enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-175
and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute reduce_k_below_max_tokens: bool = False Reduce the number of results to return from store based on tokens limit attribute retriever: langchain.schema.BaseRetriever [Required] Index to connect to. attribute return_source_documents: bool = False Return the source documents. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-176
use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict classmethod from_chain_type(llm, chain_type='stuff', chain_type_kwargs=None, **kwargs) Load chain from chain type. Parameters llm (langchain.base_language.BaseLanguageModel) – chain_type (str) – chain_type_kwargs (Optional[dict]) – kwargs (Any) – Return type langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-177
classmethod from_llm(llm, document_prompt=PromptTemplate(input_variables=['page_content', 'source'], output_parser=None, partial_variables={}, template='Content: {page_content}\nSource: {source}', template_format='f-string', validate_template=True), question_prompt=PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \nReturn any relevant text verbatim.\n{context}\nQuestion: {question}\nRelevant text, if any:', template_format='f-string', validate_template=True), combine_prompt=PromptTemplate(input_variables=['summaries', 'question'], output_parser=None, partial_variables={}, template='Given the following extracted parts of a long document and a question, create a final answer with references ("SOURCES"). \nIf you don\'t know the answer, just say that you don\'t know. Don\'t try to make up an answer.\nALWAYS return a "SOURCES" part in your answer.\n\nQUESTION: Which state/country\'s law governs the interpretation of the contract?\n=========\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in  relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an  injunction or other relief to protect its Intellectual Property Rights.\nSource: 28-pl\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)  right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation  in force of the remainder of the term (if
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-178
of this Agreement shall not affect the continuation  in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any  kind between the parties.\n\n11.9 No Third-Party Beneficiaries.\nSource: 30-pl\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as  defined in Clause 8.5) or that such a violation is reasonably likely to occur,\nSource: 4-pl\n=========\nFINAL ANSWER: This Agreement is governed by English law.\nSOURCES: 28-pl\n\nQUESTION: What did the president say about Michael Jackson?\n=========\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.  \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-179
their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\nSource: 0-pl\nContent: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.  \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.  \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\nSource: 24-pl\nContent: And a proud Ukrainian people, who have known 30 years  of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.  \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-180
you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions  is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.  \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.  \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay.\nSource: 5-pl\nContent: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more.  \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-181
\n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation.\nSource: 34-pl\n=========\nFINAL ANSWER: The president did not mention Michael Jackson.\nSOURCES:\n\nQUESTION: {question}\n=========\n{summaries}\n=========\nFINAL ANSWER:', template_format='f-string', validate_template=True), **kwargs)
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-182
Construct the chain from an LLM. Parameters llm (langchain.base_language.BaseLanguageModel) – document_prompt (langchain.prompts.base.BasePromptTemplate) – question_prompt (langchain.prompts.base.BasePromptTemplate) – combine_prompt (langchain.prompts.base.BasePromptTemplate) – kwargs (Any) – Return type langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-183
Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.RouterChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None)[source] Bases: langchain.chains.base.Chain, abc.ABC Chain that outputs the name of a destination chain and the inputs to it. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute memory: Optional[BaseMemory] = None
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-184
for full details. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-185
to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async aroute(inputs, callbacks=None)[source] Parameters inputs (Dict[str, Any]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type langchain.chains.router.base.Route async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] route(inputs, callbacks=None)[source] Parameters inputs (Dict[str, Any]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-186
Parameters inputs (Dict[str, Any]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type langchain.chains.router.base.Route run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented abstract property input_keys: List[str] Input keys this chain expects. property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-187
property lc_serializable: bool Return whether or not the class is serializable. property output_keys: List[str] Output keys this chain expects. class langchain.chains.SQLDatabaseChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, llm_chain, llm=None, database, prompt=None, top_k=5, input_key='query', output_key='result', return_intermediate_steps=False, return_direct=False, use_query_checker=False, query_checker_prompt=None)[source] Bases: langchain.chains.base.Chain Chain for interacting with SQL Database. Example from langchain import SQLDatabaseChain, OpenAI, SQLDatabase db = SQLDatabase(...) db_chain = SQLDatabaseChain.from_llm(OpenAI(), db) Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – llm_chain (langchain.chains.llm.LLMChain) – llm (Optional[langchain.base_language.BaseLanguageModel]) – database (langchain.sql_database.SQLDatabase) – prompt (Optional[langchain.prompts.base.BasePromptTemplate]) – top_k (int) – input_key (str) – output_key (str) – return_intermediate_steps (bool) – return_direct (bool) – use_query_checker (bool) – query_checker_prompt (Optional[langchain.prompts.base.BasePromptTemplate]) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-188
Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute database: SQLDatabase [Required] SQL Database to connect to. attribute llm: Optional[BaseLanguageModel] = None [Deprecated] LLM wrapper to use. attribute llm_chain: LLMChain [Required] attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute prompt: Optional[BasePromptTemplate] = None [Deprecated] Prompt to use to translate natural language to SQL. attribute query_checker_prompt: Optional[BasePromptTemplate] = None The prompt template that should be used by the query checker attribute return_direct: bool = False Whether or not to return the result of querying the SQL table directly. attribute return_intermediate_steps: bool = False Whether or not to return the intermediate steps along with the final answer. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain,
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-189
These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute top_k: int = 5 Number of results to return from the query attribute use_query_checker: bool = False Whether or not the query checker tool should be used to attempt to fix the initial SQL from the LLM. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-190
Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict classmethod from_llm(llm, db, prompt=None, **kwargs)[source] Parameters llm (langchain.base_language.BaseLanguageModel) – db (langchain.sql_database.SQLDatabase) – prompt (Optional[langchain.prompts.base.BasePromptTemplate]) – kwargs (Any) – Return type langchain.chains.sql_database.base.SQLDatabaseChain prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-191
Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.SQLDatabaseSequentialChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, decider_chain, sql_chain, input_key='query', output_key='result', return_intermediate_steps=False)[source] Bases: langchain.chains.base.Chain Chain for querying SQL database that is a sequential chain. The chain is as follows:
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-192
Chain for querying SQL database that is a sequential chain. The chain is as follows: 1. Based on the query, determine which tables to use. 2. Based on those tables, call the normal SQL database chain. This is useful in cases where the number of tables in the database is large. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – decider_chain (langchain.chains.llm.LLMChain) – sql_chain (langchain.chains.sql_database.base.SQLDatabaseChain) – input_key (str) – output_key (str) – return_intermediate_steps (bool) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute decider_chain: LLMChain [Required] attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-193
There are many different types of memory - please see memory docs for the full catalog. attribute return_intermediate_steps: bool = False attribute sql_chain: SQLDatabaseChain [Required] attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-194
Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-195
Parameters kwargs (Any) – Return type Dict classmethod from_llm(llm, database, query_prompt=PromptTemplate(input_variables=['input', 'table_info', 'dialect', 'top_k'], output_parser=None, partial_variables={}, template='Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database.\n\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\n\nPay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n\nUse the following format:\n\nQuestion: Question here\nSQLQuery: SQL Query to run\nSQLResult: Result of the SQLQuery\nAnswer: Final answer here\n\nOnly use the following tables:\n{table_info}\n\nQuestion: {input}', template_format='f-string', validate_template=True), decider_prompt=PromptTemplate(input_variables=['query', 'table_names'], output_parser=CommaSeparatedListOutputParser(), partial_variables={}, template='Given the below input question and list of potential tables, output a comma separated list of the table names that may be necessary to answer this question.\n\nQuestion: {query}\n\nTable Names: {table_names}\n\nRelevant Table Names:', template_format='f-string', validate_template=True), **kwargs)[source] Load the necessary chains. Parameters llm (langchain.base_language.BaseLanguageModel) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-196
Parameters llm (langchain.base_language.BaseLanguageModel) – database (langchain.sql_database.SQLDatabase) – query_prompt (langchain.prompts.base.BasePromptTemplate) – decider_prompt (langchain.prompts.base.BasePromptTemplate) – kwargs (Any) – Return type langchain.chains.sql_database.base.SQLDatabaseSequentialChain prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-197
langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.SequentialChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, chains, input_variables, output_variables, return_all=False)[source] Bases: langchain.chains.base.Chain Chain where the outputs of one chain feed directly into next. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – chains (List[langchain.chains.base.Chain]) – input_variables (List[str]) – output_variables (List[str]) – return_all (bool) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain,
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-198
Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute chains: List[langchain.chains.base.Chain] [Required] attribute input_variables: List[str] [Required] attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute return_all: bool = False attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-199
response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-200
inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-201
property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.SimpleSequentialChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, chains, strip_outputs=False, input_key='input', output_key='output')[source] Bases: langchain.chains.base.Chain Simple chain where the outputs of one step feed directly into next. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – chains (List[langchain.chains.base.Chain]) – strip_outputs (bool) – input_key (str) – output_key (str) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute chains: List[langchain.chains.base.Chain] [Required] attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-202
them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute strip_outputs: bool = False attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-203
Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-204
Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.TransformChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_variables, output_variables, transform)[source] Bases: langchain.chains.base.Chain Chain transform chain output. Example from langchain import TransformChain transform_chain = TransformChain(input_variables=["text"], output_variables["entities"], transform=func()) Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-205
verbose (bool) – tags (Optional[List[str]]) – input_variables (List[str]) – output_variables (List[str]) – transform (Callable[[Dict[str, str]], Dict[str, str]]) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute input_variables: List[str] [Required] attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute output_variables: List[str] [Required] attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute transform: Callable[[Dict[str, str]], Dict[str, str]] [Required] attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-206
will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs)
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-207
kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-208
property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.VectorDBQA(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_documents_chain, input_key='query', output_key='result', return_source_documents=False, vectorstore, k=4, search_type='similarity', search_kwargs=None)[source] Bases: langchain.chains.retrieval_qa.base.BaseRetrievalQA Chain for question-answering against a vector database. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – combine_documents_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) – input_key (str) – output_key (str) – return_source_documents (bool) – vectorstore (langchain.vectorstores.base.VectorStore) – k (int) – search_type (str) – search_kwargs (Dict[str, Any]) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-209
Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute combine_documents_chain: BaseCombineDocumentsChain [Required] Chain to use to combine the documents. attribute k: int = 4 Number of documents to query for. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute return_source_documents: bool = False Return the source documents. attribute search_kwargs: Dict[str, Any] [Optional] Extra search args. attribute search_type: str = 'similarity' Search type to use over vectorstore. similarity or mmr. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute vectorstore: VectorStore [Required] Vector Database to connect to. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-210
Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-211
tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict classmethod from_chain_type(llm, chain_type='stuff', chain_type_kwargs=None, **kwargs) Load chain from chain type. Parameters llm (langchain.base_language.BaseLanguageModel) – chain_type (str) – chain_type_kwargs (Optional[dict]) – kwargs (Any) – Return type langchain.chains.retrieval_qa.base.BaseRetrievalQA classmethod from_llm(llm, prompt=None, **kwargs) Initialize from LLM. Parameters llm (langchain.base_language.BaseLanguageModel) – prompt (Optional[langchain.prompts.prompt.PromptTemplate]) – kwargs (Any) – Return type langchain.chains.retrieval_qa.base.BaseRetrievalQA prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-212
tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.VectorDBQAWithSourcesChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_documents_chain, question_key='question', input_docs_key='docs', answer_key='answer', sources_answer_key='sources', return_source_documents=False, vectorstore, k=4, reduce_k_below_max_tokens=False, max_tokens_limit=3375, search_kwargs=None)[source] Bases: langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain Question-answering with sources over a vector database. Parameters
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-213
Question-answering with sources over a vector database. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – combine_documents_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) – question_key (str) – input_docs_key (str) – answer_key (str) – sources_answer_key (str) – return_source_documents (bool) – vectorstore (langchain.vectorstores.base.VectorStore) – k (int) – reduce_k_below_max_tokens (bool) – max_tokens_limit (int) – search_kwargs (Dict[str, Any]) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute combine_documents_chain: BaseCombineDocumentsChain [Required] Chain to use to combine documents. attribute k: int = 4 Number of results to return from store attribute max_tokens_limit: int = 3375 Restrict the docs to return from store based on tokens, enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-214
enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute reduce_k_below_max_tokens: bool = False Reduce the number of results to return from store based on tokens limit attribute return_source_documents: bool = False Return the source documents. attribute search_kwargs: Dict[str, Any] [Optional] Extra search args. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute vectorstore: langchain.vectorstores.base.VectorStore [Required] Vector Database to connect to. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-215
return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict classmethod from_chain_type(llm, chain_type='stuff', chain_type_kwargs=None, **kwargs) Load chain from chain type. Parameters llm (langchain.base_language.BaseLanguageModel) – chain_type (str) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-216
chain_type (str) – chain_type_kwargs (Optional[dict]) – kwargs (Any) – Return type langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-217
classmethod from_llm(llm, document_prompt=PromptTemplate(input_variables=['page_content', 'source'], output_parser=None, partial_variables={}, template='Content: {page_content}\nSource: {source}', template_format='f-string', validate_template=True), question_prompt=PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template='Use the following portion of a long document to see if any of the text is relevant to answer the question. \nReturn any relevant text verbatim.\n{context}\nQuestion: {question}\nRelevant text, if any:', template_format='f-string', validate_template=True), combine_prompt=PromptTemplate(input_variables=['summaries', 'question'], output_parser=None, partial_variables={}, template='Given the following extracted parts of a long document and a question, create a final answer with references ("SOURCES"). \nIf you don\'t know the answer, just say that you don\'t know. Don\'t try to make up an answer.\nALWAYS return a "SOURCES" part in your answer.\n\nQUESTION: Which state/country\'s law governs the interpretation of the contract?\n=========\nContent: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in  relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an  injunction or other relief to protect its Intellectual Property Rights.\nSource: 28-pl\nContent: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other)  right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation  in force of the remainder of the term (if
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-218
of this Agreement shall not affect the continuation  in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any  kind between the parties.\n\n11.9 No Third-Party Beneficiaries.\nSource: 30-pl\nContent: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as  defined in Clause 8.5) or that such a violation is reasonably likely to occur,\nSource: 4-pl\n=========\nFINAL ANSWER: This Agreement is governed by English law.\nSOURCES: 28-pl\n\nQUESTION: What did the president say about Michael Jackson?\n=========\nContent: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.  \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-219
their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland.\nSource: 0-pl\nContent: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.  \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.  \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.\nSource: 24-pl\nContent: And a proud Ukrainian people, who have known 30 years  of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.  \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-220
you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions  is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.  \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.  \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay.\nSource: 5-pl\nContent: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more.  \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-221
\n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation.\nSource: 34-pl\n=========\nFINAL ANSWER: The president did not mention Michael Jackson.\nSOURCES:\n\nQUESTION: {question}\n=========\n{summaries}\n=========\nFINAL ANSWER:', template_format='f-string', validate_template=True), **kwargs)
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-222
Construct the chain from an LLM. Parameters llm (langchain.base_language.BaseLanguageModel) – document_prompt (langchain.prompts.base.BasePromptTemplate) – question_prompt (langchain.prompts.base.BasePromptTemplate) – combine_prompt (langchain.prompts.base.BasePromptTemplate) – kwargs (Any) – Return type langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-223
Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. langchain.chains.create_extraction_chain(schema, llm)[source] Creates a chain that extracts information from a passage. Parameters schema (dict) – The schema of the entities to extract. llm (langchain.base_language.BaseLanguageModel) – The language model to use. Returns Chain that can be used to extract information from a passage. Return type langchain.chains.base.Chain langchain.chains.create_extraction_chain_pydantic(pydantic_schema, llm)[source] Creates a chain that extracts information from a passage using pydantic schema. Parameters pydantic_schema (Any) – The pydantic schema of the entities to extract. llm (langchain.base_language.BaseLanguageModel) – The language model to use. Returns Chain that can be used to extract information from a passage. Return type langchain.chains.base.Chain langchain.chains.create_tagging_chain(schema, llm)[source] Creates a chain that extracts information from a passage. Parameters schema (dict) – The schema of the entities to extract.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-224
Parameters schema (dict) – The schema of the entities to extract. llm (langchain.base_language.BaseLanguageModel) – The language model to use. Returns Chain (LLMChain) that can be used to extract information from a passage. Return type langchain.chains.base.Chain langchain.chains.create_tagging_chain_pydantic(pydantic_schema, llm)[source] Creates a chain that extracts information from a passage. Parameters pydantic_schema (Any) – The pydantic schema of the entities to extract. llm (langchain.base_language.BaseLanguageModel) – The language model to use. Returns Chain (LLMChain) that can be used to extract information from a passage. Return type langchain.chains.base.Chain langchain.chains.load_chain(path, **kwargs)[source] Unified method for loading a chain from LangChainHub or local fs. Parameters path (Union[str, pathlib.Path]) – kwargs (Any) – Return type langchain.chains.base.Chain langchain.chains.create_citation_fuzzy_match_chain(llm)[source] Create a citation fuzzy match chain. Parameters llm (langchain.base_language.BaseLanguageModel) – Language model to use for the chain. Returns Chain (LLMChain) that can be used to answer questions with citations. Return type langchain.chains.llm.LLMChain langchain.chains.create_qa_with_structure_chain(llm, schema, output_parser='base', prompt=None)[source] Create a question answering chain that returns an answer with sources. Parameters llm (langchain.base_language.BaseLanguageModel) – Language model to use for the chain.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-225
schema (Union[dict, Type[pydantic.main.BaseModel]]) – Pydantic schema to use for the output. output_parser (str) – Output parser to use. Should be one of pydantic or base. Default to base. prompt (Optional[Union[langchain.prompts.prompt.PromptTemplate, langchain.prompts.chat.ChatPromptTemplate]]) – Optional prompt to use for the chain. Return type langchain.chains.llm.LLMChain Returns: langchain.chains.create_qa_with_sources_chain(llm, **kwargs)[source] Create a question answering chain that returns an answer with sources. Parameters llm (langchain.base_language.BaseLanguageModel) – Language model to use for the chain. **kwargs – Keyword arguments to pass to create_qa_with_structure_chain. kwargs (Any) – Returns Chain (LLMChain) that can be used to answer questions with citations. Return type langchain.chains.llm.LLMChain class langchain.chains.StuffDocumentsChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_documents', output_key='output_text', llm_chain, document_prompt=None, document_variable_name, document_separator='\n\n')[source] Bases: langchain.chains.combine_documents.base.BaseCombineDocumentsChain Chain that combines documents by stuffing into context. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – input_key (str) – output_key (str) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-226
input_key (str) – output_key (str) – llm_chain (langchain.chains.llm.LLMChain) – document_prompt (langchain.prompts.base.BasePromptTemplate) – document_variable_name (str) – document_separator (str) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute document_prompt: langchain.prompts.base.BasePromptTemplate [Optional] Prompt to use to format each document. attribute document_separator: str = '\n\n' The string with which to join the formatted documents attribute document_variable_name: str [Required] The variable name in the llm_chain to put the documents in. If only one variable in the llm_chain, this need not be provided. attribute llm_chain: langchain.chains.llm.LLMChain [Required] LLM wrapper to use after formatting documents. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute tags: Optional[List[str]] = None
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-227
for the full catalog. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] async acombine_docs(docs, callbacks=None, **kwargs)[source] Stuff all documents into one prompt and pass to LLM. Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-228
kwargs (Any) – Return type Tuple[str, dict] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str combine_docs(docs, callbacks=None, **kwargs)[source] Stuff all documents into one prompt and pass to LLM. Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str]
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-229
return_only_outputs (bool) – Return type Dict[str, str] prompt_length(docs, **kwargs)[source] Get the prompt length by formatting the prompt. Parameters docs (List[langchain.schema.Document]) – kwargs (Any) – Return type Optional[int] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-230
property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.MapRerankDocumentsChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_documents', output_key='output_text', llm_chain, document_variable_name, rank_key, answer_key, metadata_keys=None, return_intermediate_steps=False)[source] Bases: langchain.chains.combine_documents.base.BaseCombineDocumentsChain Combining documents by mapping a chain over them, then reranking results. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – input_key (str) – output_key (str) – llm_chain (langchain.chains.llm.LLMChain) – document_variable_name (str) – rank_key (str) – answer_key (str) – metadata_keys (Optional[List[str]]) – return_intermediate_steps (bool) – Return type None attribute answer_key: str [Required] Key in output of llm_chain to return as answer. attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-231
Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute document_variable_name: str [Required] The variable name in the llm_chain to put the documents in. If only one variable in the llm_chain, this need not be provided. attribute llm_chain: LLMChain [Required] Chain to apply to each document individually. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute metadata_keys: Optional[List[str]] = None attribute rank_key: str [Required] Key in output of llm_chain to rank on. attribute return_intermediate_steps: bool = False attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param.
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-232
only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] async acombine_docs(docs, callbacks=None, **kwargs)[source] Combine documents in a map rerank manner. Combine by mapping first chain over all documents, then reranking the results. Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-233
tags (Optional[List[str]]) – kwargs (Any) – Return type str combine_docs(docs, callbacks=None, **kwargs)[source] Combine documents in a map rerank manner. Combine by mapping first chain over all documents, then reranking the results. Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] prompt_length(docs, **kwargs) Return the prompt length given the documents passed in. Returns None if the method does not depend on the prompt length. Parameters docs (List[langchain.schema.Document]) – kwargs (Any) – Return type Optional[int] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-234
kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.MapReduceDocumentsChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_documents', output_key='output_text', llm_chain, combine_document_chain, collapse_document_chain=None, document_variable_name, return_intermediate_steps=False)[source] Bases: langchain.chains.combine_documents.base.BaseCombineDocumentsChain Combining documents by mapping a chain over them, then combining results. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-235
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – input_key (str) – output_key (str) – llm_chain (langchain.chains.llm.LLMChain) – combine_document_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) – collapse_document_chain (Optional[langchain.chains.combine_documents.base.BaseCombineDocumentsChain]) – document_variable_name (str) – return_intermediate_steps (bool) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute collapse_document_chain: Optional[BaseCombineDocumentsChain] = None Chain to use to collapse intermediary results if needed. If None, will use the combine_document_chain. attribute combine_document_chain: BaseCombineDocumentsChain [Required] Chain to use to combine results of applying llm_chain to documents. attribute document_variable_name: str [Required] The variable name in the llm_chain to put the documents in. If only one variable in the llm_chain, this need not be provided. attribute llm_chain: LLMChain [Required] Chain to apply to each document individually. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-236
Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. attribute return_intermediate_steps: bool = False Return the results of the map steps in the output. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-237
include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any] async acombine_docs(docs, callbacks=None, **kwargs)[source] Combine documents in a map reduce manner. Combine by mapping first chain over all documents, then reducing the results. This reducing can be done recursively if needed (if there are many documents). Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str combine_docs(docs, token_max=3000, callbacks=None, **kwargs)[source] Combine documents in a map reduce manner. Combine by mapping first chain over all documents, then reducing the results. This reducing can be done recursively if needed (if there are many documents). Parameters docs (List[langchain.schema.Document]) – token_max (int) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-238
docs (List[langchain.schema.Document]) – token_max (int) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] prompt_length(docs, **kwargs) Return the prompt length given the documents passed in. Returns None if the method does not depend on the prompt length. Parameters docs (List[langchain.schema.Document]) – kwargs (Any) – Return type Optional[int] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”)
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-239
Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable. class langchain.chains.RefineDocumentsChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_documents', output_key='output_text', initial_llm_chain, refine_llm_chain, document_variable_name, initial_response_name, document_prompt=None, return_intermediate_steps=False)[source] Bases: langchain.chains.combine_documents.base.BaseCombineDocumentsChain Combine documents by doing a first pass and then refining on more documents. Parameters memory (Optional[langchain.schema.BaseMemory]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – verbose (bool) – tags (Optional[List[str]]) – input_key (str) – output_key (str) –
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-240
input_key (str) – output_key (str) – initial_llm_chain (langchain.chains.llm.LLMChain) – refine_llm_chain (langchain.chains.llm.LLMChain) – document_variable_name (str) – initial_response_name (str) – document_prompt (langchain.prompts.base.BasePromptTemplate) – return_intermediate_steps (bool) – Return type None attribute callback_manager: Optional[BaseCallbackManager] = None Deprecated, use callbacks instead. attribute callbacks: Callbacks = None Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. attribute document_prompt: BasePromptTemplate [Optional] Prompt to use to format each document. attribute document_variable_name: str [Required] The variable name in the initial_llm_chain to put the documents in. If only one variable in the initial_llm_chain, this need not be provided. attribute initial_llm_chain: LLMChain [Required] LLM chain to use on initial document. attribute initial_response_name: str [Required] The variable name to format the initial response in when refining. attribute memory: Optional[BaseMemory] = None Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-241
There are many different types of memory - please see memory docs for the full catalog. attribute refine_llm_chain: LLMChain [Required] LLM chain to use when refining. attribute return_intermediate_steps: bool = False Return the results of the refine steps in the output. attribute tags: Optional[List[str]] = None Optional list of tags associated with the chain. Defaults to None These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. attribute verbose: bool [Optional] Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to langchain.verbose value. async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False) Run the logic of this chain and add to output if desired. Parameters inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects only one param. return_only_outputs (bool) – boolean for whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will use the callbacks provided to the chain. include_run_info (bool) – Whether to include run info in the response. Defaults to False. tags (Optional[List[str]]) – Return type Dict[str, Any]
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-242
tags (Optional[List[str]]) – Return type Dict[str, Any] async acombine_docs(docs, callbacks=None, **kwargs)[source] Combine by mapping first chain over all, then stuffing into final chain. Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] apply(input_list, callbacks=None) Call the chain on all inputs in the list. Parameters input_list (List[Dict[str, Any]]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Return type List[Dict[str, str]] async arun(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str combine_docs(docs, callbacks=None, **kwargs)[source] Combine by mapping first chain over all, then stuffing into final chain. Parameters docs (List[langchain.schema.Document]) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – kwargs (Any) – Return type Tuple[str, dict] dict(**kwargs) Return dictionary representation of chain. Parameters kwargs (Any) – Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-243
Return type Dict prep_inputs(inputs) Validate and prep inputs. Parameters inputs (Union[Dict[str, Any], Any]) – Return type Dict[str, str] prep_outputs(inputs, outputs, return_only_outputs=False) Validate and prep outputs. Parameters inputs (Dict[str, str]) – outputs (Dict[str, str]) – return_only_outputs (bool) – Return type Dict[str, str] prompt_length(docs, **kwargs) Return the prompt length given the documents passed in. Returns None if the method does not depend on the prompt length. Parameters docs (List[langchain.schema.Document]) – kwargs (Any) – Return type Optional[int] run(*args, callbacks=None, tags=None, **kwargs) Run the chain as text in, text out or multiple variables, text out. Parameters args (Any) – callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – tags (Optional[List[str]]) – kwargs (Any) – Return type str save(file_path) Save the chain. Parameters file_path (Union[pathlib.Path, str]) – Path to file to save the chain to. Return type None Example: .. code-block:: python chain.save(file_path=”path/chain.yaml”) to_json() Return type Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented] to_json_not_implemented() Return type langchain.load.serializable.SerializedNotImplemented property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the
https://api.python.langchain.com/en/stable/modules/chains.html
5d97bfd0cb46-244
serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool Return whether or not the class is serializable.
https://api.python.langchain.com/en/stable/modules/chains.html
76417e48a30b-0
Base classes Common schema objects. langchain.schema.get_buffer_string(messages, human_prefix='Human', ai_prefix='AI')[source] Get buffer string of messages. Parameters messages (List[langchain.schema.BaseMessage]) – human_prefix (str) – ai_prefix (str) – Return type str class langchain.schema.AgentAction(tool, tool_input, log)[source] Bases: object Agent’s action to take. Parameters tool (str) – tool_input (Union[str, dict]) – log (str) – Return type None class langchain.schema.AgentFinish(return_values, log)[source] Bases: NamedTuple Agent’s return value. Parameters return_values (dict) – log (str) – return_values: dict Alias for field number 0 log: str Alias for field number 1 count(value, /) Return number of occurrences of value. index(value, start=0, stop=9223372036854775807, /) Return first index of value. Raises ValueError if the value is not present. class langchain.schema.Generation(*, text, generation_info=None)[source] Bases: langchain.load.serializable.Serializable Output of a single generation. Parameters text (str) – generation_info (Optional[Dict[str, Any]]) – Return type None attribute generation_info: Optional[Dict[str, Any]] = None Raw generation info response from the provider attribute text: str [Required] Generated text output. classmethod construct(_fields_set=None, **values) Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-1
Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values Parameters _fields_set (Optional[SetStr]) – values (Any) – Return type Model copy(*, include=None, exclude=None, update=None, deep=False) Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep (bool) – set to True to make a deep copy of the model self (Model) – Returns new model instance Return type Model dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – Return type DictStrAny
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-2
exclude_none (bool) – Return type DictStrAny json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – encoder (Optional[Callable[[Any], Any]]) – models_as_dict (bool) – dumps_kwargs (Any) – Return type unicode classmethod update_forward_refs(**localns) Try to update ForwardRefs on fields based on this Model, globalns and localns. Parameters localns (Any) – Return type None property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool This class is LangChain serializable.
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-3
property lc_serializable: bool This class is LangChain serializable. class langchain.schema.BaseMessage(*, content, additional_kwargs=None)[source] Bases: langchain.load.serializable.Serializable Message object. Parameters content (str) – additional_kwargs (dict) – Return type None classmethod construct(_fields_set=None, **values) Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values Parameters _fields_set (Optional[SetStr]) – values (Any) – Return type Model copy(*, include=None, exclude=None, update=None, deep=False) Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep (bool) – set to True to make a deep copy of the model self (Model) – Returns new model instance Return type Model dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-4
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – Return type DictStrAny json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – encoder (Optional[Callable[[Any], Any]]) – models_as_dict (bool) – dumps_kwargs (Any) – Return type unicode classmethod update_forward_refs(**localns) Try to update ForwardRefs on fields based on this Model, globalns and localns. Parameters localns (Any) – Return type None property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str]
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-5
constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool This class is LangChain serializable. abstract property type: str Type of the message, used for serialization. class langchain.schema.HumanMessage(*, content, additional_kwargs=None, example=False)[source] Bases: langchain.schema.BaseMessage Type of message that is spoken by the human. Parameters content (str) – additional_kwargs (dict) – example (bool) – Return type None classmethod construct(_fields_set=None, **values) Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values Parameters _fields_set (Optional[SetStr]) – values (Any) – Return type Model copy(*, include=None, exclude=None, update=None, deep=False) Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-6
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep (bool) – set to True to make a deep copy of the model self (Model) – Returns new model instance Return type Model dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – Return type DictStrAny json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – encoder (Optional[Callable[[Any], Any]]) – models_as_dict (bool) –
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-7
models_as_dict (bool) – dumps_kwargs (Any) – Return type unicode classmethod update_forward_refs(**localns) Try to update ForwardRefs on fields based on this Model, globalns and localns. Parameters localns (Any) – Return type None property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool This class is LangChain serializable. property type: str Type of the message, used for serialization. class langchain.schema.AIMessage(*, content, additional_kwargs=None, example=False)[source] Bases: langchain.schema.BaseMessage Type of message that is spoken by the AI. Parameters content (str) – additional_kwargs (dict) – example (bool) – Return type None classmethod construct(_fields_set=None, **values) Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values Parameters _fields_set (Optional[SetStr]) – values (Any) – Return type Model copy(*, include=None, exclude=None, update=None, deep=False)
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-8
Model copy(*, include=None, exclude=None, update=None, deep=False) Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep (bool) – set to True to make a deep copy of the model self (Model) – Returns new model instance Return type Model dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – Return type DictStrAny json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). Parameters
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-9
Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – encoder (Optional[Callable[[Any], Any]]) – models_as_dict (bool) – dumps_kwargs (Any) – Return type unicode classmethod update_forward_refs(**localns) Try to update ForwardRefs on fields based on this Model, globalns and localns. Parameters localns (Any) – Return type None property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool This class is LangChain serializable. property type: str Type of the message, used for serialization. class langchain.schema.SystemMessage(*, content, additional_kwargs=None)[source] Bases: langchain.schema.BaseMessage Type of message that is a system message. Parameters content (str) – additional_kwargs (dict) – Return type None classmethod construct(_fields_set=None, **values)
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-10
Return type None classmethod construct(_fields_set=None, **values) Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values Parameters _fields_set (Optional[SetStr]) – values (Any) – Return type Model copy(*, include=None, exclude=None, update=None, deep=False) Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep (bool) – set to True to make a deep copy of the model self (Model) – Returns new model instance Return type Model dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – Return type
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-11
exclude_defaults (bool) – exclude_none (bool) – Return type DictStrAny json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – encoder (Optional[Callable[[Any], Any]]) – models_as_dict (bool) – dumps_kwargs (Any) – Return type unicode classmethod update_forward_refs(**localns) Try to update ForwardRefs on fields based on this Model, globalns and localns. Parameters localns (Any) – Return type None property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str] Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”] property lc_secrets: Dict[str, str] Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”} property lc_serializable: bool
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-12
property lc_serializable: bool This class is LangChain serializable. property type: str Type of the message, used for serialization. class langchain.schema.FunctionMessage(*, content, additional_kwargs=None, name)[source] Bases: langchain.schema.BaseMessage Parameters content (str) – additional_kwargs (dict) – name (str) – Return type None classmethod construct(_fields_set=None, **values) Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values Parameters _fields_set (Optional[SetStr]) – values (Any) – Return type Model copy(*, include=None, exclude=None, update=None, deep=False) Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep (bool) – set to True to make a deep copy of the model self (Model) – Returns new model instance Return type Model dict(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False)
https://api.python.langchain.com/en/stable/modules/base_classes.html
76417e48a30b-13
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – Return type DictStrAny json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs) Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). Parameters include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – by_alias (bool) – skip_defaults (Optional[bool]) – exclude_unset (bool) – exclude_defaults (bool) – exclude_none (bool) – encoder (Optional[Callable[[Any], Any]]) – models_as_dict (bool) – dumps_kwargs (Any) – Return type unicode classmethod update_forward_refs(**localns) Try to update ForwardRefs on fields based on this Model, globalns and localns. Parameters localns (Any) – Return type None property lc_attributes: Dict Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_namespace: List[str]
https://api.python.langchain.com/en/stable/modules/base_classes.html