Return type
str
save(file_path)
Save the chain.
Parameters
file_path (Union[pathlib.Path, str]) – Path to file to save the chain to.
Return type
None
Example:
.. code-block:: python
chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property lc_attributes: Dict
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]


property lc_secrets: Dict[str, str]
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool
Return whether or not the class is serializable.
class langchain.chains.MapReduceDocumentsChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_documents', output_key='output_text', llm_chain, combine_document_chain, collapse_document_chain=None, document_variable_name, return_intermediate_steps=False)[source]
Bases: langchain.chains.combine_documents.base.BaseCombineDocumentsChain
Combining documents by mapping a chain over them, then combining results.
Parameters
memory (Optional[langchain.schema.BaseMemory]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –


callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
verbose (bool) –
tags (Optional[List[str]]) –
input_key (str) –
output_key (str) –
llm_chain (langchain.chains.llm.LLMChain) –
combine_document_chain (langchain.chains.combine_documents.base.BaseCombineDocumentsChain) –
collapse_document_chain (Optional[langchain.chains.combine_documents.base.BaseCombineDocumentsChain]) –
document_variable_name (str) –
return_intermediate_steps (bool) –
Return type
None
attribute callback_manager: Optional[BaseCallbackManager] = None
Deprecated, use callbacks instead.
attribute callbacks: Callbacks = None
Optional list of callback handlers (or callback manager). Defaults to None.
Callback handlers are called throughout the lifecycle of a call to a chain,


starting with on_chain_start, ending with on_chain_end or on_chain_error.
Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
attribute collapse_document_chain: Optional[BaseCombineDocumentsChain] = None
Chain to use to collapse intermediary results if needed.
If None, will use the combine_document_chain.
attribute combine_document_chain: BaseCombineDocumentsChain [Required]
Chain to use to combine results of applying llm_chain to documents.
attribute document_variable_name: str [Required]
The variable name in the llm_chain to put the documents in.
If only one variable in the llm_chain, this need not be provided.
attribute llm_chain: LLMChain [Required]
Chain to apply to each document individually.
attribute memory: Optional[BaseMemory] = None
Optional memory object. Defaults to None.


Optional memory object. Defaults to None.
Memory is a class that gets called at the start
and at the end of every chain. At the start, memory loads variables and passes
them along in the chain. At the end, it saves any returned variables.
There are many different types of memory - please see memory docs
for the full catalog.
attribute return_intermediate_steps: bool = False
Return the results of the map steps in the output.
attribute tags: Optional[List[str]] = None
Optional list of tags associated with the chain. Defaults to None
These tags will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
attribute verbose: bool [Optional]
Whether or not run in verbose mode. In verbose mode, some intermediate logs


will be printed to the console. Defaults to langchain.verbose value.
async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False)
Run the logic of this chain and add to output if desired.
Parameters
inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects
only one param.
return_only_outputs (bool) – boolean for whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will
use the callbacks provided to the chain.


use the callbacks provided to the chain.
include_run_info (bool) – Whether to include run info in the response. Defaults
to False.
tags (Optional[List[str]]) –
Return type
Dict[str, Any]
async acombine_docs(docs, callbacks=None, **kwargs)[source]
Combine documents in a map reduce manner.
Combine by mapping first chain over all documents, then reducing the results.
This reducing can be done recursively if needed (if there are many documents).
Parameters
docs (List[langchain.schema.Document]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
Tuple[str, dict]
apply(input_list, callbacks=None)
Call the chain on all inputs in the list.
Parameters
input_list (List[Dict[str, Any]]) –


callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type
List[Dict[str, str]]
async arun(*args, callbacks=None, tags=None, **kwargs)
Run the chain as text in, text out or multiple variables, text out.
Parameters
args (Any) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
tags (Optional[List[str]]) –
kwargs (Any) –
Return type
str
combine_docs(docs, token_max=3000, callbacks=None, **kwargs)[source]
Combine documents in a map reduce manner.
Combine by mapping first chain over all documents, then reducing the results.
This reducing can be done recursively if needed (if there are many documents).
Parameters


Parameters
docs (List[langchain.schema.Document]) –
token_max (int) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
Tuple[str, dict]
dict(**kwargs)
Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict
prep_inputs(inputs)
Validate and prep inputs.
Parameters
inputs (Union[Dict[str, Any], Any]) –
Return type
Dict[str, str]
prep_outputs(inputs, outputs, return_only_outputs=False)
Validate and prep outputs.
Parameters
inputs (Dict[str, str]) –
outputs (Dict[str, str]) –
return_only_outputs (bool) –
Return type
Dict[str, str]
prompt_length(docs, **kwargs)


prompt_length(docs, **kwargs)
Return the prompt length given the documents passed in.
Returns None if the method does not depend on the prompt length.
Parameters
docs (List[langchain.schema.Document]) –
kwargs (Any) –
Return type
Optional[int]
run(*args, callbacks=None, tags=None, **kwargs)
Run the chain as text in, text out or multiple variables, text out.
Parameters
args (Any) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
tags (Optional[List[str]]) –
kwargs (Any) –
Return type
str
save(file_path)
Save the chain.
Parameters
file_path (Union[pathlib.Path, str]) – Path to file to save the chain to.
Return type
None
Example:


Return type
None
Example:
.. code-block:: python
chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property lc_attributes: Dict
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}


property lc_serializable: bool
Return whether or not the class is serializable.
class langchain.chains.RefineDocumentsChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, input_key='input_documents', output_key='output_text', initial_llm_chain, refine_llm_chain, document_variable_name, initial_response_name, document_prompt=None, return_intermediate_steps=False)[source]
Bases: langchain.chains.combine_documents.base.BaseCombineDocumentsChain
Combine documents by doing a first pass and then refining on more documents.
Parameters
memory (Optional[langchain.schema.BaseMemory]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
verbose (bool) –
tags (Optional[List[str]]) –


tags (Optional[List[str]]) –
input_key (str) –
output_key (str) –
initial_llm_chain (langchain.chains.llm.LLMChain) –
refine_llm_chain (langchain.chains.llm.LLMChain) –
document_variable_name (str) –
initial_response_name (str) –
document_prompt (langchain.prompts.base.BasePromptTemplate) –
return_intermediate_steps (bool) –
Return type
None
attribute callback_manager: Optional[BaseCallbackManager] = None
Deprecated, use callbacks instead.
attribute callbacks: Callbacks = None
Optional list of callback handlers (or callback manager). Defaults to None.
Callback handlers are called throughout the lifecycle of a call to a chain,
starting with on_chain_start, ending with on_chain_end or on_chain_error.


Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
attribute document_prompt: BasePromptTemplate [Optional]
Prompt to use to format each document.
attribute document_variable_name: str [Required]
The variable name in the initial_llm_chain to put the documents in.
If only one variable in the initial_llm_chain, this need not be provided.
attribute initial_llm_chain: LLMChain [Required]
LLM chain to use on initial document.
attribute initial_response_name: str [Required]
The variable name to format the initial response in when refining.
attribute memory: Optional[BaseMemory] = None
Optional memory object. Defaults to None.
Memory is a class that gets called at the start
and at the end of every chain. At the start, memory loads variables and passes


them along in the chain. At the end, it saves any returned variables.
There are many different types of memory - please see memory docs
for the full catalog.
attribute refine_llm_chain: LLMChain [Required]
LLM chain to use when refining.
attribute return_intermediate_steps: bool = False
Return the results of the refine steps in the output.
attribute tags: Optional[List[str]] = None
Optional list of tags associated with the chain. Defaults to None
These tags will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
attribute verbose: bool [Optional]
Whether or not run in verbose mode. In verbose mode, some intermediate logs
will be printed to the console. Defaults to langchain.verbose value.


async acall(inputs, return_only_outputs=False, callbacks=None, *, tags=None, include_run_info=False)
Run the logic of this chain and add to output if desired.
Parameters
inputs (Union[Dict[str, Any], Any]) – Dictionary of inputs, or single input if chain expects
only one param.
return_only_outputs (bool) – boolean for whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) – Callbacks to use for this chain run. If not provided, will
use the callbacks provided to the chain.
include_run_info (bool) – Whether to include run info in the response. Defaults
to False.


to False.
tags (Optional[List[str]]) –
Return type
Dict[str, Any]
async acombine_docs(docs, callbacks=None, **kwargs)[source]
Combine by mapping first chain over all, then stuffing into final chain.
Parameters
docs (List[langchain.schema.Document]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
Tuple[str, dict]
apply(input_list, callbacks=None)
Call the chain on all inputs in the list.
Parameters
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Return type
List[Dict[str, str]]


List[Dict[str, str]]
async arun(*args, callbacks=None, tags=None, **kwargs)
Run the chain as text in, text out or multiple variables, text out.
Parameters
args (Any) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
tags (Optional[List[str]]) –
kwargs (Any) –
Return type
str
combine_docs(docs, callbacks=None, **kwargs)[source]
Combine by mapping first chain over all, then stuffing into final chain.
Parameters
docs (List[langchain.schema.Document]) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
kwargs (Any) –
Return type
Tuple[str, dict]
dict(**kwargs)
Return dictionary representation of chain.


Return dictionary representation of chain.
Parameters
kwargs (Any) –
Return type
Dict
prep_inputs(inputs)
Validate and prep inputs.
Parameters
inputs (Union[Dict[str, Any], Any]) –
Return type
Dict[str, str]
prep_outputs(inputs, outputs, return_only_outputs=False)
Validate and prep outputs.
Parameters
inputs (Dict[str, str]) –
outputs (Dict[str, str]) –
return_only_outputs (bool) –
Return type
Dict[str, str]
prompt_length(docs, **kwargs)
Return the prompt length given the documents passed in.
Returns None if the method does not depend on the prompt length.
Parameters
docs (List[langchain.schema.Document]) –
kwargs (Any) –
Return type
Optional[int]
run(*args, callbacks=None, tags=None, **kwargs)


Run the chain as text in, text out or multiple variables, text out.
Parameters
args (Any) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
tags (Optional[List[str]]) –
kwargs (Any) –
Return type
str
save(file_path)
Save the chain.
Parameters
file_path (Union[pathlib.Path, str]) – Path to file to save the chain to.
Return type
None
Example:
.. code-block:: python
chain.save(file_path=”path/chain.yaml”)
to_json()
Return type
Union[langchain.load.serializable.SerializedConstructor, langchain.load.serializable.SerializedNotImplemented]
to_json_not_implemented()
Return type
langchain.load.serializable.SerializedNotImplemented
property lc_attributes: Dict


property lc_attributes: Dict
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool
Return whether or not the class is serializable.


Agent Toolkits
Agent toolkits.


langchain.agents.agent_toolkits.create_json_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to interact with JSON.\nYour goal is to return a final answer by interacting with the JSON.\nYou have access to the following tools which help you learn more about the JSON you are interacting with.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nDo not make up any information that is not contained in the JSON.\nYour input to the tools should be in the form of `data["key"][0]` where `data` is the JSON blob you are interacting with, and the syntax used is Python. \nYou should only use keys that you know for a fact exist. You must validate that a key exists by seeing it previously when calling `json_spec_list_keys`. \nIf you have not seen a key in one of those responses, you cannot use


key in one of those responses, you cannot use it.\nYou should only add one key at a time to the path. You cannot add multiple keys at once.\nIf you encounter a "KeyError", go back to the previous key, look at the available keys, and try again.\n\nIf the question does not seem to be related to the JSON, just return "I don\'t know" as the answer.\nAlways begin your interaction with the `json_spec_list_keys` tool with input "data" to see what keys exist in the JSON.\n\nNote that sometimes the value at a given path is large. In this case, you will get an error "Value is a large dictionary, should explore its keys directly".\nIn this case, you should ALWAYS follow up by using the `json_spec_list_keys` tool to see what keys exist at that path.\nDo not simply refer the user to the JSON or a section of the JSON, as


the JSON or a section of the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it.\n', suffix='Begin!"\n\nQuestion: {input}\nThought: I should look at the keys that exist in data to see what I have access to\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, verbose=False, agent_executor_kwargs=None, **kwargs)[source]


Construct a json agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (langchain.agents.agent_toolkits.json.toolkit.JsonToolkit) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –
suffix (str) –
format_instructions (str) –
input_variables (Optional[List[str]]) –
verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent_toolkits.create_sql_agent(llm, toolkit, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, prefix='You are an agent designed to interact with a SQL database.\nGiven an input question, create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.\nUnless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\nYou can order the results by a relevant column to return the most interesting examples in the database.\nNever query for all the columns from a specific table, only ask for the relevant columns given the question.\nYou have access to tools for interacting with the database.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nYou MUST double check your query before executing it. If you get an error while


before executing it. If you get an error while executing a query, rewrite the query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix=None, format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, top_k=10, max_iterations=15, max_execution_time=None,


max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, **kwargs)[source]


Construct a sql agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit) –
agent_type (langchain.agents.agent_types.AgentType) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –
suffix (Optional[str]) –
format_instructions (str) –
input_variables (Optional[List[str]]) –
top_k (int) –
max_iterations (Optional[int]) –
max_execution_time (Optional[float]) –
early_stopping_method (str) –
verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent_toolkits.create_openapi_agent(llm, toolkit, callback_manager=None, prefix="You are an agent designed to answer questions by making web requests to an API given the openapi spec.\n\nIf the question does not seem related to the API, return I don't know. Do not make up an answer.\nOnly use information provided by the tools to construct your response.\n\nFirst, find the base URL needed to make the request.\n\nSecond, find the relevant paths needed to answer the question. Take note that, sometimes, you might need to make more than one request to more than one path to answer the question.\n\nThird, find the required parameters needed to make the request. For GET requests, these are usually URL parameters and for POST requests, these are request body parameters.\n\nFourth, make the requests needed to answer the question. Ensure that you are sending the correct parameters to the request by checking which parameters are


correct parameters to the request by checking which parameters are required. For parameters with a fixed set of values, please use the spec to look at which values are allowed.\n\nUse the exact parameter names as listed in the spec, do not make up any names or abbreviate the names of parameters.\nIf you get a not found error, ensure that you are using a path that actually exists in the spec.\n", suffix='Begin!\n\nQuestion: {input}\nThought: I should explore the spec to find the base url for the API.\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N


Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, return_intermediate_steps=False, agent_executor_kwargs=None, **kwargs)[source]


Construct a json agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –
suffix (str) –
format_instructions (str) –
input_variables (Optional[List[str]]) –
max_iterations (Optional[int]) –
max_execution_time (Optional[float]) –
early_stopping_method (str) –
verbose (bool) –
return_intermediate_steps (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent_toolkits.create_pbi_agent(llm, toolkit, powerbi=None, callback_manager=None, prefix='You are an agent designed to help users interact with a PowerBI Dataset.\n\nAgent has access to a tool that can write a query based on the question and then run those against PowerBI, Microsofts business intelligence tool. The questions from the users should be interpreted as related to the dataset that is available and not general questions about the world. If the question does not seem related to the dataset, just return "This does not appear to be part of this dataset." as the answer.\n\nGiven an input question, ask to run the questions against the dataset, then look at the results and return the answer, the answer should be a complete sentence that answers the question, if multiple rows are asked find a way to write that in a easily readable format for a human, also make sure to represent numbers in readable ways, like 1M instead of


in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix='Begin!\n\nQuestion: {input}\nThought: I can first ask which tables I have, then how each table is defined and then ask the query tool the question I need, and finally create a nice sentence that answers the question.\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer


the final answer\nFinal Answer: the final answer to the original input question', examples=None, input_variables=None, top_k=10, verbose=False, agent_executor_kwargs=None, **kwargs)[source]


Construct a pbi agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (Optional[langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit]) –
powerbi (Optional[langchain.utilities.powerbi.PowerBIDataset]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –
suffix (str) –
format_instructions (str) –
examples (Optional[str]) –
input_variables (Optional[List[str]]) –
top_k (int) –
verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent_toolkits.create_pbi_chat_agent(llm, toolkit, powerbi=None, callback_manager=None, output_parser=None, prefix='Assistant is a large language model built to help users interact with a PowerBI Dataset.\n\nAssistant has access to a tool that can write a query based on the question and then run those against PowerBI, Microsofts business intelligence tool. The questions from the users should be interpreted as related to the dataset that is available and not general questions about the world. If the question does not seem related to the dataset, just return "This does not appear to be part of this dataset." as the answer.\n\nGiven an input question, ask to run the questions against the dataset, then look at the results and return the answer, the answer should be a complete sentence that answers the question, if multiple rows are asked find a way to write that in a easily readable format for a human, also make sure to represent numbers in readable


human, also make sure to represent numbers in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix="TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}\n", examples=None, input_variables=None, memory=None, top_k=10, verbose=False, agent_executor_kwargs=None, **kwargs)[source]


Construct a pbi agent from an Chat LLM and tools.
If you supply only a toolkit and no powerbi dataset, the same LLM is used for both.
Parameters
llm (langchain.chat_models.base.BaseChatModel) –
toolkit (Optional[langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit]) –
powerbi (Optional[langchain.utilities.powerbi.PowerBIDataset]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) –
prefix (str) –
suffix (str) –
examples (Optional[str]) –
input_variables (Optional[List[str]]) –
memory (Optional[langchain.memory.chat_memory.BaseChatMemory]) –
top_k (int) –
verbose (bool) –


verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent.AgentExecutor
langchain.agents.agent_toolkits.create_python_agent(llm, tool, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, verbose=False, prefix='You are an agent designed to write and execute python code to answer questions.\nYou have access to a python REPL, which you can use to execute python code.\nIf you get an error, debug your code and try again.\nOnly use the output of your code to answer the question. \nYou might know the answer without running any code, but you should still run the code to get the answer.\nIf it does not seem like you can write code to answer the question, just return "I don\'t know" as the answer.\n', agent_executor_kwargs=None, **kwargs)[source]
Construct a python agent from an LLM and tool.
Parameters
llm (langchain.base_language.BaseLanguageModel) –


tool (langchain.tools.python.tool.PythonREPLTool) –
agent_type (langchain.agents.agent_types.AgentType) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
verbose (bool) –
prefix (str) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent.AgentExecutor
langchain.agents.agent_toolkits.create_vectorstore_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to answer questions about sets of documents.\nYou have access to tools for interacting with the documents, and the inputs to the tools are questions.\nSometimes, you will be asked to provide sources for your questions, in which case you should use the appropriate tool to do so.\nIf the question does not seem relevant to any of the tools provided, just return "I don\'t know" as the answer.\n', verbose=False, agent_executor_kwargs=None, **kwargs)[source]
Construct a vectorstore agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit) –


callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –
verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor
class langchain.agents.agent_toolkits.JsonToolkit(*, spec)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with a JSON spec.
Parameters
spec (langchain.tools.json.tool.JsonSpec) –
Return type
None
attribute spec: langchain.tools.json.tool.JsonSpec [Required]
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.SQLDatabaseToolkit(*, db, llm)[source]


Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with SQL databases.
Parameters
db (langchain.sql_database.SQLDatabase) –
llm (langchain.base_language.BaseLanguageModel) –
Return type
None
attribute db: langchain.sql_database.SQLDatabase [Required]
attribute llm: langchain.base_language.BaseLanguageModel [Required]
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
property dialect: str
Return string representation of dialect to use.
class langchain.agents.agent_toolkits.SparkSQLToolkit(*, db, llm)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with Spark SQL.
Parameters
db (langchain.utilities.spark_sql.SparkSQL) –


llm (langchain.base_language.BaseLanguageModel) –
Return type
None
attribute db: langchain.utilities.spark_sql.SparkSQL [Required]
attribute llm: langchain.base_language.BaseLanguageModel [Required]
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.NLAToolkit(*, nla_tools)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Natural Language API Toolkit Definition.
Parameters
nla_tools (Sequence[langchain.agents.agent_toolkits.nla.tool.NLATool]) –
Return type
None
attribute nla_tools: Sequence[langchain.agents.agent_toolkits.nla.tool.NLATool] [Required]
List of API Endpoint Tools.


List of API Endpoint Tools.
classmethod from_llm_and_ai_plugin(llm, ai_plugin, requests=None, verbose=False, **kwargs)[source]
Instantiate the toolkit from an OpenAPI Spec URL
Parameters
llm (langchain.base_language.BaseLanguageModel) –
ai_plugin (langchain.tools.plugin.AIPlugin) –
requests (Optional[langchain.requests.Requests]) –
verbose (bool) –
kwargs (Any) –
Return type
langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit
classmethod from_llm_and_ai_plugin_url(llm, ai_plugin_url, requests=None, verbose=False, **kwargs)[source]
Instantiate the toolkit from an OpenAPI Spec URL
Parameters
llm (langchain.base_language.BaseLanguageModel) –
ai_plugin_url (str) –
requests (Optional[langchain.requests.Requests]) –


verbose (bool) –
kwargs (Any) –
Return type
langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit
classmethod from_llm_and_spec(llm, spec, requests=None, verbose=False, **kwargs)[source]
Instantiate the toolkit by creating tools for each operation.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
spec (langchain.utilities.openapi.OpenAPISpec) –
requests (Optional[langchain.requests.Requests]) –
verbose (bool) –
kwargs (Any) –
Return type
langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit
classmethod from_llm_and_url(llm, open_api_url, requests=None, verbose=False, **kwargs)[source]
Instantiate the toolkit from an OpenAPI Spec URL
Parameters
llm (langchain.base_language.BaseLanguageModel) –


open_api_url (str) –
requests (Optional[langchain.requests.Requests]) –
verbose (bool) –
kwargs (Any) –
Return type
langchain.agents.agent_toolkits.nla.toolkit.NLAToolkit
get_tools()[source]
Get the tools for all the API operations.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.PowerBIToolkit(*, powerbi, llm, examples=None, max_iterations=5, callback_manager=None)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with PowerBI dataset.
Parameters
powerbi (langchain.utilities.powerbi.PowerBIDataset) –
llm (langchain.base_language.BaseLanguageModel) –
examples (Optional[str]) –
max_iterations (int) –


max_iterations (int) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
Return type
None
attribute callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None
attribute examples: Optional[str] = None
attribute llm: langchain.base_language.BaseLanguageModel [Required]
attribute max_iterations: int = 5
attribute powerbi: langchain.utilities.powerbi.PowerBIDataset [Required]
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.OpenAPIToolkit(*, json_agent, requests_wrapper)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with a OpenAPI api.
Parameters


Parameters
json_agent (langchain.agents.agent.AgentExecutor) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None
attribute json_agent: langchain.agents.agent.AgentExecutor [Required]
attribute requests_wrapper: langchain.requests.TextRequestsWrapper [Required]
classmethod from_llm(llm, json_spec, requests_wrapper, **kwargs)[source]
Create json agent from llm, then initialize.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
json_spec (langchain.tools.json.tool.JsonSpec) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
kwargs (Any) –
Return type
langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]


List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.VectorStoreToolkit(*, vectorstore_info, llm=None)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with a vector store.
Parameters
vectorstore_info (langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo) –
llm (langchain.base_language.BaseLanguageModel) –
Return type
None
attribute llm: langchain.base_language.BaseLanguageModel [Optional]
attribute vectorstore_info: langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo [Required]
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]


List[langchain.tools.base.BaseTool]
langchain.agents.agent_toolkits.create_vectorstore_router_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to answer questions.\nYou have access to tools for interacting with different sources, and the inputs to the tools are questions.\nYour main task is to decide which of the tools is relevant for answering question at hand.\nFor complex questions, you can break the question down into sub questions and use tools to answers the sub questions.\n', verbose=False, agent_executor_kwargs=None, **kwargs)[source]
Construct a vectorstore router agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –


prefix (str) –
verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor
class langchain.agents.agent_toolkits.VectorStoreInfo(*, vectorstore, name, description)[source]
Bases: pydantic.main.BaseModel
Information about a vectorstore.
Parameters
vectorstore (langchain.vectorstores.base.VectorStore) –
name (str) –
description (str) –
Return type
None
attribute description: str [Required]
attribute name: str [Required]
attribute vectorstore: langchain.vectorstores.base.VectorStore [Required]
class langchain.agents.agent_toolkits.VectorStoreRouterToolkit(*, vectorstores, llm=None)[source]


Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for routing between vector stores.
Parameters
vectorstores (List[langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo]) –
llm (langchain.base_language.BaseLanguageModel) –
Return type
None
attribute llm: langchain.base_language.BaseLanguageModel [Optional]
attribute vectorstores: List[langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo] [Required]
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]


List[langchain.tools.base.BaseTool]
langchain.agents.agent_toolkits.create_pandas_dataframe_agent(llm, df, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, prefix=None, suffix=None, input_variables=None, verbose=False, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', agent_executor_kwargs=None, include_df_in_prompt=True, **kwargs)[source]
Construct a pandas agent from an LLM and dataframe.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
df (Any) –
agent_type (langchain.agents.agent_types.AgentType) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (Optional[str]) –
suffix (Optional[str]) –
input_variables (Optional[List[str]]) –
verbose (bool) –


verbose (bool) –
return_intermediate_steps (bool) –
max_iterations (Optional[int]) –
max_execution_time (Optional[float]) –
early_stopping_method (str) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
include_df_in_prompt (Optional[bool]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent.AgentExecutor
langchain.agents.agent_toolkits.create_spark_dataframe_agent(llm, df, callback_manager=None, prefix='\nYou are working with a spark dataframe in Python. The name of the dataframe is `df`.\nYou should use the tools below to answer the question posed of you:', suffix='\nThis is the result of `print(df.first())`:\n{df}\n\nBegin!\nQuestion: {input}\n{agent_scratchpad}', input_variables=None, verbose=False, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', agent_executor_kwargs=None, **kwargs)[source]
Construct a spark agent from an LLM and dataframe.
Parameters
llm (langchain.llms.base.BaseLLM) –
df (Any) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –


prefix (str) –
suffix (str) –
input_variables (Optional[List[str]]) –
verbose (bool) –
return_intermediate_steps (bool) –
max_iterations (Optional[int]) –
max_execution_time (Optional[float]) –
early_stopping_method (str) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent_toolkits.create_spark_sql_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to interact with Spark SQL.\nGiven an input question, create a syntactically correct Spark SQL query to run, then look at the results of the query and return the answer.\nUnless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\nYou can order the results by a relevant column to return the most interesting examples in the database.\nNever query for all the columns from a specific table, only ask for the relevant columns given the question.\nYou have access to tools for interacting with the database.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nYou MUST double check your query before executing it. If you get an error while executing a query, rewrite the query and try


while executing a query, rewrite the query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix='Begin!\n\nQuestion: {input}\nThought: I should look at the tables in the database to see what I can query.\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the


answer\nFinal Answer: the final answer to the original input question', input_variables=None, top_k=10, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, **kwargs)[source]


Construct a sql agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
toolkit (langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
prefix (str) –
suffix (str) –
format_instructions (str) –
input_variables (Optional[List[str]]) –
top_k (int) –
max_iterations (Optional[int]) –
max_execution_time (Optional[float]) –
early_stopping_method (str) –
verbose (bool) –
agent_executor_kwargs (Optional[Dict[str, Any]]) –
kwargs (Dict[str, Any]) –
Return type
langchain.agents.agent.AgentExecutor


langchain.agents.agent.AgentExecutor
langchain.agents.agent_toolkits.create_csv_agent(llm, path, pandas_kwargs=None, **kwargs)[source]
Create csv agent by loading to a dataframe and using pandas agent.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
path (Union[str, List[str]]) –
pandas_kwargs (Optional[dict]) –
kwargs (Any) –
Return type
langchain.agents.agent.AgentExecutor
class langchain.agents.agent_toolkits.ZapierToolkit(*, tools=[])[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Zapier Toolkit.
Parameters
tools (List[langchain.tools.base.BaseTool]) –
Return type
None
attribute tools: List[langchain.tools.base.BaseTool] = []


classmethod from_zapier_nla_wrapper(zapier_nla_wrapper)[source]
Create a toolkit from a ZapierNLAWrapper.
Parameters
zapier_nla_wrapper (langchain.utilities.zapier.ZapierNLAWrapper) –
Return type
langchain.agents.agent_toolkits.zapier.toolkit.ZapierToolkit
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.GmailToolkit(*, api_resource=None)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with Gmail.
Parameters
api_resource (Resource) –
Return type
None
attribute api_resource: Resource [Optional]
get_tools()[source]
Get the tools in the toolkit.
Return type


Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.JiraToolkit(*, tools=[])[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Jira Toolkit.
Parameters
tools (List[langchain.tools.base.BaseTool]) –
Return type
None
attribute tools: List[langchain.tools.base.BaseTool] = []
classmethod from_jira_api_wrapper(jira_api_wrapper)[source]
Parameters
jira_api_wrapper (langchain.utilities.jira.JiraAPIWrapper) –
Return type
langchain.agents.agent_toolkits.jira.toolkit.JiraToolkit
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.FileManagementToolkit(*, root_dir=None, selected_tools=None)[source]


Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for interacting with a Local Files.
Parameters
root_dir (Optional[str]) –
selected_tools (Optional[List[str]]) –
Return type
None
attribute root_dir: Optional[str] = None
If specified, all file operations are made relative to root_dir.
attribute selected_tools: Optional[List[str]] = None
If provided, only provide the selected tools. Defaults to all.
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.PlayWrightBrowserToolkit(*, sync_browser=None, async_browser=None)[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for web browser tools.
Parameters
sync_browser (Optional['SyncBrowser']) –


async_browser (Optional['AsyncBrowser']) –
Return type
None
attribute async_browser: Optional['AsyncBrowser'] = None
attribute sync_browser: Optional['SyncBrowser'] = None
classmethod from_browser(sync_browser=None, async_browser=None)[source]
Instantiate the toolkit.
Parameters
sync_browser (Optional[SyncBrowser]) –
async_browser (Optional[AsyncBrowser]) –
Return type
PlayWrightBrowserToolkit
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]
class langchain.agents.agent_toolkits.AzureCognitiveServicesToolkit[source]
Bases: langchain.agents.agent_toolkits.base.BaseToolkit
Toolkit for Azure Cognitive Services.
Return type
None
get_tools()[source]
Get the tools in the toolkit.
Return type
List[langchain.tools.base.BaseTool]


Retrievers
class langchain.retrievers.AmazonKendraRetriever(index_id, region_name=None, credentials_profile_name=None, top_k=3, attribute_filter=None, client=None)[source]
Bases: langchain.schema.BaseRetriever
Retriever class to query documents from Amazon Kendra Index.
Parameters
index_id (str) – Kendra index id
region_name (Optional[str]) – The aws region e.g., us-west-2.
Fallsback to AWS_DEFAULT_REGION env variable
or region specified in ~/.aws/config.
credentials_profile_name (Optional[str]) – The name of the profile in the ~/.aws/credentials
or ~/.aws/config files, which has either access keys or role information
specified. If not specified, the default credential profile or, if on an
EC2 instance, credentials from IMDS will be used.
top_k (int) – No of results to return


attribute_filter (Optional[Dict]) – Additional filtering of results based on metadata
See: https://docs.aws.amazon.com/kendra/latest/APIReference
client (Optional[Any]) – boto3 client for Kendra
Example
retriever = AmazonKendraRetriever(
    index_id="c0806df7-e76b-4bce-9b5c-d5582f6b1a03"
)
get_relevant_documents(query)[source]
Run search on Kendra index and get top k documents
Example:
.. code-block:: python
docs = retriever.get_relevant_documents(‘This is my query’)
Parameters
query (str) –
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns


Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ArxivRetriever(*, arxiv_search=None, arxiv_exceptions=None, top_k_results=3, load_max_docs=100, load_all_available_meta=False, doc_content_chars_max=4000, ARXIV_MAX_QUERY_LENGTH=300)[source]
Bases: langchain.schema.BaseRetriever, langchain.utilities.arxiv.ArxivAPIWrapper
It is effectively a wrapper for ArxivAPIWrapper.
It wraps load() to get_relevant_documents().
It uses all ArxivAPIWrapper arguments without any change.
Parameters
arxiv_search (Any) –
arxiv_exceptions (Any) –
top_k_results (int) –
load_max_docs (int) –
load_all_available_meta (bool) –
doc_content_chars_max (Optional[int]) –


ARXIV_MAX_QUERY_LENGTH (int) –
Return type
None
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.AzureCognitiveSearchRetriever(*, service_name='', index_name='', api_key='', api_version='2020-06-30', aiosession=None, content_key='content')[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Wrapper around Azure Cognitive Search.
Parameters


Wrapper around Azure Cognitive Search.
Parameters
service_name (str) –
index_name (str) –
api_key (str) –
api_version (str) –
aiosession (Optional[aiohttp.client.ClientSession]) –
content_key (str) –
Return type
None
attribute aiosession: Optional[aiohttp.client.ClientSession] = None
ClientSession, in case we want to reuse connection for better performance.
attribute api_key: str = ''
API Key. Both Admin and Query keys work, but for reading data it’s
recommended to use a Query key.
attribute api_version: str = '2020-06-30'
API version
attribute content_key: str = 'content'
Key in a retrieved result to set as the Document page_content.
attribute index_name: str = ''


attribute index_name: str = ''
Name of Index inside Azure Cognitive Search service
attribute service_name: str = ''
Name of Azure Cognitive Search service
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ChatGPTPluginRetriever(*, url, bearer_token, top_k=3, filter=None, aiosession=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Parameters


Parameters
url (str) –
bearer_token (str) –
top_k (int) –
filter (Optional[dict]) –
aiosession (Optional[aiohttp.client.ClientSession]) –
Return type
None
attribute aiosession: Optional[aiohttp.client.ClientSession] = None
attribute bearer_token: str [Required]
attribute filter: Optional[dict] = None
attribute top_k: int = 3
attribute url: str [Required]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters


Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ContextualCompressionRetriever(*, base_compressor, base_retriever)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Retriever that wraps a base retriever and compresses the results.
Parameters
base_compressor (langchain.retrievers.document_compressors.base.BaseDocumentCompressor) –
base_retriever (langchain.schema.BaseRetriever) –
Return type
None
attribute base_compressor: langchain.retrievers.document_compressors.base.BaseDocumentCompressor [Required]
Compressor for compressing retrieved documents.
attribute base_retriever: langchain.schema.BaseRetriever [Required]


Base Retriever to use for getting relevant documents.
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
Sequence of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.DataberryRetriever(datastore_url, top_k=None, api_key=None)[source]
Bases: langchain.schema.BaseRetriever
Retriever that uses the Databerry API.
Parameters
datastore_url (str) –
top_k (Optional[int]) –
api_key (Optional[str]) –


api_key (Optional[str]) –
datastore_url: str
api_key: Optional[str]
top_k: Optional[int]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ElasticSearchBM25Retriever(client, index_name)[source]
Bases: langchain.schema.BaseRetriever
Wrapper around Elasticsearch using BM25 as a retrieval method.
To connect to an Elasticsearch instance that requires login credentials,


including Elastic Cloud, use the Elasticsearch URL format
https://username:password@es_host:9243. For example, to connect to Elastic
Cloud, create the Elasticsearch URL with the required authentication details and
pass it to the ElasticVectorSearch constructor as the named parameter
elasticsearch_url.
You can obtain your Elastic Cloud URL and login credentials by logging in to the
Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and
navigating to the “Deployments” page.
To obtain your Elastic Cloud password for the default “elastic” user:
Log in to the Elastic Cloud console at https://cloud.elastic.co
Go to “Security” > “Users”
Locate the “elastic” user and click “Edit”
Click “Reset password”
Follow the prompts to reset the password
The format for Elastic Cloud URLs is


The format for Elastic Cloud URLs is
https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.
Parameters
client (Any) –
index_name (str) –
classmethod create(elasticsearch_url, index_name, k1=2.0, b=0.75)[source]
Parameters
elasticsearch_url (str) –
index_name (str) –
k1 (float) –
b (float) –
Return type
langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever
add_texts(texts, refresh_indices=True)[source]
Run more texts through the embeddings and add to the retriever.
Parameters
texts (Iterable[str]) – Iterable of strings to add to the retriever.
refresh_indices (bool) – bool to refresh ElasticSearch indices
Returns


Returns
List of ids from adding the texts into the retriever.
Return type
List[str]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.KNNRetriever(*, embeddings, index=None, texts, k=4, relevancy_threshold=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
KNN Retriever.
Parameters


KNN Retriever.
Parameters
embeddings (langchain.embeddings.base.Embeddings) –
index (Any) –
texts (List[str]) –
k (int) –
relevancy_threshold (Optional[float]) –
Return type
None
attribute embeddings: langchain.embeddings.base.Embeddings [Required]
attribute index: Any = None
attribute k: int = 4
attribute relevancy_threshold: Optional[float] = None
attribute texts: List[str] [Required]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
classmethod from_texts(texts, embeddings, **kwargs)[source]
Parameters
texts (List[str]) –


Parameters
texts (List[str]) –
embeddings (langchain.embeddings.base.Embeddings) –
kwargs (Any) –
Return type
langchain.retrievers.knn.KNNRetriever
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.LlamaIndexGraphRetriever(*, graph=None, query_configs=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Question-answering with sources over an LlamaIndex graph data structure.
Parameters
graph (Any) –
query_configs (List[Dict]) –
Return type
None
attribute graph: Any = None


attribute graph: Any = None
attribute query_configs: List[Dict] [Optional]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) –
Return type
List[langchain.schema.Document]
class langchain.retrievers.LlamaIndexRetriever(*, index=None, query_kwargs=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Question-answering with sources over an LlamaIndex data structure.
Parameters
index (Any) –
query_kwargs (Dict) –
Return type
None


Return type
None
attribute index: Any = None
attribute query_kwargs: Dict [Optional]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) –
Return type
List[langchain.schema.Document]
class langchain.retrievers.MergerRetriever(retrievers)[source]
Bases: langchain.schema.BaseRetriever
This class merges the results of multiple retrievers.
Parameters
retrievers (List[langchain.schema.BaseRetriever]) – A list of retrievers to merge.
get_relevant_documents(query)[source]


Get the relevant documents for a given query.
Parameters
query (str) – The query to search for.
Returns
A list of relevant documents.
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Asynchronously get the relevant documents for a given query.
Parameters
query (str) – The query to search for.
Returns
A list of relevant documents.
Return type
List[langchain.schema.Document]
merge_documents(query)[source]
Merge the results of the retrievers.
Parameters
query (str) – The query to search for.
Returns
A list of merged documents.
Return type
List[langchain.schema.Document]
async amerge_documents(query)[source]
Asynchronously merge the results of the retrievers.
Parameters
query (str) – The query to search for.
Returns
A list of merged documents.


Returns
A list of merged documents.
Return type
List[langchain.schema.Document]
class langchain.retrievers.MetalRetriever(client, params=None)[source]
Bases: langchain.schema.BaseRetriever
Retriever that uses the Metal API.
Parameters
client (Any) –
params (Optional[dict]) –
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]


List[langchain.schema.Document]
class langchain.retrievers.MilvusRetriever(embedding_function, collection_name='LangChainCollection', connection_args=None, consistency_level='Session', search_params=None)[source]
Bases: langchain.schema.BaseRetriever
Retriever that uses the Milvus API.
Parameters
embedding_function (langchain.embeddings.base.Embeddings) –
collection_name (str) –
connection_args (Optional[Dict[str, Any]]) –
consistency_level (str) –
search_params (Optional[dict]) –
add_texts(texts, metadatas=None)[source]
Add text to the Milvus store
Parameters
texts (List[str]) – The text
metadatas (List[dict]) – Metadata dicts, must line up with existing store
Return type
None
get_relevant_documents(query)[source]


Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.PineconeHybridSearchRetriever(*, embeddings, sparse_encoder=None, index=None, top_k=4, alpha=0.5)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Parameters
embeddings (langchain.embeddings.base.Embeddings) –
sparse_encoder (Any) –
index (Any) –
top_k (int) –
alpha (float) –


alpha (float) –
Return type
None
attribute alpha: float = 0.5
attribute embeddings: langchain.embeddings.base.Embeddings [Required]
attribute index: Any = None
attribute sparse_encoder: Any = None
attribute top_k: int = 4
add_texts(texts, ids=None, metadatas=None)[source]
Parameters
texts (List[str]) –
ids (Optional[List[str]]) –
metadatas (Optional[List[dict]]) –
Return type
None
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters


Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.PubMedRetriever(*, top_k_results=3, load_max_docs=25, doc_content_chars_max=2000, load_all_available_meta=False, email='your_email@example.com', base_url_esearch='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?', base_url_efetch='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?', max_retry=5, sleep_time=0.2, ARXIV_MAX_QUERY_LENGTH=300)[source]
Bases: langchain.schema.BaseRetriever, langchain.utilities.pupmed.PubMedAPIWrapper
It is effectively a wrapper for PubMedAPIWrapper.


It wraps load() to get_relevant_documents().
It uses all PubMedAPIWrapper arguments without any change.
Parameters
top_k_results (int) –
load_max_docs (int) –
doc_content_chars_max (int) –
load_all_available_meta (bool) –
email (str) –
base_url_esearch (str) –
base_url_efetch (str) –
max_retry (int) –
sleep_time (float) –
ARXIV_MAX_QUERY_LENGTH (int) –
Return type
None
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters


Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.RemoteLangChainRetriever(*, url, headers=None, input_key='message', response_key='response', page_content_key='page_content', metadata_key='metadata')[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Parameters
url (str) –
headers (Optional[dict]) –
input_key (str) –
response_key (str) –
page_content_key (str) –
metadata_key (str) –
Return type
None
attribute headers: Optional[dict] = None
attribute input_key: str = 'message'
attribute metadata_key: str = 'metadata'


attribute page_content_key: str = 'page_content'
attribute response_key: str = 'response'
attribute url: str [Required]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.SVMRetriever(*, embeddings, index=None, texts, k=4, relevancy_threshold=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
SVM Retriever.


SVM Retriever.
Parameters
embeddings (langchain.embeddings.base.Embeddings) –
index (Any) –
texts (List[str]) –
k (int) –
relevancy_threshold (Optional[float]) –
Return type
None
attribute embeddings: langchain.embeddings.base.Embeddings [Required]
attribute index: Any = None
attribute k: int = 4
attribute relevancy_threshold: Optional[float] = None
attribute texts: List[str] [Required]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
classmethod from_texts(texts, embeddings, **kwargs)[source]
Parameters
texts (List[str]) –


Parameters
texts (List[str]) –
embeddings (langchain.embeddings.base.Embeddings) –
kwargs (Any) –
Return type
langchain.retrievers.svm.SVMRetriever
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.SelfQueryRetriever(*, vectorstore, llm_chain, search_type='similarity', search_kwargs=None, structured_query_translator, verbose=False, use_original_query=False)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Retriever that wraps around a vector store and uses an LLM to generate
the vector store queries.
Parameters


the vector store queries.
Parameters
vectorstore (langchain.vectorstores.base.VectorStore) –
llm_chain (langchain.chains.llm.LLMChain) –
search_type (str) –
search_kwargs (dict) –
structured_query_translator (langchain.chains.query_constructor.ir.Visitor) –
verbose (bool) –
use_original_query (bool) –
Return type
None
attribute llm_chain: langchain.chains.llm.LLMChain [Required]
The LLMChain for generating the vector store queries.
attribute search_kwargs: dict [Optional]
Keyword arguments to pass in to the vector store search.
attribute search_type: str = 'similarity'
The search type to perform on the vector store.
attribute structured_query_translator: langchain.chains.query_constructor.ir.Visitor [Required]


Translator for turning internal query language into vectorstore search params.
attribute use_original_query: bool = False
attribute vectorstore: langchain.vectorstores.base.VectorStore [Required]
The underlying vector store from which documents will be retrieved.
attribute verbose: bool = False
Use original query instead of the revised new query from LLM
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
classmethod from_llm(llm, vectorstore, document_contents, metadata_field_info, structured_query_translator=None, chain_kwargs=None, enable_limit=False, use_original_query=False, **kwargs)[source]
Parameters
llm (langchain.base_language.BaseLanguageModel) –


vectorstore (langchain.vectorstores.base.VectorStore) –
document_contents (str) –
metadata_field_info (List[langchain.chains.query_constructor.schema.AttributeInfo]) –
structured_query_translator (Optional[langchain.chains.query_constructor.ir.Visitor]) –
chain_kwargs (Optional[Dict]) –
enable_limit (bool) –
use_original_query (bool) –
kwargs (Any) –
Return type
langchain.retrievers.self_query.base.SelfQueryRetriever
get_relevant_documents(query, callbacks=None)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
Returns
List of relevant documents
Return type
List[langchain.schema.Document]


List[langchain.schema.Document]
class langchain.retrievers.TFIDFRetriever(*, vectorizer=None, docs, tfidf_array=None, k=4)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Parameters
vectorizer (Any) –
docs (List[langchain.schema.Document]) –
tfidf_array (Any) –
k (int) –
Return type
None
attribute docs: List[langchain.schema.Document] [Required]
attribute k: int = 4
attribute tfidf_array: Any = None
attribute vectorizer: Any = None
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type


Returns
List of relevant documents
Return type
List[langchain.schema.Document]
classmethod from_documents(documents, *, tfidf_params=None, **kwargs)[source]
Parameters
documents (Iterable[langchain.schema.Document]) –
tfidf_params (Optional[Dict[str, Any]]) –
kwargs (Any) –
Return type
langchain.retrievers.tfidf.TFIDFRetriever
classmethod from_texts(texts, metadatas=None, tfidf_params=None, **kwargs)[source]
Parameters
texts (Iterable[str]) –
metadatas (Optional[Iterable[dict]]) –
tfidf_params (Optional[Dict[str, Any]]) –
kwargs (Any) –
Return type
langchain.retrievers.tfidf.TFIDFRetriever
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters


Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.TimeWeightedVectorStoreRetriever(*, vectorstore, search_kwargs=None, memory_stream=None, decay_rate=0.01, k=4, other_score_keys=[], default_salience=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Retriever combining embedding similarity with recency.
Parameters
vectorstore (langchain.vectorstores.base.VectorStore) –
search_kwargs (dict) –
memory_stream (List[langchain.schema.Document]) –
decay_rate (float) –
k (int) –
other_score_keys (List[str]) –
default_salience (Optional[float]) –
Return type
None


Return type
None
attribute decay_rate: float = 0.01
The exponential decay factor used as (1.0-decay_rate)**(hrs_passed).
attribute default_salience: Optional[float] = None
The salience to assign memories not retrieved from the vector store.
None assigns no salience to documents not fetched from the vector store.
attribute k: int = 4
The maximum number of documents to retrieve in a given call.
attribute memory_stream: List[langchain.schema.Document] [Optional]
The memory_stream of documents to search through.
attribute other_score_keys: List[str] = []
Other keys in the metadata to factor into the score, e.g. ‘importance’.
attribute search_kwargs: dict [Optional]
Keyword arguments to pass to the vectorstore similarity search.


attribute vectorstore: langchain.vectorstores.base.VectorStore [Required]
The vectorstore to store documents and determine salience.
async aadd_documents(documents, **kwargs)[source]
Add documents to vectorstore.
Parameters
documents (List[langchain.schema.Document]) –
kwargs (Any) –
Return type
List[str]
add_documents(documents, **kwargs)[source]
Add documents to vectorstore.
Parameters
documents (List[langchain.schema.Document]) –
kwargs (Any) –
Return type
List[str]
async aget_relevant_documents(query)[source]
Return documents that are relevant to the query.
Parameters
query (str) –
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Return documents that are relevant to the query.
Parameters
query (str) –


Parameters
query (str) –
Return type
List[langchain.schema.Document]
get_salient_docs(query)[source]
Return documents that are salient to the query.
Parameters
query (str) –
Return type
Dict[int, Tuple[langchain.schema.Document, float]]
class langchain.retrievers.VespaRetriever(app, body, content_field, metadata_fields=None)[source]
Bases: langchain.schema.BaseRetriever
Retriever that uses the Vespa.
Parameters
app (Vespa) –
body (Dict) –
content_field (str) –
metadata_fields (Optional[Sequence[str]]) –
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type


Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents_with_filter(query, *, _filter=None)[source]
Parameters
query (str) –
_filter (Optional[str]) –
Return type
List[langchain.schema.Document]
classmethod from_params(url, content_field, *, k=None, metadata_fields=(), sources=None, _filter=None, yql=None, **kwargs)[source]
Instantiate retriever from params.
Parameters
url (str) – Vespa app URL.
content_field (str) – Field in results to return as Document page_content.


k (Optional[int]) – Number of Documents to return. Defaults to None.
metadata_fields (Sequence[str] or "*") – Fields in results to include in
document metadata. Defaults to empty tuple ().
sources (Sequence[str] or "*" or None) – Sources to retrieve
from. Defaults to None.
_filter (Optional[str]) – Document filter condition expressed in YQL.
Defaults to None.
yql (Optional[str]) – Full YQL query to be used. Should not be specified
if _filter or sources are specified. Defaults to None.
kwargs (Any) – Keyword arguments added to query body.
Return type
langchain.retrievers.vespa_retriever.VespaRetriever
class langchain.retrievers.WeaviateHybridSearchRetriever(client, index_name, text_key, alpha=0.5, k=4, attributes=None, create_schema_if_missing=True)[source]


Bases: langchain.schema.BaseRetriever
Parameters
client (Any) –
index_name (str) –
text_key (str) –
alpha (float) –
k (int) –
attributes (Optional[List[str]]) –
create_schema_if_missing (bool) –
class Config[source]
Bases: object
Configuration for this pydantic object.
extra = 'forbid'
arbitrary_types_allowed = True
add_documents(docs, **kwargs)[source]
Upload documents to Weaviate.
Parameters
docs (List[langchain.schema.Document]) –
kwargs (Any) –
Return type
List[str]
get_relevant_documents(query, where_filter=None)[source]
Look up similar documents in Weaviate.
Parameters
query (str) –


Parameters
query (str) –
where_filter (Optional[Dict[str, object]]) –
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query, where_filter=None)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
where_filter (Optional[Dict[str, object]]) –
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.WikipediaRetriever(*, wiki_client=None, top_k_results=3, lang='en', load_all_available_meta=False, doc_content_chars_max=4000)[source]
Bases: langchain.schema.BaseRetriever, langchain.utilities.wikipedia.WikipediaAPIWrapper
It is effectively a wrapper for WikipediaAPIWrapper.
It wraps load() to get_relevant_documents().


It uses all WikipediaAPIWrapper arguments without any change.
Parameters
wiki_client (Any) –
top_k_results (int) –
lang (str) –
load_all_available_meta (bool) –
doc_content_chars_max (int) –
Return type
None
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ZepRetriever(session_id, url, top_k=None)[source]


Bases: langchain.schema.BaseRetriever
A Retriever implementation for the Zep long-term memory store. Search your
user’s long-term chat history with Zep.
Note: You will need to provide the user’s session_id to use this retriever.
More on Zep:
Zep provides long-term conversation storage for LLM apps. The server stores,
summarizes, embeds, indexes, and enriches conversational AI chat
histories, and exposes them via simple, low-latency APIs.
For server installation instructions, see:
https://getzep.github.io/deployment/quickstart/
Parameters
session_id (str) –
url (str) –
top_k (Optional[int]) –
get_relevant_documents(query, metadata=None)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for


metadata (Optional[Dict]) –
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query, metadata=None)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
metadata (Optional[Dict]) –
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ZillizRetriever(embedding_function, collection_name='LangChainCollection', connection_args=None, consistency_level='Session', search_params=None)[source]
Bases: langchain.schema.BaseRetriever
Retriever that uses the Zilliz API.
Parameters
embedding_function (langchain.embeddings.base.Embeddings) –
collection_name (str) –
connection_args (Optional[Dict[str, Any]]) –


consistency_level (str) –
search_params (Optional[dict]) –
add_texts(texts, metadatas=None)[source]
Add text to the Zilliz store
Parameters
texts (List[str]) – The text
metadatas (List[dict]) – Metadata dicts, must line up with existing store
Return type
None
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]


List[langchain.schema.Document]
class langchain.retrievers.DocArrayRetriever(*, index=None, embeddings, search_field, content_field, search_type=SearchType.similarity, top_k=1, filters=None)[source]
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Retriever class for DocArray Document Indices.
Currently, supports 5 backends:
InMemoryExactNNIndex, HnswDocumentIndex, QdrantDocumentIndex,
ElasticDocIndex, and WeaviateDocumentIndex.
Parameters
index (Any) –
embeddings (langchain.embeddings.base.Embeddings) –
search_field (str) –
content_field (str) –
search_type (langchain.retrievers.docarray.SearchType) –
top_k (int) –
filters (Optional[Any]) –
Return type
None


Return type
None
index
One of the above-mentioned index instances
embeddings
Embedding model to represent text as vectors
search_field
Field to consider for searching in the documents.
Should be an embedding/vector/tensor.
content_field
Field that represents the main content in your document schema.
Will be used as a page_content. Everything else will go into metadata.
search_type
Type of search to perform (similarity / mmr)
filters
Filters applied for document retrieval.
top_k
Number of documents to return
attribute content_field: str [Required]
attribute embeddings: langchain.embeddings.base.Embeddings [Required]
attribute filters: Optional[Any] = None
attribute index: Any = None
attribute search_field: str [Required]


attribute search_type: langchain.retrievers.docarray.SearchType = SearchType.similarity
attribute top_k: int = 1
async aget_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]
Get documents relevant for a query.
Parameters
query (str) – string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
Document compressors
class langchain.retrievers.document_compressors.DocumentCompressorPipeline(*, transformers)[source]
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Document compressor that uses a pipeline of transformers.
Parameters


Parameters
transformers (List[Union[langchain.schema.BaseDocumentTransformer, langchain.retrievers.document_compressors.base.BaseDocumentCompressor]]) –
Return type
None
attribute transformers: List[Union[langchain.schema.BaseDocumentTransformer, langchain.retrievers.document_compressors.base.BaseDocumentCompressor]] [Required]
List of document filters that are chained together and run in sequence.
async acompress_documents(documents, query)[source]
Compress retrieved documents given the query context.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]
Transform a list of documents.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]


Sequence[langchain.schema.Document]
class langchain.retrievers.document_compressors.EmbeddingsFilter(*, embeddings, similarity_fn=<function cosine_similarity>, k=20, similarity_threshold=None)[source]
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Parameters
embeddings (langchain.embeddings.base.Embeddings) –
similarity_fn (Callable) –
k (Optional[int]) –
similarity_threshold (Optional[float]) –
Return type
None
attribute embeddings: langchain.embeddings.base.Embeddings [Required]
Embeddings to use for embedding document contents and queries.
attribute k: Optional[int] = 20
The number of relevant documents to return. Can be set to None, in which case
similarity_threshold must be specified. Defaults to 20.
attribute similarity_fn: Callable = <function cosine_similarity>


Similarity function for comparing documents. Function expected to take as input
two matrices (List[List[float]]) and return a matrix of scores where higher values
indicate greater similarity.
attribute similarity_threshold: Optional[float] = None
Threshold for determining when two documents are similar enough
to be considered redundant. Defaults to None, must be specified if k is set
to None.
async acompress_documents(documents, query)[source]
Filter down documents.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]
Filter documents based on similarity of their embeddings to the query.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]


Sequence[langchain.schema.Document]
class langchain.retrievers.document_compressors.LLMChainExtractor(*, llm_chain, get_input=<function default_get_input>)[source]
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Parameters
llm_chain (langchain.chains.llm.LLMChain) –
get_input (Callable[[str, langchain.schema.Document], dict]) –
Return type
None
attribute get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input>
Callable for constructing the chain input from the query and a Document.
attribute llm_chain: langchain.chains.llm.LLMChain [Required]
LLM wrapper to use for compressing documents.
async acompress_documents(documents, query)[source]
Compress page content of raw documents asynchronously.
Parameters


Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]
Compress page content of raw documents.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
classmethod from_llm(llm, prompt=None, get_input=None, llm_chain_kwargs=None)[source]
Initialize from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) –
prompt (Optional[langchain.prompts.prompt.PromptTemplate]) –
get_input (Optional[Callable[[str, langchain.schema.Document], str]]) –
llm_chain_kwargs (Optional[dict]) –
Return type
langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor


class langchain.retrievers.document_compressors.LLMChainFilter(*, llm_chain, get_input=<function default_get_input>)[source]
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Filter that drops documents that aren’t relevant to the query.
Parameters
llm_chain (langchain.chains.llm.LLMChain) –
get_input (Callable[[str, langchain.schema.Document], dict]) –
Return type
None
attribute get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input>
Callable for constructing the chain input from the query and a Document.
attribute llm_chain: langchain.chains.llm.LLMChain [Required]
LLM wrapper to use for filtering documents.
The chain prompt is expected to have a BooleanOutputParser.
async acompress_documents(documents, query)[source]


Filter down documents.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]
Filter down documents based on their relevance to the query.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
classmethod from_llm(llm, prompt=None, **kwargs)[source]
Parameters
llm (langchain.base_language.BaseLanguageModel) –
prompt (Optional[langchain.prompts.base.BasePromptTemplate]) –
kwargs (Any) –
Return type
langchain.retrievers.document_compressors.chain_filter.LLMChainFilter


class langchain.retrievers.document_compressors.CohereRerank(*, client, top_n=3, model='rerank-english-v2.0')[source]
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Parameters
client (Client) –
top_n (int) –
model (str) –
Return type
None
attribute client: Client [Required]
attribute model: str = 'rerank-english-v2.0'
attribute top_n: int = 3
async acompress_documents(documents, query)[source]
Compress retrieved documents given the query context.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]


Compress retrieved documents given the query context.
Parameters
documents (Sequence[langchain.schema.Document]) –
query (str) –
Return type
Sequence[langchain.schema.Document]


Chat Models
class langchain.chat_models.ChatOpenAI(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, client=None, model='gpt-3.5-turbo', temperature=0.7, model_kwargs=None, openai_api_key=None, openai_api_base=None, openai_organization=None, openai_proxy=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None, tiktoken_model_name=None)[source]
Bases: langchain.chat_models.base.BaseChatModel
Wrapper around OpenAI Chat large language models.
To use, you should have the openai python package installed, and the
environment variable OPENAI_API_KEY set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved on this class.
Example


Example
from langchain.chat_models import ChatOpenAI
openai = ChatOpenAI(model_name="gpt-3.5-turbo")
Parameters
cache (Optional[bool]) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
tags (Optional[List[str]]) –
client (Any) –
model (str) –
temperature (float) –
model_kwargs (Dict[str, Any]) –
openai_api_key (Optional[str]) –
openai_api_base (Optional[str]) –
openai_organization (Optional[str]) –
openai_proxy (Optional[str]) –
request_timeout (Optional[Union[float, Tuple[float, float]]]) –


max_retries (int) –
streaming (bool) –
n (int) –
max_tokens (Optional[int]) –
tiktoken_model_name (Optional[str]) –
Return type
None
attribute max_retries: int = 6
Maximum number of retries to make when generating.
attribute max_tokens: Optional[int] = None
Maximum number of tokens to generate.
attribute model_kwargs: Dict[str, Any] [Optional]
Holds any model parameters valid for create call not explicitly specified.
attribute model_name: str = 'gpt-3.5-turbo' (alias 'model')
Model name to use.
attribute n: int = 1
Number of chat completions to generate for each prompt.
attribute openai_api_base: Optional[str] = None


attribute openai_api_key: Optional[str] = None
Base URL path for API requests,
leave blank if not using a proxy or service emulator.
attribute openai_organization: Optional[str] = None
attribute openai_proxy: Optional[str] = None
attribute request_timeout: Optional[Union[float, Tuple[float, float]]] = None
Timeout for requests to OpenAI completion API. Default is 600 seconds.
attribute streaming: bool = False
Whether to stream the results or not.
attribute temperature: float = 0.7
What sampling temperature to use.
attribute tiktoken_model_name: Optional[str] = None
The model name to pass to tiktoken when using this class.
Tiktoken is used to count the number of tokens in documents to constrain
them to be under a certain limit. By default, when set to None, this will


be the same as the embedding model name. However, there are some cases
where you may want to use this Embedding class with a model name not
supported by tiktoken. This can include when using Azure embeddings or
when using one of the many model providers that expose an OpenAI-like
API but with different models. In those cases, in order to avoid erroring
when tiktoken is called, you can specify a model name to use here.
completion_with_retry(**kwargs)[source]
Use tenacity to retry the completion call.
Parameters
kwargs (Any) –
Return type
Any
get_num_tokens_from_messages(messages)[source]
Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.
Official documentation: https://github.com/openai/openai-cookbook/blob/
main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb


Parameters
messages (List[langchain.schema.BaseMessage]) –
Return type
int
get_token_ids(text)[source]
Get the tokens present in the text with tiktoken package.
Parameters
text (str) –
Return type
List[int]
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.chat_models.AzureChatOpenAI(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, client=None, model='gpt-3.5-turbo', temperature=0.7, model_kwargs=None, openai_api_key='', openai_api_base='', openai_organization='', openai_proxy='', request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None, tiktoken_model_name=None, deployment_name='', openai_api_type='azure', openai_api_version='')[source]
Bases: langchain.chat_models.openai.ChatOpenAI
Wrapper around Azure OpenAI Chat Completion API. To use this class you
must have a deployed model on Azure OpenAI. Use deployment_name in the
constructor to refer to the “Model deployment name” in the Azure portal.
In addition, you should have the openai python package installed, and the


following environment variables set or passed in constructor in lower case:
- OPENAI_API_TYPE (default: azure)
- OPENAI_API_KEY
- OPENAI_API_BASE
- OPENAI_API_VERSION
- OPENAI_PROXY
For exmaple, if you have gpt-35-turbo deployed, with the deployment name
35-turbo-dev, the constructor should look like:
AzureChatOpenAI(
    deployment_name="35-turbo-dev",
    openai_api_version="2023-03-15-preview",
)
Be aware the API version may change.
Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved on this class.
Parameters
cache (Optional[bool]) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –


callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
tags (Optional[List[str]]) –
client (Any) –
model (str) –
temperature (float) –
model_kwargs (Dict[str, Any]) –
openai_api_key (str) –
openai_api_base (str) –
openai_organization (str) –
openai_proxy (str) –
request_timeout (Optional[Union[float, Tuple[float, float]]]) –
max_retries (int) –
streaming (bool) –
n (int) –
max_tokens (Optional[int]) –
tiktoken_model_name (Optional[str]) –
deployment_name (str) –
openai_api_type (str) –
openai_api_version (str) –
Return type
None
attribute deployment_name: str = ''


attribute deployment_name: str = ''
attribute openai_api_base: str = ''
attribute openai_api_key: str = ''
Base URL path for API requests,
leave blank if not using a proxy or service emulator.
attribute openai_api_type: str = 'azure'
attribute openai_api_version: str = ''
attribute openai_organization: str = ''
attribute openai_proxy: str = ''
class langchain.chat_models.FakeListChatModel(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, responses, i=0)[source]
Bases: langchain.chat_models.base.SimpleChatModel
Fake ChatModel for testing purposes.
Parameters
cache (Optional[bool]) –
verbose (bool) –


verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
tags (Optional[List[str]]) –
responses (List) –
i (int) –
Return type
None
attribute i: int = 0
attribute responses: List [Required]


attribute responses: List [Required]
class langchain.chat_models.PromptLayerChatOpenAI(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, client=None, model='gpt-3.5-turbo', temperature=0.7, model_kwargs=None, openai_api_key=None, openai_api_base=None, openai_organization=None, openai_proxy=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None, tiktoken_model_name=None, pl_tags=None, return_pl_id=False)[source]
Bases: langchain.chat_models.openai.ChatOpenAI
Wrapper around OpenAI Chat large language models and PromptLayer.
To use, you should have the openai and promptlayer python
package installed, and the environment variable OPENAI_API_KEY
and PROMPTLAYER_API_KEY set with your openAI API key and


promptlayer key respectively.
All parameters that can be passed to the OpenAI LLM can also
be passed here. The PromptLayerChatOpenAI adds to optional
Parameters
pl_tags (Optional[List[str]]) – List of strings to tag the request with.
return_pl_id (Optional[bool]) – If True, the PromptLayer request ID will be
returned in the generation_info field of the
Generation object.
cache (Optional[bool]) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
tags (Optional[List[str]]) –
client (Any) –
model (str) –
temperature (float) –
model_kwargs (Dict[str, Any]) –
openai_api_key (Optional[str]) –


openai_api_base (Optional[str]) –
openai_organization (Optional[str]) –
openai_proxy (Optional[str]) –
request_timeout (Optional[Union[float, Tuple[float, float]]]) –
max_retries (int) –
streaming (bool) –
n (int) –
max_tokens (Optional[int]) –
tiktoken_model_name (Optional[str]) –
Return type
None
Example
from langchain.chat_models import PromptLayerChatOpenAI
openai = PromptLayerChatOpenAI(model_name="gpt-3.5-turbo")
attribute pl_tags: Optional[List[str]] = None
attribute return_pl_id: Optional[bool] = False