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.


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 aroute(inputs, callbacks=None)
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)


str
dict(**kwargs)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict
classmethod from_llm(llm, prompt, **kwargs)[source]
Convenience constructor.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
prompt (langchain.prompts.base.BasePromptTemplate) –
kwargs (Any) –
Return type
langchain.chains.router.llm_router.LLMRouterChain
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


Return type
Dict[str, str]
route(inputs, callbacks=None)
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:


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.
property output_keys: List[str]
Output keys this chain expects.


class langchain.chains.LLMSummarizationCheckerChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, sequential_chain, llm=None, create_assertions_prompt=PromptTemplate(input_variables=['summary'], output_parser=None, partial_variables={}, template='Given some text, extract a list of facts from the text.\n\nFormat your output as a bulleted list.\n\nText:\n"""\n{summary}\n"""\n\nFacts:', template_format='f-string', validate_template=True), check_assertions_prompt=PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\n\nHere is a bullet point list of facts:\n"""\n{assertions}\n"""\n\nFor each fact, determine whether it is true or false about the subject. If you


is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".\nIf the fact is false, explain why.\n\n', template_format='f-string', validate_template=True), revised_summary_prompt=PromptTemplate(input_variables=['checked_assertions', 'summary'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\n\nChecked Assertions:\n"""\n{checked_assertions}\n"""\n\nOriginal Summary:\n"""\n{summary}\n"""\n\nUsing these checked assertions, rewrite the original summary to be completely true.\n\nThe output should have the same structure and formatting as the original summary.\n\nSummary:', template_format='f-string', validate_template=True), are_all_true_prompt=PromptTemplate(input_variables=['checked_assertions'],


output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false.\n\nIf all of the assertions are true, return "True". If any of the assertions are false, return "False".\n\nHere are some examples:\n===\n\nChecked Assertions: """\n- The sky is red: False\n- Water is made of lava: False\n- The sun is a star: True\n"""\nResult: False\n\n===\n\nChecked Assertions: """\n- The sky is blue: True\n- Water is wet: True\n- The sun is a star: True\n"""\nResult: True\n\n===\n\nChecked Assertions: """\n- The sky is blue - True\n- Water is made of lava- False\n- The sun is a star - True\n"""\nResult: False\n\n===\n\nChecked


False\n\n===\n\nChecked Assertions:"""\n{checked_assertions}\n"""\nResult:', template_format='f-string', validate_template=True), input_key='query', output_key='result', max_checks=2)[source]


Bases: langchain.chains.base.Chain
Chain for question-answering with self-verification.
Example
from langchain import OpenAI, LLMSummarizationCheckerChain
llm = OpenAI(temperature=0.0)
checker_chain = LLMSummarizationCheckerChain.from_llm(llm)
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]]) –
sequential_chain (langchain.chains.sequential.SequentialChain) –
llm (Optional[langchain.base_language.BaseLanguageModel]) –
create_assertions_prompt (langchain.prompts.prompt.PromptTemplate) –


check_assertions_prompt (langchain.prompts.prompt.PromptTemplate) –
revised_summary_prompt (langchain.prompts.prompt.PromptTemplate) –
are_all_true_prompt (langchain.prompts.prompt.PromptTemplate) –
input_key (str) –
output_key (str) –
max_checks (int) –
Return type
None


attribute are_all_true_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false.\n\nIf all of the assertions are true, return "True". If any of the assertions are false, return "False".\n\nHere are some examples:\n===\n\nChecked Assertions: """\n- The sky is red: False\n- Water is made of lava: False\n- The sun is a star: True\n"""\nResult: False\n\n===\n\nChecked Assertions: """\n- The sky is blue: True\n- Water is wet: True\n- The sun is a star: True\n"""\nResult: True\n\n===\n\nChecked Assertions: """\n- The sky is blue - True\n- Water is made of lava- False\n- The sun is a star -


False\n- The sun is a star - True\n"""\nResult: False\n\n===\n\nChecked Assertions:"""\n{checked_assertions}\n"""\nResult:', template_format='f-string', validate_template=True)


[Deprecated]
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.


for full details.
attribute check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\n\nHere is a bullet point list of facts:\n"""\n{assertions}\n"""\n\nFor each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".\nIf the fact is false, explain why.\n\n', template_format='f-string', validate_template=True)
[Deprecated]


[Deprecated]
attribute create_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['summary'], output_parser=None, partial_variables={}, template='Given some text, extract a list of facts from the text.\n\nFormat your output as a bulleted list.\n\nText:\n"""\n{summary}\n"""\n\nFacts:', template_format='f-string', validate_template=True)
[Deprecated]
attribute llm: Optional[BaseLanguageModel] = None
[Deprecated] LLM wrapper to use.
attribute max_checks: int = 2
Maximum number of times to check the assertions. Default to double-checking.
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 revised_summary_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'summary'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\n\nChecked Assertions:\n"""\n{checked_assertions}\n"""\n\nOriginal Summary:\n"""\n{summary}\n"""\n\nUsing these checked assertions, rewrite the original summary to be completely true.\n\nThe output should have the same structure and formatting as the original summary.\n\nSummary:', template_format='f-string', validate_template=True)
[Deprecated]
attribute sequential_chain: SequentialChain [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
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type


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, create_assertions_prompt=PromptTemplate(input_variables=['summary'], output_parser=None, partial_variables={}, template='Given some text, extract a list of facts from the text.\n\nFormat your output as a bulleted list.\n\nText:\n"""\n{summary}\n"""\n\nFacts:', template_format='f-string', validate_template=True), check_assertions_prompt=PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\n\nHere is a bullet point list of facts:\n"""\n{assertions}\n"""\n\nFor each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".\nIf the fact is false, explain why.\n\n',


fact is false, explain why.\n\n', template_format='f-string', validate_template=True), revised_summary_prompt=PromptTemplate(input_variables=['checked_assertions', 'summary'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\n\nChecked Assertions:\n"""\n{checked_assertions}\n"""\n\nOriginal Summary:\n"""\n{summary}\n"""\n\nUsing these checked assertions, rewrite the original summary to be completely true.\n\nThe output should have the same structure and formatting as the original summary.\n\nSummary:', template_format='f-string', validate_template=True), are_all_true_prompt=PromptTemplate(input_variables=['checked_assertions'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false.\n\nIf all of the


true or false.\n\nIf all of the assertions are true, return "True". If any of the assertions are false, return "False".\n\nHere are some examples:\n===\n\nChecked Assertions: """\n- The sky is red: False\n- Water is made of lava: False\n- The sun is a star: True\n"""\nResult: False\n\n===\n\nChecked Assertions: """\n- The sky is blue: True\n- Water is wet: True\n- The sun is a star: True\n"""\nResult: True\n\n===\n\nChecked Assertions: """\n- The sky is blue - True\n- Water is made of lava- False\n- The sun is a star - True\n"""\nResult: False\n\n===\n\nChecked Assertions:"""\n{checked_assertions}\n"""\nResult:', template_format='f-string', validate_template=True),


template_format='f-string', validate_template=True), verbose=False, **kwargs)[source]


Parameters
llm (langchain.base_language.BaseLanguageModel) –
create_assertions_prompt (langchain.prompts.prompt.PromptTemplate) –
check_assertions_prompt (langchain.prompts.prompt.PromptTemplate) –
revised_summary_prompt (langchain.prompts.prompt.PromptTemplate) –
are_all_true_prompt (langchain.prompts.prompt.PromptTemplate) –
verbose (bool) –
kwargs (Any) –
Return type
langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain
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]) –


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


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.MapReduceChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_documents_chain, text_splitter, input_key='input_text', output_key='output_text')[source]
Bases: langchain.chains.base.Chain
Map-reduce chain.
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) –
text_splitter (langchain.text_splitter.TextSplitter) –
input_key (str) –
output_key (str) –
Return type
None


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 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 text_splitter: TextSplitter [Required]
Text splitter to use.
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


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


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


Return type
Dict
classmethod from_params(llm, prompt, text_splitter, callbacks=None, combine_chain_kwargs=None, reduce_chain_kwargs=None, **kwargs)[source]
Construct a map-reduce chain that uses the chain for map and reduce.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
prompt (langchain.prompts.base.BasePromptTemplate) –
text_splitter (langchain.text_splitter.TextSplitter) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
combine_chain_kwargs (Optional[Mapping[str, Any]]) –
reduce_chain_kwargs (Optional[Mapping[str, Any]]) –
kwargs (Any) –
Return type
langchain.chains.mapreduce.MapReduceChain
prep_inputs(inputs)
Validate and prep inputs.
Parameters


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


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.MultiPromptChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, router_chain, destination_chains, default_chain, silent_errors=False)[source]
Bases: langchain.chains.router.base.MultiRouteChain
A multi-route chain that uses an LLM router chain to choose amongst prompts.
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]]) –


tags (Optional[List[str]]) –
router_chain (langchain.chains.router.base.RouterChain) –
destination_chains (Mapping[str, langchain.chains.llm.LLMChain]) –
default_chain (langchain.chains.llm.LLMChain) –
silent_errors (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 default_chain: LLMChain [Required]


Default chain to use when router doesn’t map input to one of the destinations.
attribute destination_chains: Mapping[str, LLMChain] [Required]
Map of name to candidate chains that inputs can be routed to.
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 router_chain: RouterChain [Required]
Chain for deciding a destination chain and the input to it.
attribute silent_errors: bool = False
If True, use default_chain when an invalid destination name is provided.
Defaults to False.


Defaults to 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.


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)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict
classmethod from_prompts(llm, prompt_infos, default_chain=None, **kwargs)[source]
Convenience constructor for instantiating from destination prompts.
Parameters


Parameters
llm (langchain.base_language.BaseLanguageModel) –
prompt_infos (List[Dict[str, str]]) –
default_chain (Optional[langchain.chains.llm.LLMChain]) –
kwargs (Any) –
Return type
langchain.chains.router.multi_prompt.MultiPromptChain
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.
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.MultiRetrievalQAChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, router_chain, destination_chains, default_chain, silent_errors=False)[source]
Bases: langchain.chains.router.base.MultiRouteChain
A multi-route chain that uses an LLM router chain to choose amongst retrieval
qa chains.
Parameters


qa chains.
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]]) –
router_chain (langchain.chains.router.llm_router.LLMRouterChain) –
destination_chains (Mapping[str, langchain.chains.retrieval_qa.base.BaseRetrievalQA]) –
default_chain (langchain.chains.base.Chain) –
silent_errors (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 default_chain: Chain [Required]
Default chain to use when router doesn’t map input to one of the destinations.
attribute destination_chains: Mapping[str, BaseRetrievalQA] [Required]
Map of name to candidate chains that inputs can be routed to.
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.


for the full catalog.
attribute router_chain: LLMRouterChain [Required]
Chain for deciding a destination chain and the input to it.
attribute silent_errors: bool = False
If True, use default_chain when an invalid destination name is provided.
Defaults to 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)


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


Return type
Dict
classmethod from_retrievers(llm, retriever_infos, default_retriever=None, default_prompt=None, default_chain=None, **kwargs)[source]
Parameters
llm (langchain.base_language.BaseLanguageModel) –
retriever_infos (List[Dict[str, Any]]) –
default_retriever (Optional[langchain.schema.BaseRetriever]) –
default_prompt (Optional[langchain.prompts.prompt.PromptTemplate]) –
default_chain (Optional[langchain.chains.base.Chain]) –
kwargs (Any) –
Return type
langchain.chains.router.multi_retrieval_qa.MultiRetrievalQAChain
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.
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.MultiRouteChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, router_chain, destination_chains, default_chain, silent_errors=False)[source]
Bases: langchain.chains.base.Chain
Use a single chain to route an input to one of multiple candidate chains.
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]]) –
router_chain (langchain.chains.router.base.RouterChain) –
destination_chains (Mapping[str, langchain.chains.base.Chain]) –
default_chain (langchain.chains.base.Chain) –
silent_errors (bool) –
Return type


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 default_chain: Chain [Required]
Default chain to use when none of the destination chains are suitable.
attribute destination_chains: Mapping[str, Chain] [Required]
Chains that return final answer to inputs.
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 router_chain: RouterChain [Required]
Chain that routes inputs to destination chains.
attribute silent_errors: bool = False
If True, use default_chain when an invalid destination name is provided.
Defaults to 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.


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]) –
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) –


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.NatBotChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, llm_chain, objective, llm=None, input_url_key='url', input_browser_content_key='browser_content', previous_command='', output_key='command')[source]
Bases: langchain.chains.base.Chain
Implement an LLM driven browser.
Example


Implement an LLM driven browser.
Example
from langchain import NatBotChain
natbot = NatBotChain.from_default("Buy me a new hat.")
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) –
objective (str) –
llm (Optional[langchain.base_language.BaseLanguageModel]) –
input_url_key (str) –
input_browser_content_key (str) –
previous_command (str) –
output_key (str) –
Return type
None


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 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 objective: str [Required]
Objective that NatBot is tasked with completing.
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)


Return type
Dict
execute(url, browser_content)[source]
Figure out next browser command to run.
Parameters
url (str) – URL of the site currently on.
browser_content (str) – Content of the page as currently displayed by the browser.
Returns
Next browser command to run.
Return type
str
Example
browser_content = "...."
llm_command = natbot.run("www.google.com", browser_content)
classmethod from_default(objective, **kwargs)[source]
Load with default LLMChain.
Parameters
objective (str) –
kwargs (Any) –
Return type
langchain.chains.natbot.base.NatBotChain
classmethod from_llm(llm, objective, **kwargs)[source]
Load from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
objective (str) –


objective (str) –
kwargs (Any) –
Return type
langchain.chains.natbot.base.NatBotChain
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.


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.NebulaGraphQAChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, graph, ngql_generation_chain, qa_chain, input_key='query', output_key='result')[source]
Bases: langchain.chains.base.Chain
Chain for question-answering against a graph by generating nGQL statements.
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]]) –
graph (langchain.graphs.nebula_graph.NebulaGraph) –
ngql_generation_chain (langchain.chains.llm.LLMChain) –
qa_chain (langchain.chains.llm.LLMChain) –
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 graph: NebulaGraph [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 ngql_generation_chain: LLMChain [Required]
attribute qa_chain: LLMChain [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
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type
List[Dict[str, str]]


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, *, qa_prompt=PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template="You are an assistant that helps to form nice and human understandable answers.\nThe information part contains the provided information that you must use to construct an answer.\nThe provided information is authorative, you must never doubt it or try to use your internal knowledge to correct it.\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\nIf the provided information is empty, say that you don't know the answer.\nInformation:\n{context}\n\nQuestion: {question}\nHelpful Answer:", template_format='f-string', validate_template=True), ngql_prompt=PromptTemplate(input_variables=['schema', 'question'], output_parser=None, partial_variables={}, template="Task:Generate NebulaGraph Cypher statement to query a graph


NebulaGraph Cypher statement to query a graph database.\n\nInstructions:\n\nFirst, generate cypher then convert it to NebulaGraph Cypher dialect(rather than standard):\n1. it requires explicit label specification when referring to node properties: v.`Foo`.name\n2. it uses double equals sign for comparison: `==` rather than `=`\nFor instance:\n```diff\n< MATCH (p:person)-[:directed]->(m:movie) WHERE m.name = 'The Godfather II'\n< RETURN p.name;\n---\n> MATCH (p:`person`)-[:directed]->(m:`movie`) WHERE m.`movie`.`name` == 'The Godfather II'\n> RETURN p.`person`.`name`;\n```\n\nUse only the provided relationship types and properties in the schema.\nDo not use any other relationship types or properties that are not


use any other relationship types or properties that are not provided.\nSchema:\n{schema}\nNote: Do not include any explanations or apologies in your responses.\nDo not respond to any questions that might ask anything else than for you to construct a Cypher statement.\nDo not include any text except the generated Cypher statement.\n\nThe question is:\n{question}", template_format='f-string', validate_template=True), **kwargs)[source]


Initialize from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
qa_prompt (langchain.prompts.base.BasePromptTemplate) –
ngql_prompt (langchain.prompts.base.BasePromptTemplate) –
kwargs (Any) –
Return type
langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain
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


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.OpenAIModerationChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, client=None, model_name=None, error=False, input_key='input', output_key='output', openai_api_key=None, openai_organization=None)[source]


Bases: langchain.chains.base.Chain
Pass input through a moderation endpoint.
To use, you should have the openai python package installed, and the
environment variable OPENAI_API_KEY set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved on this class.
Example
from langchain.chains import OpenAIModerationChain
moderation = OpenAIModerationChain()
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]]) –
client (Any) –
model_name (Optional[str]) –
error (bool) –


error (bool) –
input_key (str) –
output_key (str) –
openai_api_key (Optional[str]) –
openai_organization (Optional[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 error: bool = False
Whether or not to error if bad content was found.
attribute memory: Optional[BaseMemory] = None
Optional memory object. Defaults to 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 model_name: Optional[str] = None
Moderation model name to use.
attribute openai_api_key: Optional[str] = None
attribute openai_organization: Optional[str] = None
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]


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.


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]) –
return_only_outputs (bool) –
Return type
Dict[str, str]


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()


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.OpenAPIEndpointChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, api_request_chain, api_response_chain=None, api_operation, requests=None, param_mapping, return_intermediate_steps=False, instructions_key='instructions', output_key='output', max_text_length=None)[source]
Bases: langchain.chains.base.Chain, pydantic.main.BaseModel
Chain interacts with an OpenAPI endpoint using natural language.
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]]) –
api_request_chain (langchain.chains.llm.LLMChain) –


api_response_chain (Optional[langchain.chains.llm.LLMChain]) –
api_operation (langchain.tools.openapi.utils.api_models.APIOperation) –
requests (langchain.requests.Requests) –
param_mapping (langchain.chains.api.openapi.chain._ParamMapping) –
return_intermediate_steps (bool) –
instructions_key (str) –
output_key (str) –
max_text_length (Optional[int]) –
Return type
None
attribute api_operation: APIOperation [Required]
attribute api_request_chain: LLMChain [Required]
attribute api_response_chain: Optional[LLMChain] = 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
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 param_mapping: _ParamMapping [Required]
attribute requests: Requests [Optional]
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.
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]]


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
deserialize_json_input(serialized_args)[source]
Use the serialized typescript dictionary.
Resolve the path, query params dict, and optional requestBody dict.
Parameters
serialized_args (str) –
Return type
dict
dict(**kwargs)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict


Return type
Dict
classmethod from_api_operation(operation, llm, requests=None, verbose=False, return_intermediate_steps=False, raw_response=False, callbacks=None, **kwargs)[source]
Create an OpenAPIEndpointChain from an operation and a spec.
Parameters
operation (langchain.tools.openapi.utils.api_models.APIOperation) –
llm (langchain.base_language.BaseLanguageModel) –
requests (Optional[langchain.requests.Requests]) –
verbose (bool) –
return_intermediate_steps (bool) –
raw_response (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
langchain.chains.api.openapi.chain.OpenAPIEndpointChain


classmethod from_url_and_method(spec_url, path, method, llm, requests=None, return_intermediate_steps=False, **kwargs)[source]
Create an OpenAPIEndpoint from a spec at the specified url.
Parameters
spec_url (str) –
path (str) –
method (str) –
llm (langchain.base_language.BaseLanguageModel) –
requests (Optional[langchain.requests.Requests]) –
return_intermediate_steps (bool) –
kwargs (Any) –
Return type
langchain.chains.api.openapi.chain.OpenAPIEndpointChain
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]) –


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


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.PALChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, llm_chain, llm=None, prompt=PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\n\n# solution in Python:\n\n\ndef solution():\n    """Olivia has $23. She bought five bagels for $3 each. How much money does she have left?"""\n    money_initial = 23\n    bagels = 5\n    bagel_cost = 3\n    money_spent = bagels * bagel_cost\n    money_left = money_initial - money_spent\n    result = money_left\n    return result\n\n\n\n\n\nQ: Michael had 58 golf balls. On tuesday, he lost 23 golf


On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\n\n# solution in Python:\n\n\ndef solution():\n    """Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?"""\n    golf_balls_initial = 58\n    golf_balls_lost_tuesday = 23\n    golf_balls_lost_wednesday = 2\n    golf_balls_left = golf_balls_initial - golf_balls_lost_tuesday - golf_balls_lost_wednesday\n    result = golf_balls_left\n    return result\n\n\n\n\n\nQ: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers


from monday to thursday. How many computers are now in the server room?\n\n# solution in Python:\n\n\ndef solution():\n    """There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?"""\n    computers_initial = 9\n    computers_per_day = 5\n    num_days = 4  # 4 days between monday and thursday\n    computers_added = computers_per_day * num_days\n    computers_total = computers_initial + computers_added\n    result = computers_total\n    return result\n\n\n\n\n\nQ: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\n\n# solution in Python:\n\n\ndef solution():\n    """Shawn has five toys. For Christmas, he got two toys each from his mom


Christmas, he got two toys each from his mom and dad. How many toys does he have now?"""\n    toys_initial = 5\n    mom_toys = 2\n    dad_toys = 2\n    total_received = mom_toys + dad_toys\n    total_toys = toys_initial + total_received\n    result = total_toys\n    return result\n\n\n\n\n\nQ: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\n\n# solution in Python:\n\n\ndef solution():\n    """Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?"""\n    jason_lollipops_initial


jason_lollipops_initial = 20\n    jason_lollipops_after = 12\n    denny_lollipops = jason_lollipops_initial - jason_lollipops_after\n    result = denny_lollipops\n    return result\n\n\n\n\n\nQ: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\n\n# solution in Python:\n\n\ndef solution():\n    """Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?"""\n    leah_chocolates = 32\n    sister_chocolates = 42\n    total_chocolates = leah_chocolates + sister_chocolates\n    chocolates_eaten = 35\n    chocolates_left = total_chocolates -


chocolates_left = total_chocolates - chocolates_eaten\n    result = chocolates_left\n    return result\n\n\n\n\n\nQ: If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\n\n# solution in Python:\n\n\ndef solution():\n    """If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?"""\n    cars_initial = 3\n    cars_arrived = 2\n    total_cars = cars_initial + cars_arrived\n    result = total_cars\n    return result\n\n\n\n\n\nQ: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\n\n# solution in


workers plant today?\n\n# solution in Python:\n\n\ndef solution():\n    """There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?"""\n    trees_initial = 15\n    trees_after = 21\n    trees_added = trees_after - trees_initial\n    result = trees_added\n    return result\n\n\n\n\n\nQ: {question}\n\n# solution in Python:\n\n\n', template_format='f-string', validate_template=True), stop='\n\n', get_answer_expr='print(solution())', python_globals=None, python_locals=None, output_key='result', return_intermediate_steps=False)[source]


Bases: langchain.chains.base.Chain
Implements Program-Aided Language Models.
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]) –
prompt (langchain.prompts.base.BasePromptTemplate) –
stop (str) –
get_answer_expr (str) –
python_globals (Optional[Dict[str, Any]]) –
python_locals (Optional[Dict[str, Any]]) –
output_key (str) –
return_intermediate_steps (bool) –


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 get_answer_expr: str = 'print(solution())'
attribute llm: Optional[BaseLanguageModel] = None
[Deprecated]
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: BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\n\n# solution in Python:\n\n\ndef solution():\n    """Olivia has $23. She bought five bagels for $3 each. How much money does she have left?"""\n    money_initial = 23\n    bagels = 5\n    bagel_cost = 3\n    money_spent = bagels * bagel_cost\n    money_left = money_initial - money_spent\n    result = money_left\n    return result\n\n\n\n\n\nQ: Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\n\n#


at the end of wednesday?\n\n# solution in Python:\n\n\ndef solution():\n    """Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?"""\n    golf_balls_initial = 58\n    golf_balls_lost_tuesday = 23\n    golf_balls_lost_wednesday = 2\n    golf_balls_left = golf_balls_initial - golf_balls_lost_tuesday - golf_balls_lost_wednesday\n    result = golf_balls_left\n    return result\n\n\n\n\n\nQ: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?\n\n# solution in Python:\n\n\ndef solution():\n    """There were nine computers


solution():\n    """There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?"""\n    computers_initial = 9\n    computers_per_day = 5\n    num_days = 4  # 4 days between monday and thursday\n    computers_added = computers_per_day * num_days\n    computers_total = computers_initial + computers_added\n    result = computers_total\n    return result\n\n\n\n\n\nQ: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\n\n# solution in Python:\n\n\ndef solution():\n    """Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?"""\n    toys_initial = 5\n    mom_toys =


= 5\n    mom_toys = 2\n    dad_toys = 2\n    total_received = mom_toys + dad_toys\n    total_toys = toys_initial + total_received\n    result = total_toys\n    return result\n\n\n\n\n\nQ: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\n\n# solution in Python:\n\n\ndef solution():\n    """Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?"""\n    jason_lollipops_initial = 20\n    jason_lollipops_after = 12\n    denny_lollipops =


denny_lollipops = jason_lollipops_initial - jason_lollipops_after\n    result = denny_lollipops\n    return result\n\n\n\n\n\nQ: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\n\n# solution in Python:\n\n\ndef solution():\n    """Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?"""\n    leah_chocolates = 32\n    sister_chocolates = 42\n    total_chocolates = leah_chocolates + sister_chocolates\n    chocolates_eaten = 35\n    chocolates_left = total_chocolates - chocolates_eaten\n    result = chocolates_left\n    return result\n\n\n\n\n\nQ: If there are 3


If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\n\n# solution in Python:\n\n\ndef solution():\n    """If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?"""\n    cars_initial = 3\n    cars_arrived = 2\n    total_cars = cars_initial + cars_arrived\n    result = total_cars\n    return result\n\n\n\n\n\nQ: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\n\n# solution in Python:\n\n\ndef solution():\n    """There are 15 trees in the grove. Grove workers will plant trees in the grove today. After


will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?"""\n    trees_initial = 15\n    trees_after = 21\n    trees_added = trees_after - trees_initial\n    result = trees_added\n    return result\n\n\n\n\n\nQ: {question}\n\n# solution in Python:\n\n\n', template_format='f-string', validate_template=True)


[Deprecated]
attribute python_globals: Optional[Dict[str, Any]] = None
attribute python_locals: Optional[Dict[str, Any]] = None
attribute return_intermediate_steps: bool = False
attribute stop: str = '\n\n'
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)


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


Return type
Dict
classmethod from_colored_object_prompt(llm, **kwargs)[source]
Load PAL from colored object prompt.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
kwargs (Any) –
Return type
langchain.chains.pal.base.PALChain
classmethod from_math_prompt(llm, **kwargs)[source]
Load PAL from math prompt.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
kwargs (Any) –
Return type
langchain.chains.pal.base.PALChain
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]) –


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


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.QAGenerationChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, llm_chain, text_splitter=<langchain.text_splitter.RecursiveCharacterTextSplitter object>, input_key='text', output_key='questions', k=None)[source]
Bases: langchain.chains.base.Chain
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) –
text_splitter (langchain.text_splitter.TextSplitter) –
input_key (str) –
output_key (str) –


output_key (str) –
k (Optional[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 input_key: str = 'text'
attribute k: Optional[int] = None
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 output_key: str = 'questions'
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 text_splitter: TextSplitter = <langchain.text_splitter.RecursiveCharacterTextSplitter object>
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.


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_llm(llm, prompt=None, **kwargs)[source]
Parameters
llm (langchain.base_language.BaseLanguageModel) –
prompt (Optional[langchain.prompts.base.BasePromptTemplate]) –
kwargs (Any) –
Return type
langchain.chains.qa_generation.base.QAGenerationChain
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]) –


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


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]]) –


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.


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]


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.


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) –
chain_type_kwargs (Optional[dict]) –
kwargs (Any) –
Return type
langchain.chains.qa_with_sources.base.BaseQAWithSourcesChain


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.


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


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


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