
langchain API Reference¶

langchain.adapters¶

Classes¶






adapters.openai.ChatCompletion()






Functions¶






adapters.openai.aenumerate(iterable[, start])
Async version of enumerate.

adapters.openai.convert_dict_to_message(_dict)


adapters.openai.convert_message_to_dict(message)


adapters.openai.convert_messages_for_finetuning(...)
Convert messages to a list of lists of dictionaries for fine-tuning.

adapters.openai.convert_openai_messages(messages)
Convert dictionaries representing OpenAI messages to LangChain format.






langchain.agents¶
Agent is a class that uses an LLM to choose a sequence of actions to take.
In Chains, a sequence of actions is hardcoded. In Agents,
a language model is used as a reasoning engine to determine which actions
to take and in which order.
Agents select and use Tools and Toolkits for actions.
Class hierarchy:
BaseSingleActionAgent --> LLMSingleActionAgent
                          OpenAIFunctionsAgent
                          XMLAgent
                          Agent --> <name>Agent  # Examples: ZeroShotAgent, ChatAgent


BaseMultiActionAgent  --> OpenAIMultiFunctionsAgent


Main helpers:
AgentType, AgentExecutor, AgentOutputParser, AgentExecutorIterator,
AgentAction, AgentFinish



Classes¶






agents.agent.Agent
Agent that calls the language model and deciding the action.

agents.agent.AgentExecutor
Agent that is using tools.

agents.agent.AgentOutputParser
Base class for parsing agent output into agent action/finish.

agents.agent.BaseMultiActionAgent
Base Multi Action Agent class.

agents.agent.BaseSingleActionAgent
Base Single Action Agent class.

agents.agent.ExceptionTool
Tool that just returns the query.

agents.agent.LLMSingleActionAgent
Base class for single action agents.

agents.agent.RunnableAgent
Agent powered by runnables.

agents.agent_iterator.AgentExecutorIterator(...)
Iterator for AgentExecutor.

agents.agent_iterator.BaseAgentExecutorIterator()
Base class for AgentExecutorIterator.

agents.agent_toolkits.ainetwork.toolkit.AINetworkToolkit
Toolkit for interacting with AINetwork Blockchain.

agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit
Toolkit for interacting with Office365.

agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit
Toolkit for Azure Cognitive Services.

agents.agent_toolkits.base.BaseToolkit
Base Toolkit representing a collection of related tools.

agents.agent_toolkits.file_management.toolkit.FileManagementToolkit
Toolkit for interacting with a Local Files.

agents.agent_toolkits.github.toolkit.GitHubToolkit
GitHub Toolkit.

agents.agent_toolkits.gitlab.toolkit.GitLabToolkit
GitLab Toolkit.

agents.agent_toolkits.gmail.toolkit.GmailToolkit
Toolkit for interacting with Gmail.

agents.agent_toolkits.jira.toolkit.JiraToolkit
Jira Toolkit.

agents.agent_toolkits.json.toolkit.JsonToolkit
Toolkit for interacting with a JSON spec.

agents.agent_toolkits.multion.toolkit.MultionToolkit
Toolkit for interacting with the Browser Agent

agents.agent_toolkits.nla.tool.NLATool
Natural Language API Tool.

agents.agent_toolkits.nla.toolkit.NLAToolkit
Natural Language API Toolkit.

agents.agent_toolkits.office365.toolkit.O365Toolkit
Toolkit for interacting with Office 365.

agents.agent_toolkits.openapi.planner.RequestsDeleteToolWithParsing
A tool that sends a DELETE request and parses the response.

agents.agent_toolkits.openapi.planner.RequestsGetToolWithParsing
Requests GET tool with LLM-instructed extraction of truncated responses.

agents.agent_toolkits.openapi.planner.RequestsPatchToolWithParsing
Requests PATCH tool with LLM-instructed extraction of truncated responses.

agents.agent_toolkits.openapi.planner.RequestsPostToolWithParsing
Requests POST tool with LLM-instructed extraction of truncated responses.

agents.agent_toolkits.openapi.planner.RequestsPutToolWithParsing
Requests PUT tool with LLM-instructed extraction of truncated responses.

agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec(...)
A reduced OpenAPI spec.

agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit
Toolkit for interacting with an OpenAPI API.

agents.agent_toolkits.openapi.toolkit.RequestsToolkit
Toolkit for making REST requests.

agents.agent_toolkits.playwright.toolkit.PlayWrightBrowserToolkit
Toolkit for PlayWright browser tools.

agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit
Toolkit for interacting with Power BI dataset.

agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit
Toolkit for interacting with Spark SQL.

agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit
Toolkit for interacting with SQL databases.

agents.agent_toolkits.vectorstore.toolkit.VectorStoreInfo
Information about a VectorStore.

agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit
Toolkit for routing between Vector Stores.

agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit
Toolkit for interacting with a Vector Store.

agents.agent_toolkits.zapier.toolkit.ZapierToolkit
Zapier Toolkit.

agents.agent_types.AgentType(value[, names, ...])
Enumerator with the Agent types.

agents.chat.base.ChatAgent
Chat Agent.

agents.chat.output_parser.ChatOutputParser
Output parser for the chat agent.

agents.conversational.base.ConversationalAgent
An agent that holds a conversation in addition to using tools.

agents.conversational.output_parser.ConvoOutputParser
Output parser for the conversational agent.

agents.conversational_chat.base.ConversationalChatAgent
An agent designed to hold a conversation in addition to using tools.

agents.conversational_chat.output_parser.ConvoOutputParser
Output parser for the conversational agent.

agents.mrkl.base.ChainConfig(action_name, ...)
Configuration for chain to use in MRKL system.

agents.mrkl.base.MRKLChain
[Deprecated] Chain that implements the MRKL system.

agents.mrkl.base.ZeroShotAgent
Agent for the MRKL chain.

agents.mrkl.output_parser.MRKLOutputParser
MRKL Output parser for the chat agent.

agents.openai_functions_agent.agent_token_buffer_memory.AgentTokenBufferMemory
Memory used to save agent output AND intermediate steps.

agents.openai_functions_agent.base.OpenAIFunctionsAgent
An Agent driven by OpenAIs function powered API.

agents.openai_functions_multi_agent.base.OpenAIMultiFunctionsAgent
An Agent driven by OpenAIs function powered API.

agents.output_parsers.json.JSONAgentOutputParser
Parses tool invocations and final answers in XML format.

agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser
Parses a message into agent action/finish.

agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser
Parses ReAct-style LLM calls that have a single tool input in json format.

agents.output_parsers.react_single_input.ReActSingleInputOutputParser
Parses ReAct-style LLM calls that have a single tool input.

agents.output_parsers.self_ask.SelfAskOutputParser
Parses self-ask style LLM calls.

agents.output_parsers.xml.XMLAgentOutputParser
Parses tool invocations and final answers in XML format.

agents.react.base.DocstoreExplorer(docstore)
Class to assist with exploration of a document store.

agents.react.base.ReActChain
[Deprecated] Chain that implements the ReAct paper.

agents.react.base.ReActDocstoreAgent
Agent for the ReAct chain.

agents.react.base.ReActTextWorldAgent
Agent for the ReAct TextWorld chain.

agents.react.output_parser.ReActOutputParser
Output parser for the ReAct agent.

agents.schema.AgentScratchPadChatPromptTemplate
Chat prompt template for the agent scratchpad.

agents.self_ask_with_search.base.SelfAskWithSearchAgent
Agent for the self-ask-with-search paper.

agents.self_ask_with_search.base.SelfAskWithSearchChain
[Deprecated] Chain that does self-ask with search.

agents.structured_chat.base.StructuredChatAgent
Structured Chat Agent.

agents.structured_chat.output_parser.StructuredChatOutputParser
Output parser for the structured chat agent.

agents.structured_chat.output_parser.StructuredChatOutputParserWithRetries
Output parser with retries for the structured chat agent.

agents.tools.InvalidTool
Tool that is run when invalid tool name is encountered by agent.

agents.xml.base.XMLAgent
Agent that uses XML tags.





Functions¶






agents.agent_iterator.rebuild_callback_manager_on_set(...)
Decorator to force setters to rebuild callback mgr

agents.agent_toolkits.conversational_retrieval.openai_functions.create_conversational_retrieval_agent(...)
A convenience method for creating a conversational retrieval agent.

agents.agent_toolkits.conversational_retrieval.tool.create_retriever_tool(...)
Create a tool to do retrieval of documents.

agents.agent_toolkits.csv.base.create_csv_agent(...)
Create csv agent by loading to a dataframe and using pandas agent.

agents.agent_toolkits.json.base.create_json_agent(...)
Construct a json agent from an LLM and tools.

agents.agent_toolkits.openapi.base.create_openapi_agent(...)
Construct an OpenAPI agent from an LLM and tools.

agents.agent_toolkits.openapi.planner.create_openapi_agent(...)
Instantiate OpenAI API planner and controller for a given spec.

agents.agent_toolkits.openapi.spec.reduce_openapi_spec(spec)
Simplify/distill/minify a spec somehow.

agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent(llm, df)
Construct a pandas agent from an LLM and dataframe.

agents.agent_toolkits.powerbi.base.create_pbi_agent(llm)
Construct a Power BI agent from an LLM and tools.

agents.agent_toolkits.powerbi.chat_base.create_pbi_chat_agent(llm)
Construct a Power BI agent from a Chat LLM and tools.

agents.agent_toolkits.python.base.create_python_agent(...)
Construct a python agent from an LLM and tool.

agents.agent_toolkits.spark.base.create_spark_dataframe_agent(llm, df)
Construct a Spark agent from an LLM and dataframe.

agents.agent_toolkits.spark_sql.base.create_spark_sql_agent(...)
Construct a Spark SQL agent from an LLM and tools.

agents.agent_toolkits.sql.base.create_sql_agent(...)
Construct an SQL agent from an LLM and tools.

agents.agent_toolkits.vectorstore.base.create_vectorstore_agent(...)
Construct a VectorStore agent from an LLM and tools.

agents.agent_toolkits.vectorstore.base.create_vectorstore_router_agent(...)
Construct a VectorStore router agent from an LLM and tools.

agents.agent_toolkits.xorbits.base.create_xorbits_agent(...)
Construct a xorbits agent from an LLM and dataframe.

agents.format_scratchpad.log.format_log_to_str(...)
Construct the scratchpad that lets the agent continue its thought process.

agents.format_scratchpad.log_to_messages.format_log_to_messages(...)
Construct the scratchpad that lets the agent continue its thought process.

agents.format_scratchpad.openai_functions.format_to_openai_functions(...)
Format intermediate steps.

agents.format_scratchpad.xml.format_xml(...)


agents.initialize.initialize_agent(tools, llm)
Load an agent executor given tools and LLM.

agents.load_tools.get_all_tool_names()
Get a list of all possible tool names.

agents.load_tools.load_huggingface_tool(...)
Loads a tool from the HuggingFace Hub.

agents.load_tools.load_tools(tool_names[, ...])
Load tools based on their name.

agents.loading.load_agent(path, **kwargs)
Unified method for loading an agent from LangChainHub or local fs.

agents.loading.load_agent_from_config(config)
Load agent from Config Dict.

agents.utils.validate_tools_single_input(...)
Validate tools for single input.






langchain.agents.format_scratchpad¶
Logic for formatting intermediate steps into an agent scratchpad.
Intermediate steps refers to the list of (AgentAction, observation) tuples
that result from previous iterations of the agent.
Depending on the prompting strategy you are using, you may want to format these
differently before passing them into the LLM.

Functions¶






agents.format_scratchpad.log.format_log_to_str(...)
Construct the scratchpad that lets the agent continue its thought process.

agents.format_scratchpad.log_to_messages.format_log_to_messages(...)
Construct the scratchpad that lets the agent continue its thought process.

agents.format_scratchpad.openai_functions.format_to_openai_functions(...)
Format intermediate steps.

agents.format_scratchpad.xml.format_xml(...)







langchain.agents.output_parsers¶
Parsing utils to go from string to AgentAction or Agent Finish.
AgentAction means that an action should be taken.
This contains the name of the tool to use, the input to pass to that tool,
and a log variable (which contains a log of the agent’s thinking).
AgentFinish means that a response should be given.
This contains a return_values dictionary. This usually contains a
single output key, but can be extended to contain more.
This also contains a log variable (which contains a log of the agent’s thinking).

Classes¶






agents.output_parsers.json.JSONAgentOutputParser
Parses tool invocations and final answers in XML format.

agents.output_parsers.openai_functions.OpenAIFunctionsAgentOutputParser
Parses a message into agent action/finish.

agents.output_parsers.react_json_single_input.ReActJsonSingleInputOutputParser
Parses ReAct-style LLM calls that have a single tool input in json format.

agents.output_parsers.react_single_input.ReActSingleInputOutputParser
Parses ReAct-style LLM calls that have a single tool input.

agents.output_parsers.self_ask.SelfAskOutputParser
Parses self-ask style LLM calls.

agents.output_parsers.xml.XMLAgentOutputParser
Parses tool invocations and final answers in XML format.






langchain.cache¶

Warning
Beta Feature!

Cache provides an optional caching layer for LLMs.
Cache is useful for two reasons:

It can save you money by reducing the number of API calls you make to the LLM
provider if you’re often requesting the same completion multiple times.
It can speed up your application by reducing the number of API calls you make
to the LLM provider.

Cache directly competes with Memory. See documentation for Pros and Cons.
Class hierarchy:
BaseCache --> <name>Cache  # Examples: InMemoryCache, RedisCache, GPTCache



Classes¶






cache.CassandraCache([session, keyspace, ...])
Cache that uses Cassandra / Astra DB as a backend.

cache.CassandraSemanticCache(session, ...[, ...])
Cache that uses Cassandra as a vector-store backend for semantic (i.e.

cache.FullLLMCache(**kwargs)
SQLite table for full LLM Cache (all generations).

cache.GPTCache([init_func])
Cache that uses GPTCache as a backend.

cache.InMemoryCache()
Cache that stores things in memory.

cache.MomentoCache(cache_client, cache_name, *)
Cache that uses Momento as a backend.

cache.RedisCache(redis_, *[, ttl])
Cache that uses Redis as a backend.

cache.RedisSemanticCache(redis_url, embedding)
Cache that uses Redis as a vector-store backend.

cache.SQLAlchemyCache(engine, cache_schema)
Cache that uses SQAlchemy as a backend.

cache.SQLiteCache([database_path])
Cache that uses SQLite as a backend.





Functions¶











langchain.callbacks¶
Callback handlers allow listening to events in LangChain.
Class hierarchy:
BaseCallbackHandler --> <name>CallbackHandler  # Example: AimCallbackHandler



Classes¶






callbacks.aim_callback.AimCallbackHandler([...])
Callback Handler that logs to Aim.

callbacks.aim_callback.BaseMetadataCallbackHandler()
This class handles the metadata and associated function states for callbacks.

callbacks.argilla_callback.ArgillaCallbackHandler(...)
Callback Handler that logs into Argilla.

callbacks.arize_callback.ArizeCallbackHandler([...])
Callback Handler that logs to Arize.

callbacks.arthur_callback.ArthurCallbackHandler(...)
Callback Handler that logs to Arthur platform.

callbacks.base.AsyncCallbackHandler()
Async callback handler that can be used to handle callbacks from langchain.

callbacks.base.BaseCallbackHandler()
Base callback handler that can be used to handle callbacks from langchain.

callbacks.base.BaseCallbackManager(handlers)
Base callback manager that handles callbacks from LangChain.

callbacks.base.CallbackManagerMixin()
Mixin for callback manager.

callbacks.base.ChainManagerMixin()
Mixin for chain callbacks.

callbacks.base.LLMManagerMixin()
Mixin for LLM callbacks.

callbacks.base.RetrieverManagerMixin()
Mixin for Retriever callbacks.

callbacks.base.RunManagerMixin()
Mixin for run manager.

callbacks.base.ToolManagerMixin()
Mixin for tool callbacks.

callbacks.clearml_callback.ClearMLCallbackHandler([...])
Callback Handler that logs to ClearML.

callbacks.comet_ml_callback.CometCallbackHandler([...])
Callback Handler that logs to Comet.

callbacks.confident_callback.DeepEvalCallbackHandler(metrics)
Callback Handler that logs into deepeval.

callbacks.context_callback.ContextCallbackHandler([...])
Callback Handler that records transcripts to the Context service.

callbacks.file.FileCallbackHandler(filename)
Callback Handler that writes to a file.

callbacks.flyte_callback.FlyteCallbackHandler()
This callback handler that is used within a Flyte task.

callbacks.human.HumanApprovalCallbackHandler(...)
Callback for manually validating values.

callbacks.human.HumanRejectedException
Exception to raise when a person manually review and rejects a value.

callbacks.infino_callback.InfinoCallbackHandler([...])
Callback Handler that logs to Infino.

callbacks.labelstudio_callback.LabelStudioCallbackHandler([...])
Label Studio callback handler.

callbacks.labelstudio_callback.LabelStudioMode(value)


callbacks.llmonitor_callback.LLMonitorCallbackHandler([...])
Initializes the LLMonitorCallbackHandler. #### Parameters:     - app_id: The app id of the app you want to report to. Defaults to     None, which means that LLMONITOR_APP_ID will be used. - api_url: The url of the LLMonitor API. Defaults to None,     which means that either LLMONITOR_API_URL environment variable     or https://app.llmonitor.com will be used.

callbacks.llmonitor_callback.UserContextManager(user_id)


callbacks.manager.AsyncCallbackManager(handlers)
Async callback manager that handles callbacks from LangChain.

callbacks.manager.AsyncCallbackManagerForChainGroup(...)
Initialize callback manager.

callbacks.manager.AsyncCallbackManagerForChainRun(*, ...)
Async callback manager for chain run.

callbacks.manager.AsyncCallbackManagerForLLMRun(*, ...)
Async callback manager for LLM run.

callbacks.manager.AsyncCallbackManagerForRetrieverRun(*, ...)
Async callback manager for retriever run.

callbacks.manager.AsyncCallbackManagerForToolRun(*, ...)
Async callback manager for tool run.

callbacks.manager.AsyncParentRunManager(*, ...)
Async Parent Run Manager.

callbacks.manager.AsyncRunManager(*, run_id, ...)
Async Run Manager.

callbacks.manager.BaseRunManager(*, run_id, ...)
Base class for run manager (a bound callback manager).

callbacks.manager.CallbackManager(handlers)
Callback manager that handles callbacks from langchain.

callbacks.manager.CallbackManagerForChainGroup(...)
Initialize callback manager.

callbacks.manager.CallbackManagerForChainRun(*, ...)
Callback manager for chain run.

callbacks.manager.CallbackManagerForLLMRun(*, ...)
Callback manager for LLM run.

callbacks.manager.CallbackManagerForRetrieverRun(*, ...)
Callback manager for retriever run.

callbacks.manager.CallbackManagerForToolRun(*, ...)
Callback manager for tool run.

callbacks.manager.ParentRunManager(*, ...[, ...])
Sync Parent Run Manager.

callbacks.manager.RunManager(*, run_id, ...)
Sync Run Manager.

callbacks.mlflow_callback.MlflowCallbackHandler([...])
Callback Handler that logs metrics and artifacts to mlflow server.

callbacks.mlflow_callback.MlflowLogger(**kwargs)
Callback Handler that logs metrics and artifacts to mlflow server.

callbacks.openai_info.OpenAICallbackHandler()
Callback Handler that tracks OpenAI info.

callbacks.promptlayer_callback.PromptLayerCallbackHandler([...])
Callback handler for promptlayer.

callbacks.sagemaker_callback.SageMakerCallbackHandler(run)
Callback Handler that logs prompt artifacts and metrics to SageMaker Experiments.

callbacks.stdout.StdOutCallbackHandler([color])
Callback Handler that prints to std out.

callbacks.streaming_aiter.AsyncIteratorCallbackHandler()
Callback handler that returns an async iterator.

callbacks.streaming_aiter_final_only.AsyncFinalIteratorCallbackHandler(*)
Callback handler that returns an async iterator.

callbacks.streaming_stdout.StreamingStdOutCallbackHandler()
Callback handler for streaming.

callbacks.streaming_stdout_final_only.FinalStreamingStdOutCallbackHandler(*)
Callback handler for streaming in agents.

callbacks.streamlit.mutable_expander.ChildRecord(...)
The child record as a NamedTuple.

callbacks.streamlit.mutable_expander.ChildType(value)
The enumerator of the child type.

callbacks.streamlit.mutable_expander.MutableExpander(...)
A Streamlit expander that can be renamed and dynamically expanded/collapsed.

callbacks.streamlit.streamlit_callback_handler.LLMThought(...)
A thought in the LLM's thought stream.

callbacks.streamlit.streamlit_callback_handler.LLMThoughtLabeler()
Generates markdown labels for LLMThought containers.

callbacks.streamlit.streamlit_callback_handler.LLMThoughtState(value)
Enumerator of the LLMThought state.

callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler(...)
A callback handler that writes to a Streamlit app.

callbacks.streamlit.streamlit_callback_handler.ToolRecord(...)
The tool record as a NamedTuple.

callbacks.tracers.base.BaseTracer(**kwargs)
Base interface for tracers.

callbacks.tracers.base.TracerException
Base class for exceptions in tracers module.

callbacks.tracers.evaluation.EvaluatorCallbackHandler(...)
A tracer that runs a run evaluator whenever a run is persisted.

callbacks.tracers.langchain.LangChainTracer([...])
An implementation of the SharedTracer that POSTS to the langchain endpoint.

callbacks.tracers.langchain_v1.LangChainTracerV1(...)
An implementation of the SharedTracer that POSTS to the langchain endpoint.

callbacks.tracers.log_stream.LogEntry


callbacks.tracers.log_stream.LogStreamCallbackHandler(*)


callbacks.tracers.log_stream.RunLog(*ops, state)


callbacks.tracers.log_stream.RunLogPatch(*ops)


callbacks.tracers.log_stream.RunState


callbacks.tracers.run_collector.RunCollectorCallbackHandler([...])
A tracer that collects all nested runs in a list.

callbacks.tracers.schemas.BaseRun
Base class for Run.

callbacks.tracers.schemas.ChainRun
Class for ChainRun.

callbacks.tracers.schemas.LLMRun
Class for LLMRun.

callbacks.tracers.schemas.Run
Run schema for the V2 API in the Tracer.

callbacks.tracers.schemas.ToolRun
Class for ToolRun.

callbacks.tracers.schemas.TracerSession
TracerSessionV1 schema for the V2 API.

callbacks.tracers.schemas.TracerSessionBase
Base class for TracerSession.

callbacks.tracers.schemas.TracerSessionV1
TracerSessionV1 schema.

callbacks.tracers.schemas.TracerSessionV1Base
Base class for TracerSessionV1.

callbacks.tracers.schemas.TracerSessionV1Create
Create class for TracerSessionV1.

callbacks.tracers.stdout.ConsoleCallbackHandler(...)
Tracer that prints to the console.

callbacks.tracers.stdout.FunctionCallbackHandler(...)
Tracer that calls a function with a single str parameter.

callbacks.tracers.wandb.RunProcessor(...)
Handles the conversion of a LangChain Runs into a WBTraceTree.

callbacks.tracers.wandb.WandbRunArgs
Arguments for the WandbTracer.

callbacks.tracers.wandb.WandbTracer([run_args])
Callback Handler that logs to Weights and Biases.

callbacks.trubrics_callback.TrubricsCallbackHandler([...])
Callback handler for Trubrics.

callbacks.utils.BaseMetadataCallbackHandler()
This class handles the metadata and associated function states for callbacks.

callbacks.wandb_callback.WandbCallbackHandler([...])
Callback Handler that logs to Weights and Biases.

callbacks.whylabs_callback.WhyLabsCallbackHandler(...)
Callback Handler for logging to WhyLabs.





Functions¶






callbacks.aim_callback.import_aim()
Import the aim python package and raise an error if it is not installed.

callbacks.clearml_callback.import_clearml()
Import the clearml python package and raise an error if it is not installed.

callbacks.comet_ml_callback.import_comet_ml()
Import comet_ml and raise an error if it is not installed.

callbacks.context_callback.import_context()
Import the getcontext package.

callbacks.flyte_callback.analyze_text(text)
Analyze text using textstat and spacy.

callbacks.flyte_callback.import_flytekit()
Import flytekit and flytekitplugins-deck-standard.

callbacks.infino_callback.import_infino()
Import the infino client.

callbacks.labelstudio_callback.get_default_label_configs(mode)


callbacks.llmonitor_callback.identify(user_id)


callbacks.manager.atrace_as_chain_group(...)
Get an async callback manager for a chain group in a context manager.

callbacks.manager.collect_runs()
Collect all run traces in context.

callbacks.manager.env_var_is_set(env_var)
Check if an environment variable is set.

callbacks.manager.get_openai_callback()
Get the OpenAI callback handler in a context manager.

callbacks.manager.trace_as_chain_group(...)
Get a callback manager for a chain group in a context manager.

callbacks.manager.tracing_enabled([session_name])
Get the Deprecated LangChainTracer in a context manager.

callbacks.manager.tracing_v2_enabled([...])
Instruct LangChain to log all runs in context to LangSmith.

callbacks.manager.wandb_tracing_enabled([...])
Get the WandbTracer in a context manager.

callbacks.mlflow_callback.analyze_text(text)
Analyze text using textstat and spacy.

callbacks.mlflow_callback.construct_html_from_prompt_and_generation(...)
Construct an html element from a prompt and a generation.

callbacks.mlflow_callback.import_mlflow()
Import the mlflow python package and raise an error if it is not installed.

callbacks.openai_info.get_openai_token_cost_for_model(...)
Get the cost in USD for a given model and number of tokens.

callbacks.openai_info.standardize_model_name(...)
Standardize the model name to a format that can be used in the OpenAI API.

callbacks.sagemaker_callback.save_json(data, ...)
Save dict to local file path.

callbacks.tracers.evaluation.wait_for_all_evaluators()
Wait for all tracers to finish.

callbacks.tracers.langchain.get_client()
Get the client.

callbacks.tracers.langchain.log_error_once(...)
Log an error once.

callbacks.tracers.langchain.wait_for_all_tracers()
Wait for all tracers to finish.

callbacks.tracers.langchain_v1.get_headers()
Get the headers for the LangChain API.

callbacks.tracers.schemas.RunTypeEnum()
RunTypeEnum.

callbacks.tracers.stdout.elapsed(run)
Get the elapsed time of a run.

callbacks.tracers.stdout.try_json_stringify(...)
Try to stringify an object to JSON.

callbacks.utils.flatten_dict(nested_dict[, ...])
Flattens a nested dictionary into a flat dictionary.

callbacks.utils.hash_string(s)
Hash a string using sha1.

callbacks.utils.import_pandas()
Import the pandas python package and raise an error if it is not installed.

callbacks.utils.import_spacy()
Import the spacy python package and raise an error if it is not installed.

callbacks.utils.import_textstat()
Import the textstat python package and raise an error if it is not installed.

callbacks.utils.load_json(json_path)
Load json file to a string.

callbacks.wandb_callback.analyze_text(text)
Analyze text using textstat and spacy.

callbacks.wandb_callback.construct_html_from_prompt_and_generation(...)
Construct an html element from a prompt and a generation.

callbacks.wandb_callback.import_wandb()
Import the wandb python package and raise an error if it is not installed.

callbacks.wandb_callback.load_json_to_dict(...)
Load json file to a dictionary.

callbacks.whylabs_callback.import_langkit([...])
Import the langkit python package and raise an error if it is not installed.






langchain.chains¶
Chains are easily reusable components linked together.
Chains encode a sequence of calls to components like models, document retrievers,
other Chains, etc., and provide a simple interface to this sequence.
The Chain interface makes it easy to create apps that are:


Stateful: add Memory to any Chain to give it state,
Observable: pass Callbacks to a Chain to execute additional functionality,
like logging, outside the main sequence of component calls,
Composable: combine Chains with other components, including other Chains.


Class hierarchy:
Chain --> <name>Chain  # Examples: LLMChain, MapReduceChain, RouterChain



Classes¶






chains.api.base.APIChain
Chain that makes API calls and summarizes the responses to answer a question.

chains.api.openapi.chain.OpenAPIEndpointChain
Chain interacts with an OpenAPI endpoint using natural language.

chains.api.openapi.requests_chain.APIRequesterChain
Get the request parser.

chains.api.openapi.requests_chain.APIRequesterOutputParser
Parse the request and error tags.

chains.api.openapi.response_chain.APIResponderChain
Get the response parser.

chains.api.openapi.response_chain.APIResponderOutputParser
Parse the response and error tags.

chains.base.Chain
Abstract base class for creating structured sequences of calls to components.

chains.combine_documents.base.AnalyzeDocumentChain
Chain that splits documents, then analyzes it in pieces.

chains.combine_documents.base.BaseCombineDocumentsChain
Base interface for chains combining documents.

chains.combine_documents.map_reduce.MapReduceDocumentsChain
Combining documents by mapping a chain over them, then combining results.

chains.combine_documents.map_rerank.MapRerankDocumentsChain
Combining documents by mapping a chain over them, then reranking results.

chains.combine_documents.reduce.AsyncCombineDocsProtocol(...)
Interface for the combine_docs method.

chains.combine_documents.reduce.CombineDocsProtocol(...)
Interface for the combine_docs method.

chains.combine_documents.reduce.ReduceDocumentsChain
Combine documents by recursively reducing them.

chains.combine_documents.refine.RefineDocumentsChain
Combine documents by doing a first pass and then refining on more documents.

chains.combine_documents.stuff.StuffDocumentsChain
Chain that combines documents by stuffing into context.

chains.constitutional_ai.base.ConstitutionalChain
Chain for applying constitutional principles.

chains.constitutional_ai.models.ConstitutionalPrinciple
Class for a constitutional principle.

chains.conversation.base.ConversationChain
Chain to have a conversation and load context from memory.

chains.conversational_retrieval.base.BaseConversationalRetrievalChain
Chain for chatting with an index.

chains.conversational_retrieval.base.ChatVectorDBChain
Chain for chatting with a vector database.

chains.conversational_retrieval.base.ConversationalRetrievalChain
Chain for having a conversation based on retrieved documents.

chains.elasticsearch_database.base.ElasticsearchDatabaseChain
Chain for interacting with Elasticsearch Database.

chains.flare.base.FlareChain
Chain that combines a retriever, a question generator, and a response generator.

chains.flare.base.QuestionGeneratorChain
Chain that generates questions from uncertain spans.

chains.flare.prompts.FinishedOutputParser
Output parser that checks if the output is finished.

chains.graph_qa.arangodb.ArangoGraphQAChain
Chain for question-answering against a graph by generating AQL statements.

chains.graph_qa.base.GraphQAChain
Chain for question-answering against a graph.

chains.graph_qa.cypher.GraphCypherQAChain
Chain for question-answering against a graph by generating Cypher statements.

chains.graph_qa.falkordb.FalkorDBQAChain
Chain for question-answering against a graph by generating Cypher statements.

chains.graph_qa.hugegraph.HugeGraphQAChain
Chain for question-answering against a graph by generating gremlin statements.

chains.graph_qa.kuzu.KuzuQAChain
Chain for question-answering against a graph by generating Cypher statements for Kùzu.

chains.graph_qa.nebulagraph.NebulaGraphQAChain
Chain for question-answering against a graph by generating nGQL statements.

chains.graph_qa.neptune_cypher.NeptuneOpenCypherQAChain
Chain for question-answering against a Neptune graph by generating openCypher statements.

chains.graph_qa.sparql.GraphSparqlQAChain
Chain for question-answering against an RDF or OWL graph by generating SPARQL statements.

chains.hyde.base.HypotheticalDocumentEmbedder
Generate hypothetical document for query, and then embed that.

chains.llm.LLMChain
Chain to run queries against LLMs.

chains.llm_bash.base.LLMBashChain
Chain that interprets a prompt and executes bash operations.

chains.llm_bash.prompt.BashOutputParser
Parser for bash output.

chains.llm_checker.base.LLMCheckerChain
Chain for question-answering with self-verification.

chains.llm_math.base.LLMMathChain
Chain that interprets a prompt and executes python code to do math.

chains.llm_requests.LLM