you nest the DISTINCT function within a formula, to get a list of distinct values that can be passed to another function and then counted, summed, or used for other operations.\nDISTINCT(<table>) - Returns a table by removing duplicate rows from another table or expression.\n\nAggregation functions, names with a A in it, handle booleans and empty strings in appropriate ways, while the same function without A only uses the numeric values in a column. Functions names with an X in it can include a expression as an argument, this will be evaluated for each row in the table and the result will be used in the regular function calculation, these are the functions:\nCOUNT(<column>), COUNTA(<column>), COUNTX(<table>,<expression>), COUNTAX(<table>,<expression>), COUNTROWS([<table>]), COUNTBLANK(<column>), DISTINCTCOUNT(<column>), DISTINCTCOUNTNOBLANK (<column>) - these are all variantions of count functions.\nAVERAGE(<column>), AVERAGEA(<column>), AVERAGEX(<table>,<expression>) - these are all variantions of average functions.\nMAX(<column>), MAXA(<column>), MAXX(<table>,<expression>) - these are all variantions of max functions.\nMIN(<column>), MINA(<column>), MINX(<table>,<expression>) - these are all variantions of min functions.\nPRODUCT(<column>), PRODUCTX(<table>,<expression>) - these are all variantions of product functions.\nSUM(<column>), SUMX(<table>,<expression>) - these are all variantions of sum functions.\n\nDate and time functions:\nDATE(year, month, day) - Returns a date value that represents the specified year, month, and day.\nDATEDIFF(date1, date2, <interval>) - Returns the difference between two date values, in the specified


date2, <interval>) - Returns the difference between two date values, in the specified interval, that can be SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR.\nDATEVALUE(<date_text>) - Returns a date value that represents the specified date.\nYEAR(<date>), QUARTER(<date>), MONTH(<date>), DAY(<date>), HOUR(<date>), MINUTE(<date>), SECOND(<date>) - Returns the part of the date for the specified date.\n\nFinally, make sure to escape double quotes with a single backslash, and make sure that only table names have single quotes around them, while names of measures or the values of columns that you want to compare against are in escaped double quotes. Newlines are not necessary and can be skipped. The queries are serialized as json and so will have to fit be compliant with json syntax. Sometimes you will get a question, a DAX query and a error, in that case you need to rewrite the DAX query to get the correct answer.\n\nThe following tables exist: {tables}\n\nand the schema\'s for some are given here:\n{schemas}\n\nExamples:\n{examples}\n\nQuestion: {tool_input}\nDAX: \n'


class langchain.tools.QuerySQLCheckerTool(*, name='sql_db_query_checker', description='\n    Use this tool to double check if your query is correct before executing it.\n    Always use this tool before executing a query with query_sql_db!\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, db, template='\n{query}\nDouble check the {dialect} query above for common mistakes, including:\n- Using NOT IN with NULL values\n- Using UNION when UNION ALL should have been used\n- Using BETWEEN for exclusive ranges\n- Data type mismatch in predicates\n- Properly quoting identifiers\n- Using the correct number of arguments for functions\n- Casting to the correct data type\n- Using the proper columns for joins\n\nIf there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.', llm, llm_chain)[source]
Bases: langchain.tools.sql_database.tool.BaseSQLDatabaseTool, langchain.tools.base.BaseTool
Use an LLM to check if a query is correct.
Adapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
db (langchain.sql_database.SQLDatabase) –


db (langchain.sql_database.SQLDatabase) –
template (str) –
llm (langchain.base_language.BaseLanguageModel) –
llm_chain (langchain.chains.llm.LLMChain) –
Return type
None
attribute llm: langchain.base_language.BaseLanguageModel [Required]
attribute llm_chain: langchain.chains.llm.LLMChain [Required]
attribute template: str = '\n{query}\nDouble check the {dialect} query above for common mistakes, including:\n- Using NOT IN with NULL values\n- Using UNION when UNION ALL should have been used\n- Using BETWEEN for exclusive ranges\n- Data type mismatch in predicates\n- Properly quoting identifiers\n- Using the correct number of arguments for functions\n- Casting to the correct data type\n- Using the proper columns for joins\n\nIf there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.'
class langchain.tools.QuerySQLDataBaseTool(*, name='sql_db_query', description='\n    Input to this tool is a detailed and correct SQL query, output is a result from the database.\n    If the query is not correct, an error message will be returned.\n    If an error is returned, rewrite the query, check the query, and try again.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, db)[source]
Bases: langchain.tools.sql_database.tool.BaseSQLDatabaseTool, langchain.tools.base.BaseTool
Tool for querying a SQL database.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –


return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
db (langchain.sql_database.SQLDatabase) –
Return type
None
class langchain.tools.QuerySparkSQLTool(*, name='query_sql_db', description='\n    Input to this tool is a detailed and correct SQL query, output is a result from the Spark SQL.\n    If the query is not correct, an error message will be returned.\n    If an error is returned, rewrite the query, check the query, and try again.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, db)[source]
Bases: langchain.tools.spark_sql.tool.BaseSparkSQLTool, langchain.tools.base.BaseTool
Tool for querying a Spark SQL.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
db (langchain.utilities.spark_sql.SparkSQL) –
Return type
None


db (langchain.utilities.spark_sql.SparkSQL) –
Return type
None
class langchain.tools.ReadFileTool(*, name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, root_dir=None)[source]
Bases: langchain.tools.file_management.utils.BaseFileToolMixin, langchain.tools.base.BaseTool
Parameters
name (str) –
description (str) –
args_schema (Type[pydantic.main.BaseModel]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
root_dir (Optional[str]) –
Return type
None
attribute args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.read.ReadFileInput'>
Pydantic model class to validate and parse the tool’s input arguments.
attribute description: str = 'Read file from disk'
Used to tell the model how/when/why to use the tool.
You can provide few-shot examples as a part of the description.
attribute name: str = 'read_file'
The unique name of the tool that clearly communicates its purpose.


The unique name of the tool that clearly communicates its purpose.
class langchain.tools.RequestsDeleteTool(*, name='requests_delete', description='A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, requests_wrapper)[source]
Bases: langchain.tools.requests.tool.BaseRequestsTool, langchain.tools.base.BaseTool
Tool for making a DELETE request to an API endpoint.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None
class langchain.tools.RequestsGetTool(*, name='requests_get', description='A portal to the internet. Use this when you need to get specific content from a website. Input should be a  url (i.e. https://www.google.com). The output will be the text response of the GET request.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, requests_wrapper)[source]
Bases: langchain.tools.requests.tool.BaseRequestsTool, langchain.tools.base.BaseTool
Tool for making a GET request to an API endpoint.
Parameters


Tool for making a GET request to an API endpoint.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None
class langchain.tools.RequestsPatchTool(*, name='requests_patch', description='Use this when you want to PATCH to a website.\n    Input should be a json string with two keys: "url" and "data".\n    The value of "url" should be a string, and the value of "data" should be a dictionary of \n    key-value pairs you want to PATCH to the url.\n    Be careful to always use double quotes for strings in the json string\n    The output will be the text response of the PATCH request.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, requests_wrapper)[source]
Bases: langchain.tools.requests.tool.BaseRequestsTool, langchain.tools.base.BaseTool
Tool for making a PATCH request to an API endpoint.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –


return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None
class langchain.tools.RequestsPostTool(*, name='requests_post', description='Use this when you want to POST to a website.\n    Input should be a json string with two keys: "url" and "data".\n    The value of "url" should be a string, and the value of "data" should be a dictionary of \n    key-value pairs you want to POST to the url.\n    Be careful to always use double quotes for strings in the json string\n    The output will be the text response of the POST request.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, requests_wrapper)[source]
Bases: langchain.tools.requests.tool.BaseRequestsTool, langchain.tools.base.BaseTool
Tool for making a POST request to an API endpoint.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –


requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None
class langchain.tools.RequestsPutTool(*, name='requests_put', description='Use this when you want to PUT to a website.\n    Input should be a json string with two keys: "url" and "data".\n    The value of "url" should be a string, and the value of "data" should be a dictionary of \n    key-value pairs you want to PUT to the url.\n    Be careful to always use double quotes for strings in the json string.\n    The output will be the text response of the PUT request.\n    ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, requests_wrapper)[source]
Bases: langchain.tools.requests.tool.BaseRequestsTool, langchain.tools.base.BaseTool
Tool for making a PUT request to an API endpoint.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None


requests_wrapper (langchain.requests.TextRequestsWrapper) –
Return type
None
class langchain.tools.SceneXplainTool(*, name='image_explainer', description='An Image Captioning Tool: Use this tool to generate a detailed caption for an image. The input can be an image file of any format, and the output will be a text description that covers every detail of the image.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, api_wrapper=None)[source]
Bases: langchain.tools.base.BaseTool
Tool that adds the capability to explain images.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
api_wrapper (langchain.utilities.scenexplain.SceneXplainAPIWrapper) –
Return type
None
attribute api_wrapper: langchain.utilities.scenexplain.SceneXplainAPIWrapper [Optional]
class langchain.tools.SearxSearchResults(*, name='Searx Search Results', description='A meta search engine.Useful for when you need to answer questions about current events.Input should be a search query. Output is a JSON array of the query results', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, wrapper, num_results=4, kwargs=None, **extra_data)[source]


Bases: langchain.tools.base.BaseTool
Tool that has the capability to query a Searx instance and get back json.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
wrapper (langchain.utilities.searx_search.SearxSearchWrapper) –
num_results (int) –
kwargs (dict) –
extra_data (Any) –
Return type
None
attribute kwargs: dict [Optional]
attribute num_results: int = 4
attribute wrapper: langchain.utilities.searx_search.SearxSearchWrapper [Required]
class langchain.tools.SearxSearchRun(*, name='searx_search', description='A meta search engine.Useful for when you need to answer questions about current events.Input should be a search query.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, wrapper, kwargs=None)[source]
Bases: langchain.tools.base.BaseTool
Tool that adds the capability to query a Searx instance.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –


return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
wrapper (langchain.utilities.searx_search.SearxSearchWrapper) –
kwargs (dict) –
Return type
None
attribute kwargs: dict [Optional]
attribute wrapper: langchain.utilities.searx_search.SearxSearchWrapper [Required]
class langchain.tools.ShellTool(*, name='terminal', description='Run shell commands on this Linux machine.', args_schema=<class 'langchain.tools.shell.tool.ShellInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, process=None)[source]
Bases: langchain.tools.base.BaseTool
Tool to run shell commands.
Parameters
name (str) –
description (str) –
args_schema (Type[pydantic.main.BaseModel]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
process (langchain.utilities.bash.BashProcess) –
Return type
None
attribute args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.shell.tool.ShellInput'>
Schema for input arguments.


Schema for input arguments.
attribute description: str = 'Run shell commands on this Linux machine.'
Description of tool.
attribute name: str = 'terminal'
Name of tool.
attribute process: langchain.utilities.bash.BashProcess [Optional]
Bash process to run commands.
class langchain.tools.SleepTool(*, name='sleep', description='Make agent sleep for a specified number of seconds.', args_schema=<class 'langchain.tools.sleep.tool.SleepInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False)[source]
Bases: langchain.tools.base.BaseTool
Tool that adds the capability to sleep.
Parameters
name (str) –
description (str) –
args_schema (Type[pydantic.main.BaseModel]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
Return type
None
attribute args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.sleep.tool.SleepInput'>
Pydantic model class to validate and parse the tool’s input arguments.
langchain.tools.StdInInquireTool(*args, **kwargs)[source]
Tool for asking the user for input.
Parameters
args (Any) –
kwargs (Any) –
Return type
langchain.tools.human.tool.HumanInputRun


Return type
langchain.tools.human.tool.HumanInputRun
class langchain.tools.SteamshipImageGenerationTool(*, name='GenerateImage', description='Useful for when you need to generate an image.Input: A detailed text-2-image prompt describing an imageOutput: the UUID of a generated image', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, model_name, size='512x512', steamship, return_urls=False)[source]
Bases: langchain.tools.base.BaseTool
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
model_name (langchain.tools.steamship_image_generation.tool.ModelName) –
size (Optional[str]) –
steamship (Steamship) –
return_urls (Optional[bool]) –
Return type
None
attribute model_name: ModelName [Required]
attribute return_urls: Optional[bool] = False
attribute size: Optional[str] = '512x512'
attribute steamship: Steamship [Required]
class langchain.tools.StructuredTool(*, name, description='', args_schema, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, func, coroutine=None)[source]
Bases: langchain.tools.base.BaseTool


Bases: langchain.tools.base.BaseTool
Tool that can operate on any number of inputs.
Parameters
name (str) –
description (str) –
args_schema (Type[pydantic.main.BaseModel]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
func (Callable[[...], Any]) –
coroutine (Optional[Callable[[...], Awaitable[Any]]]) –
Return type
None
attribute args_schema: Type[pydantic.main.BaseModel] [Required]
The input arguments’ schema.
The tool schema.
attribute coroutine: Optional[Callable[[...], Awaitable[Any]]] = None
The asynchronous version of the function.
attribute description: str = ''
Used to tell the model how/when/why to use the tool.
You can provide few-shot examples as a part of the description.
attribute func: Callable[[...], Any] [Required]
The function to run when the tool is called.
classmethod from_function(func, name=None, description=None, return_direct=False, args_schema=None, infer_schema=True, **kwargs)[source]
Create tool from a given function.
A classmethod that helps to create a tool from a function.
Parameters
func (Callable) – The function from which to create a tool
name (Optional[str]) – The name of the tool. Defaults to the function name
description (Optional[str]) – The description of the tool. Defaults to the function docstring


description (Optional[str]) – The description of the tool. Defaults to the function docstring
return_direct (bool) – Whether to return the result directly or as a callback
args_schema (Optional[Type[pydantic.main.BaseModel]]) – The schema of the tool’s input arguments
infer_schema (bool) – Whether to infer the schema from the function’s signature
**kwargs – Additional arguments to pass to the tool
kwargs (Any) –
Returns
The tool
Return type
langchain.tools.base.StructuredTool
Examples
… code-block:: python
def add(a: int, b: int) -> int:“””Add two numbers”””
return a + b
tool = StructuredTool.from_function(add)
tool.run(1, 2) # 3
property args: dict
The tool’s input arguments.
class langchain.tools.Tool(name, func, description, *, args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, coroutine=None)[source]
Bases: langchain.tools.base.BaseTool
Tool that takes in function or coroutine directly.
Parameters
name (str) –
func (Callable[[...], str]) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
coroutine (Optional[Callable[[...], Awaitable[str]]]) –
Return type
None


Return type
None
attribute args_schema: Optional[Type[pydantic.main.BaseModel]] = None
Pydantic model class to validate and parse the tool’s input arguments.
attribute callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None
Deprecated. Please use callbacks instead.
attribute callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None
Callbacks to be called during tool execution.
attribute coroutine: Optional[Callable[[...], Awaitable[str]]] = None
The asynchronous version of the function.
attribute description: str = ''
Used to tell the model how/when/why to use the tool.
You can provide few-shot examples as a part of the description.
attribute func: Callable[[...], str] [Required]
The function to run when the tool is called.
attribute handle_tool_error: Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]] = False
Handle the content of the ToolException thrown.
attribute name: str [Required]
The unique name of the tool that clearly communicates its purpose.
attribute return_direct: bool = False
Whether to return the tool’s output directly. Setting this to True means
that after the tool is called, the AgentExecutor will stop looping.
attribute verbose: bool = False
Whether to log the tool’s progress.
classmethod from_function(func, name, description, return_direct=False, args_schema=None, **kwargs)[source]
Initialize tool from a function.
Parameters
func (Callable) –
name (str) –
description (str) –
return_direct (bool) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –


args_schema (Optional[Type[pydantic.main.BaseModel]]) –
kwargs (Any) –
Return type
langchain.tools.base.Tool
property args: dict
The tool’s input arguments.
class langchain.tools.VectorStoreQATool(*, name, description, args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, vectorstore, llm=None)[source]
Bases: langchain.tools.vectorstore.tool.BaseVectorStoreTool, langchain.tools.base.BaseTool
Tool for the VectorDBQA chain. To be initialized with name and chain.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
vectorstore (langchain.vectorstores.base.VectorStore) –
llm (langchain.base_language.BaseLanguageModel) –
Return type
None
static get_description(name, description)[source]
Parameters
name (str) –
description (str) –
Return type
str
class langchain.tools.VectorStoreQAWithSourcesTool(*, name, description, args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, vectorstore, llm=None)[source]
Bases: langchain.tools.vectorstore.tool.BaseVectorStoreTool, langchain.tools.base.BaseTool


Tool for the VectorDBQAWithSources chain.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
vectorstore (langchain.vectorstores.base.VectorStore) –
llm (langchain.base_language.BaseLanguageModel) –
Return type
None
static get_description(name, description)[source]
Parameters
name (str) –
description (str) –
Return type
str
class langchain.tools.WikipediaQueryRun(*, name='Wikipedia', description='A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, api_wrapper)[source]
Bases: langchain.tools.base.BaseTool
Tool that adds the capability to search using the Wikipedia API.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –


callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
api_wrapper (langchain.utilities.wikipedia.WikipediaAPIWrapper) –
Return type
None
attribute api_wrapper: langchain.utilities.wikipedia.WikipediaAPIWrapper [Required]
class langchain.tools.WolframAlphaQueryRun(*, name='wolfram_alpha', description='A wrapper around Wolfram Alpha. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, api_wrapper)[source]
Bases: langchain.tools.base.BaseTool
Tool that adds the capability to query using the Wolfram Alpha SDK.
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
api_wrapper (langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper) –
Return type
None
attribute api_wrapper: langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper [Required]


class langchain.tools.WriteFileTool(*, name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, root_dir=None)[source]
Bases: langchain.tools.file_management.utils.BaseFileToolMixin, langchain.tools.base.BaseTool
Parameters
name (str) –
description (str) –
args_schema (Type[pydantic.main.BaseModel]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
root_dir (Optional[str]) –
Return type
None
attribute args_schema: Type[pydantic.main.BaseModel] = <class 'langchain.tools.file_management.write.WriteFileInput'>
Pydantic model class to validate and parse the tool’s input arguments.
attribute description: str = 'Write file to disk'
Used to tell the model how/when/why to use the tool.
You can provide few-shot examples as a part of the description.
attribute name: str = 'write_file'
The unique name of the tool that clearly communicates its purpose.


The unique name of the tool that clearly communicates its purpose.
class langchain.tools.YouTubeSearchTool(*, name='youtube_search', description='search for youtube videos associated with a person. the input to this tool should be a comma separated list, the first part contains a person name and the second a number that is the maximum number of video results to return aka num_results. the second part is optional', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False)[source]
Bases: langchain.tools.base.BaseTool
Parameters
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
Return type
None


Return type
None
class langchain.tools.ZapierNLAListActions(*, name='ZapierNLA_list_actions', description='A wrapper around Zapier NLA actions. The input to this tool is a natural language instruction, for example "get the latest email from my bank" or "send a slack message to the #general channel". Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. For example, if the params are [\'Message_Text\', \'Channel\'], your instruction should be something like \'send a slack message to the #general channel with the text hello world\'. Another example: if the params are [\'Calendar\', \'Search_Term\'], your instruction should be something like \'find the meeting in my personal calendar at 3pm\'. Do not make up params, they will be explicitly specified in the tool description. If you do not have enough information to fill in the params, just say \'not enough information provided in the instruction, missing <param>\'. If you get a none or null response, STOP EXECUTION, do not try to another tool!This tool specifically used for: {zapier_description}, and has params: {params}This tool returns a list of the user\'s exposed actions.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, api_wrapper=None)[source]
Bases: langchain.tools.base.BaseTool
Returns a list of all exposed (enabled) actions associated withcurrent user (associated with the set api_key). Change your exposed
actions here: https://nla.zapier.com/demo/start/
The return list can be empty if no actions exposed. Else will contain
a list of action objects:
[{“id”: str,
“description”: str,
“params”: Dict[str, str]


“description”: str,
“params”: Dict[str, str]
}]
params will always contain an instructions key, the only required
param. All others optional and if provided will override any AI guesses
(see “understanding the AI guessing flow” here:
https://nla.zapier.com/api/v1/docs)
Parameters
None –
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
api_wrapper (langchain.utilities.zapier.ZapierNLAWrapper) –
Return type
None
attribute api_wrapper: langchain.utilities.zapier.ZapierNLAWrapper [Optional]


class langchain.tools.ZapierNLARunAction(*, name='', description='', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, api_wrapper=None, action_id, params=None, base_prompt='A wrapper around Zapier NLA actions. The input to this tool is a natural language instruction, for example "get the latest email from my bank" or "send a slack message to the #general channel". Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. For example, if the params are [\'Message_Text\', \'Channel\'], your instruction should be something like \'send a slack message to the #general channel with the text hello world\'. Another example: if the params are [\'Calendar\', \'Search_Term\'], your instruction should be something like \'find the meeting in my personal calendar at 3pm\'. Do not make up params, they will be explicitly specified in the tool description. If you do not have enough information to fill in the params, just say \'not enough information provided in the instruction, missing <param>\'. If you get a none or null response, STOP EXECUTION, do not try to another tool!This tool specifically used for: {zapier_description}, and has params: {params}', zapier_description, params_schema=None)[source]
Bases: langchain.tools.base.BaseTool
Executes an action that is identified by action_id, must be exposed(enabled) by the current user (associated with the set api_key). Change
your exposed actions here: https://nla.zapier.com/demo/start/
The return JSON is guaranteed to be less than ~500 words (350
tokens) making it safe to inject into the prompt of another LLM
call.
Parameters


tokens) making it safe to inject into the prompt of another LLM
call.
Parameters
action_id (str) – a specific action ID (from list actions) of the action to execute
(the set api_key must be associated with the action owner)
instructions – a natural language instruction string for using the action
(eg. “get the latest email from Mike Knoop” for “Gmail: find email” action)
params (Optional[dict]) – a dict, optional. Any params provided will override AI guesses
from instructions (see “understanding the AI guessing flow” here:
https://nla.zapier.com/api/v1/docs)
name (str) –
description (str) –
args_schema (Optional[Type[pydantic.main.BaseModel]]) –
return_direct (bool) –
verbose (bool) –
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) –
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) –
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) –
api_wrapper (langchain.utilities.zapier.ZapierNLAWrapper) –
base_prompt (str) –
zapier_description (str) –
params_schema (Dict[str, str]) –
Return type
None
attribute action_id: str [Required]
attribute api_wrapper: langchain.utilities.zapier.ZapierNLAWrapper [Optional]


attribute base_prompt: str = 'A wrapper around Zapier NLA actions. The input to this tool is a natural language instruction, for example "get the latest email from my bank" or "send a slack message to the #general channel". Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. For example, if the params are [\'Message_Text\', \'Channel\'], your instruction should be something like \'send a slack message to the #general channel with the text hello world\'. Another example: if the params are [\'Calendar\', \'Search_Term\'], your instruction should be something like \'find the meeting in my personal calendar at 3pm\'. Do not make up params, they will be explicitly specified in the tool description. If you do not have enough information to fill in the params, just say \'not enough information provided in the instruction, missing <param>\'. If you get a none or null response, STOP EXECUTION, do not try to another tool!This tool specifically used for: {zapier_description}, and has params: {params}'
attribute params: Optional[dict] = None
attribute params_schema: Dict[str, str] [Optional]
attribute zapier_description: str [Required]
langchain.tools.format_tool_to_openai_function(tool)[source]
Format tool into the OpenAI function API.
Parameters
tool (langchain.tools.base.BaseTool) –
Return type
langchain.tools.convert_to_openai.FunctionDescription
langchain.tools.tool(*args, return_direct=False, args_schema=None, infer_schema=True)[source]
Make tools out of functions, can be used with or without arguments.
Parameters
*args – The arguments to the tool.
return_direct (bool) – Whether to return directly from the tool rather


return_direct (bool) – Whether to return directly from the tool rather
than continuing the agent loop.
args_schema (Optional[Type[pydantic.main.BaseModel]]) – optional argument schema for user to specify
infer_schema (bool) – Whether to infer the schema of the arguments from
the function’s signature. This also makes the resultant tool
accept a dictionary input to its run() function.
args (Union[str, Callable]) –
Return type
Callable
Requires:
Function must be of type (str) -> str
Function must have a docstring
Examples
@tool
def search_api(query: str) -> str:
    # Searches the API for the query.
    return
@tool("search", return_direct=True)
def search_api(query: str) -> str:
    # Searches the API for the query.
    return


Callbacks
Callback handlers that allow listening to events in LangChain.
class langchain.callbacks.AimCallbackHandler(repo=None, experiment_name=None, system_tracking_interval=10, log_system_params=True)[source]
Bases: langchain.callbacks.aim_callback.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Aim.
Parameters
repo (str, optional) – Aim repository path or Repo object to which
Run object is bound. If skipped, default Repo is used.
experiment_name (str, optional) – Sets Run’s experiment property.
‘default’ if not specified. Can be used later to query runs/sequences.
system_tracking_interval (int, optional) – Sets the tracking interval
in seconds for system usage metrics (CPU, Memory, etc.). Set to None
to disable system metrics tracking.
log_system_params (bool, optional) – Enable/Disable logging of system
params such as installed packages, git info, environment variables, etc.
Return type
None
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run
and then logs the response to Aim.
setup(**kwargs)[source]
Parameters
kwargs (Any) –
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]


Return type
None
on_llm_new_token(token, **kwargs)[source]
Run when LLM generates a new token.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_tool_end(output, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]


Return type
None
on_text(text, **kwargs)[source]
Run when agent is ending.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
flush_tracker(repo=None, experiment_name=None, system_tracking_interval=10, log_system_params=True, langchain_asset=None, reset=True, finish=False)[source]
Flush the tracker and reset the session.
Parameters
repo (str, optional) – Aim repository path or Repo object to which
Run object is bound. If skipped, default Repo is used.
experiment_name (str, optional) – Sets Run’s experiment property.
‘default’ if not specified. Can be used later to query runs/sequences.
system_tracking_interval (int, optional) – Sets the tracking interval
in seconds for system usage metrics (CPU, Memory, etc.). Set to None
to disable system metrics tracking.
log_system_params (bool, optional) – Enable/Disable logging of system
params such as installed packages, git info, environment variables, etc.
langchain_asset (Any) – The langchain asset to save.
reset (bool) – Whether to reset the session.
finish (bool) – Whether to finish the run.
Returns – None
Return type
None
class langchain.callbacks.ArgillaCallbackHandler(dataset_name, workspace_name=None, api_url=None, api_key=None)[source]


Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs into Argilla.
Parameters
dataset_name (str) – name of the FeedbackDataset in Argilla. Note that it must
exist in advance. If you need help on how to create a FeedbackDataset in
Argilla, please visit
https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.
workspace_name (Optional[str]) – name of the workspace in Argilla where the specified
FeedbackDataset lives in. Defaults to None, which means that the
default workspace will be used.
api_url (Optional[str]) – URL of the Argilla Server that we want to use, and where the
FeedbackDataset lives in. Defaults to None, which means that either
ARGILLA_API_URL environment variable or the default http://localhost:6900
will be used.
api_key (Optional[str]) – API Key to connect to the Argilla Server. Defaults to None, which
means that either ARGILLA_API_KEY environment variable or the default
argilla.apikey will be used.
Raises
ImportError – if the argilla package is not installed.
ConnectionError – if the connection to Argilla fails.
FileNotFoundError – if the FeedbackDataset retrieval from Argilla fails.
Return type
None
Examples
>>> from langchain.llms import OpenAI
>>> from langchain.callbacks import ArgillaCallbackHandler
>>> argilla_callback = ArgillaCallbackHandler(
...     dataset_name="my-dataset",
...     workspace_name="my-workspace",
...     api_url="http://localhost:6900",
...     api_key="argilla.apikey",
... )
>>> llm = OpenAI(
...     temperature=0,
...     callbacks=[argilla_callback],
...     verbose=True,


...     callbacks=[argilla_callback],
...     verbose=True,
...     openai_api_key="API_KEY_HERE",
... )
>>> llm.generate([
...     "What is the best NLP-annotation tool out there? (no bias at all)",
... ])
"Argilla, no doubt about it."
on_llm_start(serialized, prompts, **kwargs)[source]
Save the prompts in memory when an LLM starts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Do nothing when a new token is generated.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Log records to Argilla when an LLM ends.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Do nothing when LLM outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
If the key input is in inputs, then save it in self.prompts using
either the parent_run_id or the run_id as the key. This is done so that
we don’t log the same input prompt twice, once when the LLM starts and once
when the chain starts.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
If either the parent_run_id or the run_id is in self.prompts, then
log the outputs to Argilla, and pop the run from self.prompts. The behavior
differs if the output is a list or not.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Do nothing when LLM chain outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Do nothing when tool starts.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Do nothing when agent takes a specific action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
on_tool_end(output, observation_prefix=None, llm_prefix=None, **kwargs)[source]
Do nothing when tool ends.
Parameters
output (str) –
observation_prefix (Optional[str]) –
llm_prefix (Optional[str]) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Do nothing when tool outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Do nothing
Parameters
text (str) –
kwargs (Any) –


Do nothing
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Do nothing
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
class langchain.callbacks.ArizeCallbackHandler(model_id=None, model_version=None, SPACE_KEY=None, API_KEY=None)[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Arize.
Parameters
model_id (Optional[str]) –
model_version (Optional[str]) –
SPACE_KEY (Optional[str]) –
API_KEY (Optional[str]) –
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Do nothing.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –


inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Do nothing.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Do nothing.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
on_tool_end(output, observation_prefix=None, llm_prefix=None, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
observation_prefix (Optional[str]) –
llm_prefix (Optional[str]) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Run on arbitrary text.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
class langchain.callbacks.AsyncIteratorCallbackHandler[source]
Bases: langchain.callbacks.base.AsyncCallbackHandler
Callback handler that returns an async iterator.
Return type
None
property always_verbose: bool
queue: asyncio.queues.Queue[str]
done: asyncio.locks.Event
async on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
async on_llm_new_token(token, **kwargs)[source]
Run on new LLM token. Only available when streaming is enabled.
Parameters
token (str) –
kwargs (Any) –
Return type
None
async on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
async on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
async aiter()[source]
Return type
AsyncIterator[str]
class langchain.callbacks.ClearMLCallbackHandler(task_type='inference', project_name='langchain_callback_demo', tags=None, task_name=None, visualize=False, complexity_metrics=False, stream_logs=False)[source]
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to ClearML.
Parameters


Callback Handler that logs to ClearML.
Parameters
job_type (str) – The type of clearml task such as “inference”, “testing” or “qc”
project_name (str) – The clearml project name
tags (list) – Tags to add to the task
task_name (str) – Name of the clearml task
visualize (bool) – Whether to visualize the run.
complexity_metrics (bool) – Whether to log complexity metrics
stream_logs (bool) – Whether to stream callback actions to ClearML
task_type (Optional[str]) –
Return type
None
This handler will utilize the associated callback method and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response to the ClearML console.
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Run when LLM generates a new token.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_tool_end(output, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Run when agent is ending.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]


Return type
None
on_agent_action(action, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
analyze_text(text)[source]
Analyze text using textstat and spacy.
Parameters
text (str) – The text to analyze.
Returns
A dictionary containing the complexity metrics.
Return type
(dict)
flush_tracker(name=None, langchain_asset=None, finish=False)[source]
Flush the tracker and setup the session.
Everything after this will be a new table.
Parameters
name (Optional[str]) – Name of the preformed session so far so it is identifyable
langchain_asset (Any) – The langchain asset to save.
finish (bool) – Whether to finish the run.
Returns – None
Return type
None
class langchain.callbacks.CometCallbackHandler(task_type='inference', workspace=None, project_name=None, tags=None, name=None, visualizations=None, complexity_metrics=False, custom_metrics=None, stream_logs=True)[source]
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Comet.
Parameters
job_type (str) – The type of comet_ml task such as “inference”,
“testing” or “qc”
project_name (str) – The comet_ml project name
tags (list) – Tags to add to the task
task_name (str) – Name of the comet_ml task
visualize (bool) – Whether to visualize the run.
complexity_metrics (bool) – Whether to log complexity metrics
stream_logs (bool) – Whether to stream callback actions to Comet
task_type (Optional[str]) –
workspace (Optional[str]) –
name (Optional[str]) –


workspace (Optional[str]) –
name (Optional[str]) –
visualizations (Optional[List[str]]) –
custom_metrics (Optional[Callable]) –
Return type
None
This handler will utilize the associated callback method and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response to Comet.
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Run when LLM generates a new token.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_tool_end(output, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Run when agent is ending.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
flush_tracker(langchain_asset=None, task_type='inference', workspace=None, project_name='comet-langchain-demo', tags=None, name=None, visualizations=None, complexity_metrics=False, custom_metrics=None, finish=False, reset=False)[source]
Flush the tracker and setup the session.
Everything after this will be a new table.


Flush the tracker and setup the session.
Everything after this will be a new table.
Parameters
name (Optional[str]) – Name of the preformed session so far so it is identifyable
langchain_asset (Any) – The langchain asset to save.
finish (bool) – Whether to finish the run.
Returns – None
task_type (Optional[str]) –
workspace (Optional[str]) –
project_name (Optional[str]) –
tags (Optional[Sequence]) –
visualizations (Optional[List[str]]) –
complexity_metrics (bool) –
custom_metrics (Optional[Callable]) –
reset (bool) –
Return type
None
class langchain.callbacks.FileCallbackHandler(filename, mode='a', color=None)[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that writes to a file.
Parameters
filename (str) –
mode (str) –
color (Optional[str]) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Print out that we are entering a chain.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Print out that we finished a chain.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_agent_action(action, color=None, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
color (Optional[str]) –
kwargs (Any) –
Return type
Any


color (Optional[str]) –
kwargs (Any) –
Return type
Any
on_tool_end(output, color=None, observation_prefix=None, llm_prefix=None, **kwargs)[source]
If not the final action, print out observation.
Parameters
output (str) –
color (Optional[str]) –
observation_prefix (Optional[str]) –
llm_prefix (Optional[str]) –
kwargs (Any) –
Return type
None
on_text(text, color=None, end='', **kwargs)[source]
Run when agent ends.
Parameters
text (str) –
color (Optional[str]) –
end (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, color=None, **kwargs)[source]
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) –
color (Optional[str]) –
kwargs (Any) –
Return type
None
class langchain.callbacks.FinalStreamingStdOutCallbackHandler(*, answer_prefix_tokens=None, strip_tokens=True, stream_prefix=False)[source]
Bases: langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler
Callback handler for streaming in agents.
Only works with agents using LLMs that support streaming.
Only the final output of the agent will be streamed.
Parameters
answer_prefix_tokens (Optional[List[str]]) –
strip_tokens (bool) –
stream_prefix (bool) –
Return type
None
append_to_last_tokens(token)[source]
Parameters
token (str) –
Return type
None
check_if_answer_reached()[source]
Return type
bool
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts running.
Parameters


Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Run on new LLM token. Only available when streaming is enabled.
Parameters
token (str) –
kwargs (Any) –
Return type
None
class langchain.callbacks.HumanApprovalCallbackHandler(approve=<function _default_approve>, should_check=<function _default_true>)[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback for manually validating values.
Parameters
approve (Callable[[Any], bool]) –
should_check (Callable[[Dict[str, Any]], bool]) –
raise_error: bool = True
on_tool_start(serialized, input_str, *, run_id, parent_run_id=None, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
run_id (uuid.UUID) –
parent_run_id (Optional[uuid.UUID]) –
kwargs (Any) –
Return type
Any
class langchain.callbacks.InfinoCallbackHandler(model_id=None, model_version=None, verbose=False)[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Infino.
Parameters
model_id (Optional[str]) –
model_version (Optional[str]) –
verbose (bool) –
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]
Log the prompts to Infino, and set start time and error flag.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –


serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Do nothing when a new token is generated.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Log the latency, error, token usage, and response to Infino.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Set the error flag.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Do nothing when LLM chain starts.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Do nothing when LLM chain ends.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Need to log the error.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Do nothing when tool starts.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]


Return type
None
on_agent_action(action, **kwargs)[source]
Do nothing when agent takes a specific action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
on_tool_end(output, observation_prefix=None, llm_prefix=None, **kwargs)[source]
Do nothing when tool ends.
Parameters
output (str) –
observation_prefix (Optional[str]) –
llm_prefix (Optional[str]) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Do nothing when tool outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Do nothing.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Do nothing.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
class langchain.callbacks.MlflowCallbackHandler(name='langchainrun-%', experiment='langchain', tags={}, tracking_uri=None)[source]
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs metrics and artifacts to mlflow server.
Parameters
name (str) – Name of the run.
experiment (str) – Name of the experiment.
tags (dict) – Tags to be attached for the run.
tracking_uri (str) – MLflow tracking server uri.
Return type
None
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run,


the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response to mlflow server.
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Run when LLM generates a new token.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_tool_end(output, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Run when agent is ending.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
flush_tracker(langchain_asset=None, finish=False)[source]
Parameters
langchain_asset (Any) –
finish (bool) –
Return type
None
class langchain.callbacks.OpenAICallbackHandler[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that tracks OpenAI info.
total_tokens: int = 0
prompt_tokens: int = 0
completion_tokens: int = 0
successful_requests: int = 0


completion_tokens: int = 0
successful_requests: int = 0
total_cost: float = 0.0
property always_verbose: bool
Whether to call verbose callbacks even if verbose is False.
on_llm_start(serialized, prompts, **kwargs)[source]
Print out the prompts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Print out the token.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Collect token usage.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
class langchain.callbacks.StdOutCallbackHandler(color=None)[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that prints to std out.
Parameters
color (Optional[str]) –
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]
Print out the prompts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Do nothing.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Do nothing.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]


Return type
None
on_llm_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Print out that we are entering a chain.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Print out that we finished a chain.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Do nothing.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_agent_action(action, color=None, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
color (Optional[str]) –
kwargs (Any) –
Return type
Any
on_tool_end(output, color=None, observation_prefix=None, llm_prefix=None, **kwargs)[source]
If not the final action, print out observation.
Parameters
output (str) –
color (Optional[str]) –
observation_prefix (Optional[str]) –
llm_prefix (Optional[str]) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, color=None, end='', **kwargs)[source]
Run when agent ends.
Parameters
text (str) –
color (Optional[str]) –
end (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, color=None, **kwargs)[source]
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) –
color (Optional[str]) –
kwargs (Any) –
Return type
None
class langchain.callbacks.StreamingStdOutCallbackHandler[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback handler for streaming. Only works with LLMs that support streaming.
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Run on new LLM token. Only available when streaming is enabled.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters


Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
on_tool_end(output, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Run on arbitrary text.
Parameters
text (str) –
kwargs (Any) –
Return type


Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
langchain.callbacks.StreamlitCallbackHandler(parent_container, *, max_thought_containers=4, expand_new_thoughts=True, collapse_completed_thoughts=True, thought_labeler=None)[source]
Construct a new StreamlitCallbackHandler. This CallbackHandler is geared towards
use with a LangChain Agent; it displays the Agent’s LLM and tool-usage “thoughts”
inside a series of Streamlit expanders.
Parameters
parent_container (DeltaGenerator) – The st.container that will contain all the Streamlit elements that the
Handler creates.
max_thought_containers (int) – The max number of completed LLM thought containers to show at once. When this
threshold is reached, a new thought will cause the oldest thoughts to be
collapsed into a “History” expander. Defaults to 4.
expand_new_thoughts (bool) – Each LLM “thought” gets its own st.expander. This param controls whether that
expander is expanded by default. Defaults to True.
collapse_completed_thoughts (bool) – If True, LLM thought expanders will be collapsed when completed.
Defaults to True.
thought_labeler (Optional[LLMThoughtLabeler]) – An optional custom LLMThoughtLabeler instance. If unspecified, the handler
will use the default thought labeling logic. Defaults to None.
Returns
A new StreamlitCallbackHandler instance.
Note that this is an “auto-updating” API (if the installed version of Streamlit)
has a more recent StreamlitCallbackHandler implementation, an instance of that class


has a more recent StreamlitCallbackHandler implementation, an instance of that class
will be used.
Return type
BaseCallbackHandler
class langchain.callbacks.LLMThoughtLabeler[source]
Bases: object
Generates markdown labels for LLMThought containers. Pass a custom
subclass of this to StreamlitCallbackHandler to override its default
labeling logic.
get_initial_label()[source]
Return the markdown label for a new LLMThought that doesn’t have
an associated tool yet.
Return type
str
get_tool_label(tool, is_complete)[source]
Return the label for an LLMThought that has an associated
tool.
Parameters
tool (langchain.callbacks.streamlit.streamlit_callback_handler.ToolRecord) – The tool’s ToolRecord
is_complete (bool) – True if the thought is complete; False if the thought
is still receiving input.
Return type
The markdown label for the thought’s container.
get_history_label()[source]
Return a markdown label for the special ‘history’ container
that contains overflow thoughts.
Return type
str
get_final_agent_thought_label()[source]
Return the markdown label for the agent’s final thought -
the “Now I have the answer” thought, that doesn’t involve
a tool.
Return type
str
class langchain.callbacks.WandbCallbackHandler(job_type=None, project='langchain_callback_demo', entity=None, tags=None, group=None, name=None, notes=None, visualize=False, complexity_metrics=False, stream_logs=False)[source]
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Weights and Biases.
Parameters
job_type (str) – The type of job.
project (str) – The project to log to.


project (str) – The project to log to.
entity (str) – The entity to log to.
tags (list) – The tags to log.
group (str) – The group to log to.
name (str) – The name of the run.
notes (str) – The notes to log.
visualize (bool) – Whether to visualize the run.
complexity_metrics (bool) – Whether to log complexity metrics.
stream_logs (bool) – Whether to stream callback actions to W&B
Return type
None
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response using the run.log() method to Weights and Biases.
on_llm_start(serialized, prompts, **kwargs)[source]
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Run when LLM generates a new token.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]


None
on_chain_start(serialized, inputs, **kwargs)[source]
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_tool_end(output, **kwargs)[source]
Run when tool ends running.
Parameters
output (str) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Run when agent is ending.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, **kwargs)[source]
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) –
kwargs (Any) –
Return type
None
on_agent_action(action, **kwargs)[source]
Run on agent action.
Parameters


Run on agent action.
Parameters
action (langchain.schema.AgentAction) –
kwargs (Any) –
Return type
Any
flush_tracker(langchain_asset=None, reset=True, finish=False, job_type=None, project=None, entity=None, tags=None, group=None, name=None, notes=None, visualize=None, complexity_metrics=None)[source]
Flush the tracker and reset the session.
Parameters
langchain_asset (Any) – The langchain asset to save.
reset (bool) – Whether to reset the session.
finish (bool) – Whether to finish the run.
job_type (Optional[str]) – The job type.
project (Optional[str]) – The project.
entity (Optional[str]) – The entity.
tags (Optional[Sequence]) – The tags.
group (Optional[str]) – The group.
name (Optional[str]) – The name.
notes (Optional[str]) – The notes.
visualize (Optional[bool]) – Whether to visualize.
complexity_metrics (Optional[bool]) – Whether to compute complexity metrics.
Returns – None
Return type
None
class langchain.callbacks.WhyLabsCallbackHandler(logger)[source]
Bases: langchain.callbacks.base.BaseCallbackHandler
WhyLabs CallbackHandler.
Parameters
logger (Logger) –
on_llm_start(serialized, prompts, **kwargs)[source]
Pass the input prompts to the logger
Parameters
serialized (Dict[str, Any]) –
prompts (List[str]) –
kwargs (Any) –
Return type
None
on_llm_end(response, **kwargs)[source]
Pass the generated response to the logger.
Parameters
response (langchain.schema.LLMResult) –
kwargs (Any) –
Return type
None


kwargs (Any) –
Return type
None
on_llm_new_token(token, **kwargs)[source]
Do nothing.
Parameters
token (str) –
kwargs (Any) –
Return type
None
on_llm_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]
Do nothing.
Parameters
serialized (Dict[str, Any]) –
inputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_end(outputs, **kwargs)[source]
Do nothing.
Parameters
outputs (Dict[str, Any]) –
kwargs (Any) –
Return type
None
on_chain_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]
Do nothing.
Parameters
serialized (Dict[str, Any]) –
input_str (str) –
kwargs (Any) –
Return type
None
on_agent_action(action, color=None, **kwargs)[source]
Do nothing.
Parameters
action (langchain.schema.AgentAction) –
color (Optional[str]) –
kwargs (Any) –
Return type
Any
on_tool_end(output, color=None, observation_prefix=None, llm_prefix=None, **kwargs)[source]
Do nothing.
Parameters
output (str) –
color (Optional[str]) –
observation_prefix (Optional[str]) –


color (Optional[str]) –
observation_prefix (Optional[str]) –
llm_prefix (Optional[str]) –
kwargs (Any) –
Return type
None
on_tool_error(error, **kwargs)[source]
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) –
kwargs (Any) –
Return type
None
on_text(text, **kwargs)[source]
Do nothing.
Parameters
text (str) –
kwargs (Any) –
Return type
None
on_agent_finish(finish, color=None, **kwargs)[source]
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) –
color (Optional[str]) –
kwargs (Any) –
Return type
None
flush()[source]
Return type
None
close()[source]
Return type
None
classmethod from_params(*, api_key=None, org_id=None, dataset_id=None, sentiment=False, toxicity=False, themes=False)[source]
Instantiate whylogs Logger from params.
Parameters
api_key (Optional[str]) – WhyLabs API key. Optional because the preferred
way to specify the API key is with environment variable
WHYLABS_API_KEY.
org_id (Optional[str]) – WhyLabs organization id to write profiles to.
If not set must be specified in environment variable
WHYLABS_DEFAULT_ORG_ID.
dataset_id (Optional[str]) – The model or dataset this callback is gathering
telemetry for. If not set must be specified in environment variable
WHYLABS_DEFAULT_DATASET_ID.
sentiment (bool) – If True will initialize a model to perform
sentiment analysis compound score. Defaults to False and will not gather
this metric.


sentiment analysis compound score. Defaults to False and will not gather
this metric.
toxicity (bool) – If True will initialize a model to score
toxicity. Defaults to False and will not gather this metric.
themes (bool) – If True will initialize a model to calculate
distance to configured themes. Defaults to None and will not gather this
metric.
Return type
Logger
langchain.callbacks.get_openai_callback()[source]
Get the OpenAI callback handler in a context manager.
which conveniently exposes token and cost information.
Returns
The OpenAI callback handler.
Return type
OpenAICallbackHandler
Example
>>> with get_openai_callback() as cb:
...     # Use the OpenAI callback handler
langchain.callbacks.tracing_enabled(session_name='default')[source]
Get the Deprecated LangChainTracer in a context manager.
Parameters
session_name (str, optional) – The name of the session.
Defaults to “default”.
Returns
The LangChainTracer session.
Return type
TracerSessionV1
Example
>>> with tracing_enabled() as session:
...     # Use the LangChainTracer session
langchain.callbacks.wandb_tracing_enabled(session_name='default')[source]
Get the WandbTracer in a context manager.
Parameters
session_name (str, optional) – The name of the session.
Defaults to “default”.
Returns
None
Return type
Generator[None, None, None]
Example
>>> with wandb_tracing_enabled() as session:
...     # Use the WandbTracer session


Document Loaders
All different types of document loaders.
class langchain.document_loaders.AcreomLoader(path, encoding='UTF-8', collect_metadata=True)[source]
Bases: langchain.document_loaders.base.BaseLoader
Parameters
path (str) –
encoding (str) –
collect_metadata (bool) –
FRONT_MATTER_REGEX = re.compile('^---\\n(.*?)\\n---\\n', re.MULTILINE|re.DOTALL)
lazy_load()[source]
A lazy loader for document content.
Return type
Iterator[langchain.schema.Document]
load()[source]
Load data into document objects.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.AZLyricsLoader(web_path, header_template=None, verify=True)[source]
Bases: langchain.document_loaders.web_base.WebBaseLoader
Loader that loads AZLyrics webpages.
Parameters
web_path (Union[str, List[str]]) –
header_template (Optional[dict]) –
verify (Optional[bool]) –
load()[source]
Load webpage.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.AirbyteJSONLoader(file_path)[source]
Bases: langchain.document_loaders.base.BaseLoader
Loader that loads local airbyte json files.
Parameters
file_path (str) –
load()[source]
Load file.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.AirtableLoader(api_token, table_id, base_id)[source]
Bases: langchain.document_loaders.base.BaseLoader
Loader for Airtable tables.
Parameters
api_token (str) –
table_id (str) –


Parameters
api_token (str) –
table_id (str) –
base_id (str) –
lazy_load()[source]
Lazy load records from table.
Return type
Iterator[langchain.schema.Document]
load()[source]
Load Table.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.ApifyDatasetLoader(dataset_id, dataset_mapping_function)[source]
Bases: langchain.document_loaders.base.BaseLoader, pydantic.main.BaseModel
Logic for loading documents from Apify datasets.
Parameters
dataset_id (str) –
dataset_mapping_function (Callable[[Dict], langchain.schema.Document]) –
Return type
None
attribute apify_client: Any = None
attribute dataset_id: str [Required]
The ID of the dataset on the Apify platform.
attribute dataset_mapping_function: Callable[[Dict], langchain.schema.Document] [Required]
A custom function that takes a single dictionary (an Apify dataset item)
and converts it to an instance of the Document class.
load()[source]
Load documents.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.ArxivLoader(query, load_max_docs=100, load_all_available_meta=False)[source]
Bases: langchain.document_loaders.base.BaseLoader
Loads a query result from arxiv.org into a list of Documents.
Each document represents one Document.
The loader converts the original PDF format into the text.
Parameters
query (str) –
load_max_docs (Optional[int]) –
load_all_available_meta (Optional[bool]) –
load()[source]
Load data into document objects.
Return type
List[langchain.schema.Document]


Load data into document objects.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.AzureBlobStorageContainerLoader(conn_str, container, prefix='')[source]
Bases: langchain.document_loaders.base.BaseLoader
Loading logic for loading documents from Azure Blob Storage.
Parameters
conn_str (str) –
container (str) –
prefix (str) –
load()[source]
Load documents.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.AzureBlobStorageFileLoader(conn_str, container, blob_name)[source]
Bases: langchain.document_loaders.base.BaseLoader
Loading logic for loading documents from Azure Blob Storage.
Parameters
conn_str (str) –
container (str) –
blob_name (str) –
load()[source]
Load documents.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.BSHTMLLoader(file_path, open_encoding=None, bs_kwargs=None, get_text_separator='')[source]
Bases: langchain.document_loaders.base.BaseLoader
Loader that uses beautiful soup to parse HTML files.
Parameters
file_path (str) –
open_encoding (Optional[str]) –
bs_kwargs (Optional[dict]) –
get_text_separator (str) –
Return type
None
load()[source]
Load data into document objects.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.BibtexLoader(file_path, *, parser=None, max_docs=None, max_content_chars=4000, load_extra_metadata=False, file_pattern='[^:]+\\.pdf')[source]
Bases: langchain.document_loaders.base.BaseLoader
Loads a bibtex file into a list of Documents.


Loads a bibtex file into a list of Documents.
Each document represents one entry from the bibtex file.
If a PDF file is present in the file bibtex field, the original PDF
is loaded into the document text. If no such file entry is present,
the abstract field is used instead.
Parameters
file_path (str) –
parser (Optional[langchain.utilities.bibtex.BibtexparserWrapper]) –
max_docs (Optional[int]) –
max_content_chars (Optional[int]) –
load_extra_metadata (bool) –
file_pattern (str) –
lazy_load()[source]
Load bibtex file using bibtexparser and get the article texts plus the
article metadata.
See https://bibtexparser.readthedocs.io/en/master/
Returns
a list of documents with the document.page_content in text format
Return type
Iterator[langchain.schema.Document]
load()[source]
Load bibtex file documents from the given bibtex file path.
See https://bibtexparser.readthedocs.io/en/master/
Parameters
file_path – the path to the bibtex file
Returns
a list of documents with the document.page_content in text format
Return type
List[langchain.schema.Document]
class langchain.document_loaders.BigQueryLoader(query, project=None, page_content_columns=None, metadata_columns=None, credentials=None)[source]
Bases: langchain.document_loaders.base.BaseLoader
Loads a query result from BigQuery into a list of documents.
Each document represents one row of the result. The page_content_columns
are written into the page_content of the document. The metadata_columns
are written into the metadata of the document. By default, all columns
are written into the page_content and none into the metadata.
Parameters


are written into the page_content and none into the metadata.
Parameters
query (str) –
project (Optional[str]) –
page_content_columns (Optional[List[str]]) –
metadata_columns (Optional[List[str]]) –
credentials (Optional[Credentials]) –
load()[source]
Load data into document objects.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.BiliBiliLoader(video_urls)[source]
Bases: langchain.document_loaders.base.BaseLoader
Loader that loads bilibili transcripts.
Parameters
video_urls (List[str]) –
load()[source]
Load from bilibili url.
Return type
List[langchain.schema.Document]
class langchain.document_loaders.BlackboardLoader(blackboard_course_url, bbrouter, load_all_recursively=True, basic_auth=None, cookies=None)[source]
Bases: langchain.document_loaders.web_base.WebBaseLoader
Loader that loads all documents from a Blackboard course.
This loader is not compatible with all Blackboard courses. It is only
compatible with courses that use the new Blackboard interface.
To use this loader, you must have the BbRouter cookie. You can get this
cookie by logging into the course and then copying the value of the
BbRouter cookie from the browser’s developer tools.
Example
from langchain.document_loaders import BlackboardLoader
loader = BlackboardLoader(
    blackboard_course_url="https://blackboard.example.com/webapps/blackboard/execute/announcement?method=search&context=course_entry&course_id=_123456_1",
    bbrouter="expires:12345...",
)
documents = loader.load()
Parameters
blackboard_course_url (str) –
bbrouter (str) –


blackboard_course_url (str) –
bbrouter (str) –
load_all_recursively (bool) –
basic_auth (Optional[Tuple[str, str]]) –
cookies (Optional[dict]) –
folder_path: str
base_url: str
load_all_recursively: bool
check_bs4()[source]
Check if BeautifulSoup4 is installed.
Raises
ImportError – If BeautifulSoup4 is not installed.
Return type
None
load()[source]
Load data into document objects.
Returns
List of documents.
Return type
List[langchain.schema.Document]
download(path)[source]
Download a file from a url.
Parameters
path (str) – Path to the file.
Return type
None
parse_filename(url)[source]
Parse the filename from a url.
Parameters
url (str) – Url to parse the filename from.
Returns
The filename.
Return type
str
class langchain.document_loaders.Blob(*, data=None, mimetype=None, encoding='utf-8', path=None)[source]
Bases: pydantic.main.BaseModel
A blob is used to represent raw data by either reference or value.
Provides an interface to materialize the blob in different representations, and
help to decouple the development of data loaders from the downstream parsing of
the raw data.
Inspired by: https://developer.mozilla.org/en-US/docs/Web/API/Blob
Parameters
data (Optional[Union[bytes, str]]) –
mimetype (Optional[str]) –
encoding (str) –
path (Optional[Union[str, pathlib.PurePath]]) –
Return type
None
attribute data: Optional[Union[bytes, str]] = None


None
attribute data: Optional[Union[bytes, str]] = None
attribute encoding: str = 'utf-8'
attribute mimetype: Optional[str] = None
attribute path: Optional[Union[str, pathlib.PurePath]] = None
as_bytes()[source]
Read data as bytes.
Return type
bytes
as_bytes_io()[source]
Read data as a byte stream.
Return type
Generator[Union[_io.BytesIO, _io.BufferedReader], None, None]
as_string()[source]
Read data as a string.
Return type
str
classmethod from_data(data, *, encoding='utf-8', mime_type=None, path=None)[source]
Initialize the blob from in-memory data.
Parameters
data (Union[str, bytes]) – the in-memory data associated with the blob
encoding (str) – Encoding to use if decoding the bytes into a string
mime_type (Optional[str]) – if provided, will be set as the mime-type of the data
path (Optional[str]) – if provided, will be set as the source from which the data came
Returns
Blob instance
Return type
langchain.document_loaders.blob_loaders.schema.Blob
classmethod from_path(path, *, encoding='utf-8', mime_type=None, guess_type=True)[source]
Load the blob from a path like object.
Parameters
path (Union[str, pathlib.PurePath]) – path like object to file to be read
encoding (str) – Encoding to use if decoding the bytes into a string
mime_type (Optional[str]) – if provided, will be set as the mime-type of the data
guess_type (bool) – If True, the mimetype will be guessed from the file extension,
if a mime-type was not provided
Returns
Blob instance
Return type