update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) –
Returns
new model instance
Return type
Model
dict(**kwargs)[source]
Return dictionary representation of output parser.
Parameters
kwargs (Any) –
Return type
Dict
get_format_instructions()[source]
Instructions on how the LLM output should be formatted.
Return type
str
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) –
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) –
by_alias (bool) –
skip_defaults (Optional[bool]) –
exclude_unset (bool) –
exclude_defaults (bool) –
exclude_none (bool) –
encoder (Optional[Callable[[Any], Any]]) –
models_as_dict (bool) –
dumps_kwargs (Any) –
Return type
unicode
abstract parse(text)[source]
Parse the output of an LLM call.
A method which takes in a string (assumed output of a language model )
and parses it into some structure.
Parameters
text (str) – output of language model
Returns
structured output
Return type
langchain.schema.T


Returns
structured output
Return type
langchain.schema.T
parse_result(result)[source]
Parse LLM Result.
Parameters
result (List[langchain.schema.Generation]) –
Return type
langchain.schema.T
parse_with_prompt(completion, prompt)[source]
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion (str) – output of language model
prompt (langchain.schema.PromptValue) – prompt value
Returns
structured output
Return type
Any
classmethod update_forward_refs(**localns)
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) –
Return type
None
property lc_attributes: Dict
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool
Return whether or not the class is serializable.
class langchain.schema.NoOpOutputParser[source]
Bases: langchain.schema.BaseOutputParser[str]
Output parser that just returns the text as is.
Return type
None
classmethod construct(_fields_set=None, **values)


Return type
None
classmethod construct(_fields_set=None, **values)
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) –
values (Any) –
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) –
Returns
new model instance
Return type
Model
dict(**kwargs)
Return dictionary representation of output parser.
Parameters
kwargs (Any) –
Return type
Dict
get_format_instructions()
Instructions on how the LLM output should be formatted.
Return type
str
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().


Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) –
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) –
by_alias (bool) –
skip_defaults (Optional[bool]) –
exclude_unset (bool) –
exclude_defaults (bool) –
exclude_none (bool) –
encoder (Optional[Callable[[Any], Any]]) –
models_as_dict (bool) –
dumps_kwargs (Any) –
Return type
unicode
parse(text)[source]
Parse the output of an LLM call.
A method which takes in a string (assumed output of a language model )
and parses it into some structure.
Parameters
text (str) – output of language model
Returns
structured output
Return type
str
parse_result(result)
Parse LLM Result.
Parameters
result (List[langchain.schema.Generation]) –
Return type
langchain.schema.T
parse_with_prompt(completion, prompt)
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion (str) – output of language model
prompt (langchain.schema.PromptValue) – prompt value
Returns
structured output
Return type
Any
classmethod update_forward_refs(**localns)
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) –
Return type
None
property lc_attributes: Dict
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.


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.
exception langchain.schema.OutputParserException(error, observation=None, llm_output=None, send_to_llm=False)[source]
Bases: ValueError
Exception that output parsers should raise to signify a parsing error.
This exists to differentiate parsing errors from other code or execution errors
that also may arise inside the output parser. OutputParserExceptions will be
available to catch and handle in ways to fix the parsing error, while other
errors will be raised.
Parameters
error (Any) –
observation (str | None) –
llm_output (str | None) –
send_to_llm (bool) –
add_note()
Exception.add_note(note) –
add a note to the exception
with_traceback()
Exception.with_traceback(tb) –
set self.__traceback__ to tb and return self.
class langchain.schema.BaseDocumentTransformer[source]
Bases: abc.ABC
Base interface for transforming documents.
abstract transform_documents(documents, **kwargs)[source]
Transform a list of documents.
Parameters
documents (Sequence[langchain.schema.Document]) –
kwargs (Any) –
Return type
Sequence[langchain.schema.Document]
abstract async atransform_documents(documents, **kwargs)[source]
Asynchronously transform a list of documents.


Asynchronously transform a list of documents.
Parameters
documents (Sequence[langchain.schema.Document]) –
kwargs (Any) –
Return type
Sequence[langchain.schema.Document]


Chains
Chains are easily reusable components which can be linked together.
class langchain.chains.APIChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, api_request_chain, api_answer_chain, requests_wrapper, api_docs, question_key='question', output_key='output')[source]
Bases: langchain.chains.base.Chain
Chain that makes API calls and summarizes the responses to answer a question.
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_answer_chain (langchain.chains.llm.LLMChain) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
api_docs (str) –
question_key (str) –
output_key (str) –
Return type
None
attribute api_answer_chain: LLMChain [Required]
attribute api_docs: str [Required]
attribute api_request_chain: LLMChain [Required]
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


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 requests_wrapper: TextRequestsWrapper [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.


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


Parameters
kwargs (Any) –
Return type
Dict
classmethod from_llm_and_api_docs(llm, api_docs, headers=None, api_url_prompt=PromptTemplate(input_variables=['api_docs', 'question'], output_parser=None, partial_variables={}, template='You are given the below API Documentation:\n{api_docs}\nUsing this documentation, generate the full API url to call for answering the user question.\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\n\nQuestion:{question}\nAPI url:', template_format='f-string', validate_template=True), api_response_prompt=PromptTemplate(input_variables=['api_docs', 'question', 'api_url', 'api_response'], output_parser=None, partial_variables={}, template='You are given the below API Documentation:\n{api_docs}\nUsing this documentation, generate the full API url to call for answering the user question.\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\n\nQuestion:{question}\nAPI url: {api_url}\n\nHere is the response from the API:\n\n{api_response}\n\nSummarize this response to answer the original question.\n\nSummary:', template_format='f-string', validate_template=True), **kwargs)[source]
Load chain from just an LLM and the api docs.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
api_docs (str) –
headers (Optional[dict]) –
api_url_prompt (langchain.prompts.base.BasePromptTemplate) –


api_url_prompt (langchain.prompts.base.BasePromptTemplate) –
api_response_prompt (langchain.prompts.base.BasePromptTemplate) –
kwargs (Any) –
Return type
langchain.chains.api.base.APIChain
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]


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.AnalyzeDocumentChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_document', text_splitter=None, combine_docs_chain)[source]
Bases: langchain.chains.base.Chain
Chain that splits documents, then analyzes it in pieces.
Parameters
memory (Optional[langchain.schema.BaseMemory]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
verbose (bool) –
tags (Optional[List[str]]) –
input_key (str) –
text_splitter (langchain.text_splitter.TextSplitter) –
combine_docs_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) –
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.


Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
attribute combine_docs_chain: langchain.chains.combine_documents.base.BaseCombineDocumentsChain [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 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: langchain.text_splitter.TextSplitter [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_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.


property lc_serializable: bool
Return whether or not the class is serializable.
class langchain.chains.ChatVectorDBChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_docs_chain, question_generator, output_key='answer', return_source_documents=False, return_generated_question=False, get_chat_history=None, vectorstore, top_k_docs_for_context=4, search_kwargs=None)[source]
Bases: langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain
Chain for chatting with a vector database.
Parameters
memory (Optional[langchain.schema.BaseMemory]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
verbose (bool) –
tags (Optional[List[str]]) –
combine_docs_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) –
question_generator (langchain.chains.llm.LLMChain) –
output_key (str) –
return_source_documents (bool) –
return_generated_question (bool) –
get_chat_history (Optional[Callable[[Union[Tuple[str, str], langchain.schema.BaseMessage]], str]]) –
vectorstore (langchain.vectorstores.base.VectorStore) –
top_k_docs_for_context (int) –
search_kwargs (dict) –
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,


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_docs_chain: BaseCombineDocumentsChain [Required]
attribute get_chat_history: Optional[Callable[[CHAT_TURN_TYPE], str]] = None
Return the source 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 output_key: str = 'answer'
attribute question_generator: LLMChain [Required]
attribute return_generated_question: bool = False
attribute return_source_documents: bool = False
attribute search_kwargs: dict [Optional]
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 top_k_docs_for_context: int = 4
attribute vectorstore: VectorStore [Required]
attribute verbose: bool [Optional]
Whether or not run in verbose mode. In verbose mode, some intermediate logs
will be printed to the console. Defaults to langchain.verbose value.
async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False)


Run the logic of this chain and add to output if desired.
Parameters
inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects
only one param.
return_only_outputs (bool) – boolean for whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will
use the callbacks provided to the chain.
include_run_info (bool) – Whether to include run info in the response. Defaults
to False.
tags (Optional[List[str]]) –
Return type
Dict[str, Any]
apply(input_list, callbacks=None)
Call the chain on all inputs in the list.
Parameters
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type
List[Dict[str, str]]
async arun(*args, callbacks=None, tags=None, **kwargs)
Run the chain as text in, text out or multiple variables, text out.
Parameters
args (Any) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
tags (Optional[List[str]]) –
kwargs (Any) –
Return type
str
dict(**kwargs)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict


Parameters
kwargs (Any) –
Return type
Dict
classmethod from_llm(llm, vectorstore, condense_question_prompt=PromptTemplate(input_variables=['chat_history', 'question'], output_parser=None, partial_variables={}, template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\n\nChat History:\n{chat_history}\nFollow Up Input: {question}\nStandalone question:', template_format='f-string', validate_template=True), chain_type='stuff', combine_docs_chain_kwargs=None, callbacks=None, **kwargs)[source]
Load chain from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
vectorstore (langchain.vectorstores.base.VectorStore) –
condense_question_prompt (langchain.prompts.base.BasePromptTemplate) –
chain_type (str) –
combine_docs_chain_kwargs (Optional[Dict]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain
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


Run the chain as text in, text out or multiple variables, text out.
Parameters
args (Any) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
tags (Optional[List[str]]) –
kwargs (Any) –
Return type
str
save(file_path)
Save the chain.
Parameters
file_path (Union[pathlib.Path, str]) – Path to file to save the chain to.
Return type
None
Example:
.. code-block:: python
chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property input_keys: List[str]
Input keys.
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.ConstitutionalChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, chain, constitutional_principles, critique_chain, revision_chain, return_intermediate_steps=False)[source]
Bases: langchain.chains.base.Chain


Bases: langchain.chains.base.Chain
Chain for applying constitutional principles.
Example
from langchain.llms import OpenAI
from langchain.chains import LLMChain, ConstitutionalChain
from langchain.chains.constitutional_ai.models                 import ConstitutionalPrinciple
llm = OpenAI()
qa_prompt = PromptTemplate(
    template="Q: {question} A:",
    input_variables=["question"],
)
qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
constitutional_chain = ConstitutionalChain.from_llm(
    llm=llm,
    chain=qa_chain,
    constitutional_principles=[
        ConstitutionalPrinciple(
            critique_request="Tell if this answer is good.",
            revision_request="Give a better answer.",
        )
    ],
)
constitutional_chain.run(question="What is the meaning of life?")
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]]) –
chain (langchain.chains.llm.LLMChain) –
constitutional_principles (List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple]) –
critique_chain (langchain.chains.llm.LLMChain) –
revision_chain (langchain.chains.llm.LLMChain) –
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.


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 chain: langchain.chains.llm.LLMChain [Required]
attribute constitutional_principles: List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple] [Required]
attribute critique_chain: langchain.chains.llm.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 return_intermediate_steps: bool = False
attribute revision_chain: langchain.chains.llm.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.


classmethod from_llm(llm, chain, critique_prompt=FewShotPromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request'], output_parser=None, partial_variables={}, examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know


are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but


I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.", 'critique': "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are


Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", 'revision': 'No revisions needed.'}], example_selector=None, example_prompt=PromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request', 'critique'], output_parser=None, partial_variables={}, template='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}', template_format='f-string', validate_template=True), suffix='Human: {input_prompt}\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique:', example_separator='\n === \n', prefix="Below is a conversation between a human and an AI model. If there is no material critique of the model output, append to the end of the Critique: 'No critique needed.' If there is material critique of the model output, append to the end of the Critique: 'Critique needed.'", template_format='f-string', validate_template=True), revision_prompt=FewShotPromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request', 'critique', 'revision_request'], output_parser=None, partial_variables={}, examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be


toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'Yes, I think it is absolutely unethical to have


harmful assumptions from the human.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly


I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision_request': 'Please rewrite the model response. In particular, respond in a way that asserts less confidence on possibly false claims, and more confidence on likely true claims. Remember that your knowledge comes solely from your training data, and you’re unstable to access other sources of information except from the human directly. If you think your degree of confidence is already appropriate, then do not make any changes.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.", 'critique': "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no


Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", 'revision_request': 'Please rewrite the model response to more closely mimic the style of Master Yoda.', 'revision': 'No revisions needed.'}], example_selector=None, example_prompt=PromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request', 'critique'], output_parser=None, partial_variables={}, template='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}', template_format='f-string', validate_template=True), suffix='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}\n\nIf the critique does not identify anything worth changing, ignore the Revision Request and do not make any revisions. Instead, return "No revisions needed".\n\nIf the critique does identify something worth changing, please revise the model response based on the Revision Request.\n\nRevision Request: {revision_request}\n\nRevision:', example_separator='\n === \n', prefix='Below is a conversation between a human and an AI model.', template_format='f-string', validate_template=True), **kwargs)[source]


Create a chain from an LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
chain (langchain.chains.llm.LLMChain) –
critique_prompt (langchain.prompts.base.BasePromptTemplate) –
revision_prompt (langchain.prompts.base.BasePromptTemplate) –
kwargs (Any) –
Return type
langchain.chains.constitutional_ai.base.ConstitutionalChain
classmethod get_principles(names=None)[source]
Parameters
names (Optional[List[str]]) –
Return type
List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple]
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


chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property input_keys: List[str]
Defines the input keys.
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]
Defines the output keys.
class langchain.chains.ConversationChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n\nCurrent conversation:\n{history}\nHuman: {input}\nAI:', template_format='f-string', validate_template=True), llm, output_key='response', output_parser=None, return_final_only=True, llm_kwargs=None, input_key='input')[source]
Bases: langchain.chains.llm.LLMChain


Bases: langchain.chains.llm.LLMChain
Chain to have a conversation and load context from memory.
Example
from langchain import ConversationChain, OpenAI
conversation = ConversationChain(llm=OpenAI())
Parameters
memory (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]]) –
prompt (langchain.prompts.base.BasePromptTemplate) –
llm (langchain.base_language.BaseLanguageModel) –
output_key (str) –
output_parser (langchain.schema.BaseLLMOutputParser) –
return_final_only (bool) –
llm_kwargs (dict) –
input_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 llm: BaseLanguageModel [Required]
Language model to call.
attribute llm_kwargs: dict [Optional]
attribute memory: langchain.schema.BaseMemory [Optional]
Default memory store.
attribute output_parser: BaseLLMOutputParser [Optional]
Output parser to use.
Defaults to one that takes the most likely string but does not change it
otherwise.


Defaults to one that takes the most likely string but does not change it
otherwise.
attribute prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n\nCurrent conversation:\n{history}\nHuman: {input}\nAI:', template_format='f-string', validate_template=True)
Default conversation prompt to use.
attribute return_final_only: bool = True
Whether to return only the final parsed result. Defaults to True.
If false, will return a bunch of extra information about the generation.
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 aapply(input_list, callbacks=None)
Utilize the LLM generate method for speed gains.
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 aapply_and_parse(input_list, callbacks=None)
Call apply and then parse the results.
Parameters
input_list (List[Dict[str, Any]]) –


Parameters
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type
Sequence[Union[str, List[str], Dict[str, str]]]
async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False)
Run the logic of this chain and add to output if desired.
Parameters
inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects
only one param.
return_only_outputs (bool) – boolean for whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will
use the callbacks provided to the chain.
include_run_info (bool) – Whether to include run info in the response. Defaults
to False.
tags (Optional[List[str]]) –
Return type
Dict[str, Any]
async agenerate(input_list, run_manager=None)
Generate LLM result from inputs.
Parameters
input_list (List[Dict[str, Any]]) –
run_manager (Optional[langchain.callbacks.manager.AsyncCallbackManagerForChainRun]) –
Return type
langchain.schema.LLMResult
apply(input_list, callbacks=None)
Utilize the LLM generate method for speed gains.
Parameters
input_list (List[Dict[str, Any]]) –


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]]
apply_and_parse(input_list, callbacks=None)
Call apply and then parse the results.
Parameters
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type
Sequence[Union[str, List[str], Dict[str, str]]]
async apredict(callbacks=None, **kwargs)
Format prompt with kwargs and pass to LLM.
Parameters
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to pass to LLMChain
**kwargs – Keys to pass to prompt template.
kwargs (Any) –
Returns
Completion from LLM.
Return type
str
Example
completion = llm.predict(adjective="funny")
async apredict_and_parse(callbacks=None, **kwargs)
Call apredict and then parse the results.
Parameters
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
Union[str, List[str], Dict[str, str]]
async aprep_prompts(input_list, run_manager=None)
Prepare prompts from inputs.
Parameters
input_list (List[Dict[str, Any]]) –
run_manager (Optional[langchain.callbacks.manager.AsyncCallbackManagerForChainRun]) –
Return type
Tuple[List[langchain.schema.PromptValue], Optional[List[str]]]


Return type
Tuple[List[langchain.schema.PromptValue], Optional[List[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
create_outputs(llm_result)
Create outputs from response.
Parameters
llm_result (langchain.schema.LLMResult) –
Return type
List[Dict[str, Any]]
dict(**kwargs)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict
classmethod from_string(llm, template)
Create LLMChain from LLM and template.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
template (str) –
Return type
langchain.chains.llm.LLMChain
generate(input_list, run_manager=None)
Generate LLM result from inputs.
Parameters
input_list (List[Dict[str, Any]]) –
run_manager (Optional[langchain.callbacks.manager.CallbackManagerForChainRun]) –
Return type
langchain.schema.LLMResult
predict(callbacks=None, **kwargs)
Format prompt with kwargs and pass to LLM.
Parameters
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to pass to LLMChain
**kwargs – Keys to pass to prompt template.
kwargs (Any) –
Returns
Completion from LLM.
Return type
str
Example


Returns
Completion from LLM.
Return type
str
Example
completion = llm.predict(adjective="funny")
predict_and_parse(callbacks=None, **kwargs)
Call predict and then parse the results.
Parameters
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
Union[str, List[str], Dict[str, Any]]
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]
prep_prompts(input_list, run_manager=None)
Prepare prompts from inputs.
Parameters
input_list (List[Dict[str, Any]]) –
run_manager (Optional[langchain.callbacks.manager.CallbackManagerForChainRun]) –
Return type
Tuple[List[langchain.schema.PromptValue], Optional[List[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:


Return type
None
Example:
.. code-block:: python
chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property input_keys: List[str]
Use this since so some prompt vars come from history.
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.ConversationalRetrievalChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, combine_docs_chain, question_generator, output_key='answer', return_source_documents=False, return_generated_question=False, get_chat_history=None, retriever, max_tokens_limit=None)[source]
Bases: langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain
Chain for chatting with an index.
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) –


verbose (bool) –
tags (Optional[List[str]]) –
combine_docs_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) –
question_generator (langchain.chains.llm.LLMChain) –
output_key (str) –
return_source_documents (bool) –
return_generated_question (bool) –
get_chat_history (Optional[Callable[[Union[Tuple[str, str], langchain.schema.BaseMessage]], str]]) –
retriever (langchain.schema.BaseRetriever) –
max_tokens_limit (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 combine_docs_chain: BaseCombineDocumentsChain [Required]
attribute get_chat_history: Optional[Callable[[CHAT_TURN_TYPE], str]] = None
Return the source documents.
attribute max_tokens_limit: Optional[int] = None
If set, restricts the docs to return from store based on tokens, enforced only
for StuffDocumentChain
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.


There are many different types of memory - please see memory docs
for the full catalog.
attribute output_key: str = 'answer'
attribute question_generator: LLMChain [Required]
attribute retriever: BaseRetriever [Required]
Index to connect to.
attribute return_generated_question: bool = False
attribute return_source_documents: 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.


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, retriever, condense_question_prompt=PromptTemplate(input_variables=['chat_history', 'question'], output_parser=None, partial_variables={}, template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\n\nChat History:\n{chat_history}\nFollow Up Input: {question}\nStandalone question:', template_format='f-string', validate_template=True), chain_type='stuff', verbose=False, condense_question_llm=None, combine_docs_chain_kwargs=None, callbacks=None, **kwargs)[source]
Load chain from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
retriever (langchain.schema.BaseRetriever) –
condense_question_prompt (langchain.prompts.base.BasePromptTemplate) –


condense_question_prompt (langchain.prompts.base.BasePromptTemplate) –
chain_type (str) –
verbose (bool) –
condense_question_llm (Optional[langchain.base_language.BaseLanguageModel]) –
combine_docs_chain_kwargs (Optional[Dict]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain
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 input_keys: List[str]
Input keys.
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.FlareChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, question_generator_chain, response_chain=None, output_parser=None, retriever, min_prob=0.2, min_token_gap=5, num_pad_tokens=2, max_iter=10, start_with_retrieval=True)[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]]) –
question_generator_chain (langchain.chains.flare.base.QuestionGeneratorChain) –
response_chain (langchain.chains.flare.base._ResponseChain) –
output_parser (langchain.chains.flare.prompts.FinishedOutputParser) –
retriever (langchain.schema.BaseRetriever) –


retriever (langchain.schema.BaseRetriever) –
min_prob (float) –
min_token_gap (int) –
num_pad_tokens (int) –
max_iter (int) –
start_with_retrieval (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 max_iter: int = 10
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 min_prob: float = 0.2
attribute min_token_gap: int = 5
attribute num_pad_tokens: int = 2
attribute output_parser: FinishedOutputParser [Optional]
attribute question_generator_chain: QuestionGeneratorChain [Required]
attribute response_chain: _ResponseChain [Optional]
attribute retriever: BaseRetriever [Required]
attribute start_with_retrieval: bool = True
attribute tags: Optional[List[str]] = None
Optional list of tags associated with the chain. Defaults to 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]]


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, max_generation_len=32, **kwargs)[source]
Parameters
llm (langchain.base_language.BaseLanguageModel) –
max_generation_len (int) –
kwargs (Any) –
Return type
langchain.chains.flare.base.FlareChain
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


Return type
str
save(file_path)
Save the chain.
Parameters
file_path (Union[pathlib.Path, str]) – Path to file to save the chain to.
Return type
None
Example:
.. code-block:: python
chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property input_keys: List[str]
Input keys this chain expects.
property lc_attributes: Dict
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool
Return whether or not the class is serializable.
property output_keys: List[str]
Output keys this chain expects.
class langchain.chains.GraphCypherQAChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, graph, cypher_generation_chain, qa_chain, input_key='query', output_key='result', top_k=10, return_intermediate_steps=False, return_direct=False)[source]
Bases: langchain.chains.base.Chain
Chain for question-answering against a graph by generating Cypher statements.
Parameters
memory (Optional[langchain.schema.BaseMemory]) –


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.neo4j_graph.Neo4jGraph) –
cypher_generation_chain (langchain.chains.llm.LLMChain) –
qa_chain (langchain.chains.llm.LLMChain) –
input_key (str) –
output_key (str) –
top_k (int) –
return_intermediate_steps (bool) –
return_direct (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 cypher_generation_chain: LLMChain [Required]
attribute graph: Neo4jGraph [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 qa_chain: LLMChain [Required]


for the full catalog.
attribute qa_chain: LLMChain [Required]
attribute return_direct: bool = False
Whether or not to return the result of querying the graph directly.
attribute return_intermediate_steps: bool = False
Whether or not to return the intermediate steps along with the final answer.
attribute tags: Optional[List[str]] = None
Optional list of tags associated with the chain. Defaults to None
These tags will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
attribute top_k: int = 10
Number of results to return from the query
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.


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


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), cypher_prompt=PromptTemplate(input_variables=['schema', 'question'], output_parser=None, partial_variables={}, template='Task:Generate Cypher statement to query a graph database.\nInstructions:\nUse only the provided relationship types and properties in the schema.\nDo 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) –
cypher_prompt (langchain.prompts.base.BasePromptTemplate) –
kwargs (Any) –
Return type
langchain.chains.graph_qa.cypher.GraphCypherQAChain


Return type
langchain.chains.graph_qa.cypher.GraphCypherQAChain
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”]


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.GraphQAChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, graph, entity_extraction_chain, qa_chain, input_key='query', output_key='result')[source]
Bases: langchain.chains.base.Chain
Chain for question-answering against a graph.
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.networkx_graph.NetworkxEntityGraph) –
entity_extraction_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.


Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
attribute entity_extraction_chain: LLMChain [Required]
attribute graph: NetworkxEntityGraph [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 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.


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


Parameters
kwargs (Any) –
Return type
Dict
classmethod from_llm(llm, qa_prompt=PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template="Use the following knowledge triplets to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", template_format='f-string', validate_template=True), entity_prompt=PromptTemplate(input_variables=['input'], output_parser=None, partial_variables={}, template="Extract all entities from the following text. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return.\n\nEXAMPLE\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Sam.\nOutput: Langchain, Sam\nEND OF EXAMPLE\n\nBegin!\n\n{input}\nOutput:", template_format='f-string', validate_template=True), **kwargs)[source]
Initialize from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
qa_prompt (langchain.prompts.base.BasePromptTemplate) –
entity_prompt (langchain.prompts.base.BasePromptTemplate) –
kwargs (Any) –
Return type
langchain.chains.graph_qa.base.GraphQAChain
prep_inputs(inputs)
Validate and prep inputs.
Parameters


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.


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.HypotheticalDocumentEmbedder(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, base_embeddings, llm_chain)[source]
Bases: langchain.chains.base.Chain, langchain.embeddings.base.Embeddings
Generate hypothetical document for query, and then embed that.
Based on https://arxiv.org/abs/2212.10496
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]]) –
base_embeddings (langchain.embeddings.base.Embeddings) –
llm_chain (langchain.chains.llm.LLMChain) –
Return type
None
attribute base_embeddings: Embeddings [Required]
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_chain: LLMChain [Required]
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 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]


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
combine_embeddings(embeddings)[source]
Combine embeddings into final embeddings.
Parameters
embeddings (List[List[float]]) –
Return type
List[float]
dict(**kwargs)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict
embed_documents(texts)[source]
Call the base embeddings.
Parameters
texts (List[str]) –
Return type
List[List[float]]
embed_query(text)[source]
Generate a hypothetical document and embedded it.
Parameters
text (str) –
Return type
List[float]
classmethod from_llm(llm, base_embeddings, prompt_key, **kwargs)[source]
Load and use LLMChain for a specific prompt key.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
base_embeddings (langchain.embeddings.base.Embeddings) –
prompt_key (str) –
kwargs (Any) –
Return type


prompt_key (str) –
kwargs (Any) –
Return type
langchain.chains.hyde.base.HypotheticalDocumentEmbedder
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 input_keys: List[str]
Input keys for Hyde’s LLM chain.
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]


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 for Hyde’s LLM chain.
class langchain.chains.KuzuQAChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, graph, cypher_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 Cypher statements for
Kùzu.
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.kuzu_graph.KuzuGraph) –
cypher_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.


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 cypher_generation_chain: LLMChain [Required]
attribute graph: KuzuGraph [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 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