Looking for the JS/TS version? Check out LangChain.js.
To help you ship LangChain apps to production faster, check out LangSmith. LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.
uv add langchain-classic
Legacy chains, langchain-community re-exports, indexing API, deprecated functionality, and more.
In most cases, you should be using the main langchain package.
For full documentation, see the API reference. For conceptual guides, tutorials, and examples on using LangChain, see the LangChain Docs.
See our Releases and Versioning policies.
As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
For detailed information on how to contribute, see the Contributing Guide.
A utility to experiment with and compare the performance of different models.
A function description for ChatOpenAI.
A runnable that routes to the selected function.
Parse an output using Pandas DataFrame format.
Retry chain input for RetryOutputParser.
Retry chain input for RetryWithErrorOutputParser.
Wrap a parser and try to fix parsing errors.
Does this by passing the original prompt and the completion to another LLM, and telling it the completion did not satisfy criteria in the prompt.
Wrap a parser and try to fix parsing errors.
Does this by passing the original prompt, the completion, AND the error that was raised to another language model and telling it that the completion did n
Parse YAML output using a Pydantic model.
Combine multiple output parsers into one.
Parse the output of an LLM call to a boolean.
Parse the output of an LLM call into a Dictionary using a regex.
Parse the output of an LLM call to a datetime.
Schema for a response from a structured output parser.
Parse the output of an LLM call to a structured output.
Input for the retry chain of the OutputFixingParser.
Wrap a parser and try to fix parsing errors.
Parse the output of an LLM call using a regex.
Parse an output that is one of a set of values.
A simple progress bar for the console.
Raised when the input format is invalid.
A dictionary of the results of a single test run.
Your architecture raised an error.
Input for a chat model.
Configuration for a given run evaluator.
Configuration for a run evaluator that only requires a single key.
Configuration for a run evaluation.
Configuration for a reference-free criteria evaluator.
Configuration for a labeled (with references) criteria evaluator.
Configuration for an embedding distance evaluator.
Configuration for a string distance evaluator.
Configuration for a QA evaluator.
Configuration for a context-based QA evaluator.
Configuration for a context-based QA evaluator.
Configuration for a json validity evaluator.
Configuration for a json equality evaluator.
Configuration for an exact match string evaluator.
Configuration for a regex match string evaluator.
Configuration for a score string evaluator.
This is like the criteria evaluator but it is configured by default to return a score on the scale from 1-10.
It is recommended to normalize these scores
Configuration for a labeled score string evaluator.
Extract items to evaluate from the run object.
Extract items to evaluate from the run object.
Extract items to evaluate from the run object from a chain.
Map an input to the tool.
Map an example, or row in the dataset, to the inputs of an evaluation.
Evaluate Run and optional examples.
The types of the evaluators.
A base class for evaluators that use an LLM.
String evaluator interface.
Grade, tag, or otherwise evaluate predictions relative to their inputs and/or reference labels.
Compare the output of two models (or two outputs of the same model).
Interface for evaluating agent trajectories.
A parser for the output of the PairwiseStringEvalChain.
Pairwise String Evaluation Chain.
A chain for comparing two outputs, such as the outputs of two models, prompts, or outputs of a single model on similar inputs.
Labeled Pairwise String Evaluation Chain.
A chain for comparing two outputs, such as the outputs of two models, prompts, or outputs of a single model on similar inputs, with labeled preferences.
LLM Chain for evaluating question answering.
LLM Chain for evaluating QA w/o GT based on context.
LLM Chain for evaluating QA using chain of thought reasoning.
LLM Chain for generating examples for question answering.
Compute a regex match between the prediction and the reference.
Examples:
evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE) evaluator.evaluate_strings( prediction=
A Criteria to evaluate.
A parser for the output of the CriteriaEvalChain.
LLM Chain for evaluating runs against criteria.
Parameters
llm : BaseLanguageModel The language model to use for evaluation. criteria : Union[Mapping[str, str]] The criteria or rub
Criteria evaluation chain that requires references.
Compute an exact match between the prediction and the reference.
Examples:
evaluator = ExactMatchChain() evaluator.evaluate_strings( prediction="Mindy is the CTO",
Distance metric to use.
Compute string distances between the prediction and the reference.
Examples:
from langchain_classic.evaluation import StringDistanceEvalChain evaluator = StringDistanceEvalChain()
Compute string edit distances between two predictions.
A named tuple containing the score and reasoning for a trajectory.
Trajectory output parser.
A chain for evaluating ReAct style agents.
This chain is used to evaluate ReAct style agents by reasoning about the sequence of actions taken and their outcomes. Based on the paper "ReAct: Synergizin
Evaluate whether the prediction is valid JSON.
This evaluator checks if the prediction is a valid JSON string. It does not require any input or reference.
Json Equality Evaluator.
Evaluate whether the prediction is equal to the reference after parsing both as JSON.
This evaluator checks if the prediction, after parsing as JSON, is equal to the ref
An evaluator that calculates the edit distance between JSON strings.
This evaluator computes a normalized Damerau-Levenshtein distance between two JSON strings after parsing them and converting them
An evaluator that validates a JSON prediction against a JSON schema reference.
This evaluator checks if a given JSON prediction conforms to the provided JSON schema. If the prediction is valid, the s
A parser for the output of the ScoreStringEvalChain.
A chain for scoring on a scale of 1-10 the output of a model.
A chain for scoring the output of a model on a scale of 1-10.
Embedding Distance Metric.
Embedding distance evaluation chain.
Use embedding distances to score semantic difference between a prediction and reference.
Use embedding distances to score semantic difference between two predictions.
Examples:
chain = PairwiseEmbeddingDistanceEvalChain() result = chain.evaluate_string_pairs(prediction="Hello", p
BaseStore interface that works on the local file system.
Wraps a store with key and value encoders/decoders.
Examples that uses JSON for encoding/decoding:
import json
def key_encoder(key: int) -> str:
return json.dumps(key)
def value_seri
Chat prompt template for the agent scratchpad.
Iterator for AgentExecutor.
Tool that is run when invalid tool name is encountered by agent.
Base Single Action Agent class.
Base Multi Action Agent class.
Base class for parsing agent output into agent action/finish.
Base class for parsing agent output into agent actions/finish.
This is used for agents that can return multiple actions.
Agent powered by Runnables.
Agent powered by Runnables.
Tool that just returns the query.
Agent that is using tools.
Output parser for the conversational agent.
Output parser for the ReAct agent.
Output parser for the structured chat agent.
Output parser with retries for the structured chat agent.
Parses ReAct-style LLM calls that have a single tool input.
Expects output to be in one of two formats.
If the output signals that an action should be taken, should be in the below format. This will
Parses ReAct-style LLM calls that have a single tool input in json format.
Expects output to be in one of two formats.
If the output signals that an action should be taken, should be in the below fo
Parses a message into agent action/finish.
Is meant to be used with OpenAI models, as it relies on the specific function_call parameter from OpenAI to convey what tools to use.
If a function_call pa
Tool agent action.
Parses a message into agent actions/finish.
If a tool_calls parameter is passed, then that is used to get the tool names and tool inputs.
If one is not passed, then the AIMessage is assumed to be th
Parses self-ask style LLM calls.
Expects output to be in one of two formats.
If the output signals that an action should be taken, should be in the below format. This will result in an AgentAction b
Parses tool invocations and final answers from XML-formatted agent output.
This parser extracts structured information from XML tags to determine whether an agent should perform a tool action or prov
Parses a message into agent actions/finish.
Is meant to be used with OpenAI models, as it relies on the specific tool_calls parameter from OpenAI to convey what tools to use.
If a tool_calls paramet
Parses tool invocations and final answers in JSON format.
Expects output to be in one of two formats.
If the output signals that an action should be taken, should be in the below format. This will r
Memory used to save agent output AND intermediate steps.
Output parser for the conversational agent.
AgentFinish with run and thread metadata.
AgentAction with info needed to submit custom tool output to existing run.
Run an OpenAI Assistant.
Information about a VectorStore.
Toolkit for interacting with a VectorStore.
Toolkit for routing between Vector Stores.
Output parser for the chat agent.
Configuration for a chain to use in MRKL system.
MRKL Output parser for the chat agent.
Table used to keep track of when a key was last updated.
A SQL Alchemy based implementation of the record manager.
Wrapper around a VectorStore for easy access.
Logic for creating indexes.
Interface for caching results from embedding models.
The interface allows works with any store that implements the abstract store interface accepting keys of type str and values of list of floats.
I
Pass input through a moderation endpoint.
To use, you should have the openai python package installed, and the
environment variable OPENAI_API_KEY set with your API key.
Any parameters that are
Abstract base class for creating structured sequences of calls to components.
Chains should be used to encode a sequence of calls to components like models, document retrievers, other chains, etc., a
Chain where the outputs of one chain feed directly into next.
Simple chain where the outputs of one step feed directly into next.
Base class for prompt selectors.
Prompt collection that goes through conditionals.
Chain that transforms the chain output.
Parser for output of router chain in the multi-prompt chain.
A route to a destination chain.
Chain that outputs the name of a destination chain and the inputs to it.
Use a single chain to route an input to one of multiple candidate chains.
Chain that uses embeddings to route between options.
Multi Retrieval QA Chain.
A multi-route chain that uses an LLM router chain to choose amongst retrieval qa chains.
Interface for loading the combine documents chain.
Class for a constitutional principle.
Chain that generates questions from uncertain spans.
Flare chain.
Chain that combines a retriever, a question generator, and a response generator.
See Active Retrieval Augmented Generation paper.
Output parser that checks if the output is finished.
Interface for loading the combine documents chain.
Generate hypothetical document for query, and then embed that.
Based on https://arxiv.org/abs/2212.10496
Output parser that parses a structured query.
Information about a data source attribute.
A date in ISO 8601 format (YYYY-MM-DD).
A datetime in ISO 8601 format (YYYY-MM-DDTHH:MM:SS).
Transform a query string into an intermediate representation.
Chain for interacting with Elasticsearch Database.
Question-answering with sources over an index.
Interface for loading the combine documents chain.
Question-answering with sources over a vector database.
A typed dictionary containing information about elements in the viewport.
A crawler for web pages.
Security Note: This is an implementation of a crawler that uses a browser via Playwright.
This crawler can be used to load arbitrary webpages INCLUDING content
Base interface for chains combining documents.
Subclasses of this chain deal with combining documents in a variety of ways. This base class exists to add some uniformity in the interface these types
Interface for the combine_docs method.
Interface for the combine_docs method.
Class representing a single statement.
Each fact has a body and a list of sources. If there are multiple facts make sure to break them apart such that each one only uses a set of sources that are rel
A question and its answer as a list of facts.
Each fact should have a source. Each sentence contains a body and a list of sources.
An answer to the question, with sources.
Raise an ImportError if APIChain is used without langchain_community.
Input type for ConversationalRetrievalChain.
Chain for chatting with an index.
Chain for chatting with a vector database.
Input for a SQL Chain.
Input for a SQL Chain.
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.
Callback handler that returns an async iterator.
Only the final output of the agent will be iterated.
Callback handler that returns an async iterator.
Tracer that logs via the input Logger.
Retriever that merges the results of multiple retrievers.
Given a query, use an LLM to re-phrase it.
Then, retrieve docs for the re-phrased query.
Time Weighted Vector Store Retriever.
Retriever that combines embedding similarity with recency in retrieving values.
Retrieve small chunks then retrieve their parent documents.
When splitting documents for retrieval, there are often conflicting desires:
Output parser for a list of lines.
Given a query, use an LLM to write a set of queries.
Retrieve docs for each query. Return the unique union of all retrieved docs.
Retriever that ensembles the multiple retrievers.
It uses a rank fusion.
Enumerator of the types of search to perform.
Retriever that supports multiple embeddings per parent document.
This retriever is designed for scenarios where documents are split into smaller chunks for embedding and vector search, but retrieval
Retriever that wraps a base retriever and compresses the results.
Document compressor that uses a pipeline of Transformers.
Embeddings Filter.
Document compressor that uses embeddings to drop documents unrelated to the query.
Parse outputs that could return a null string of some sort.
LLM Chain Extractor.
Document compressor that uses an LLM chain to extract the relevant parts of documents.
Document compressor that uses CrossEncoder for reranking.
Filter that drops documents that aren't relevant to the query.
Document compressor that uses Zero-Shot Listwise Document Reranking.
Adapted from: https://arxiv.org/pdf/2305.02156.pdf
LLMListwiseRerank uses a language model to rerank a list of documents base
Self Query Retriever.
Retriever that uses a vector store and an LLM to generate the vector store queries.
Conversation chat memory with token limit and vectordb backing.
load_memory_variables() will return a dict with the key "history". It contains background information retrieved from the vector store p
Simple Memory.
Simple memory for storing context or other information that shouldn't ever change between prompts.
Combining multiple memories' data together.
Memory wrapper that is read-only and cannot be changed.
Abstract base class for memory in Chains.
Memory refers to state in Chains. Memory can be used to store information about past executions of a Chain and inject that information into the inputs of
An instance of a runnable stored in the LangChain Hub.
An enum for agent types.
Base class for single action agents.
Agent that calls the language model and deciding the action.
This is driven by a LLMChain. The prompt in the LLMChain MUST include a variable called "agent_scratchpad" where the agent can put its int
An agent designed to hold a conversation in addition to using tools.
Agent for the ReAct chain.
Class to assist with exploration of a document store.
Agent for the ReAct TextWorld chain.
[Deprecated] Chain that implements the ReAct paper.
Agent that uses XML tags.
Structured Chat Agent.
An Agent driven by OpenAIs function powered API.
Agent driven by OpenAIs function powered API.
An agent that holds a conversation in addition to using tools.
Agent for the self-ask-with-search paper.
[Deprecated] Chain that does self-ask with search.
Chat Agent.
Agent for the MRKL chain.
Chain that implements the MRKL system.
Map-reduce chain.
Chain to run queries against LLMs.
This class is deprecated. See below for an example implementation using LangChain runnables:
from langchain_core.output_parsers import StrOutputP
Chain that interprets a prompt and executes python code to do math.
This class is deprecated. See below for a replacement implementation using LangGraph. The benefits of this impleme
A router chain that uses an LLM chain to perform routing.
This class is deprecated. See below for a replacement, which offers several benefits, including streaming and batch support.
Below is an exa
A multi-route chain that uses an LLM router chain to choose amongst prompts.
This class is deprecated. See below for a replacement, which offers several benefits, including streaming and batch suppor
Chain for applying constitutional principles.
This class is deprecated. See below for a replacement implementation using LangGraph. The benefits of this implementation are:
Chain for question-answering with self-verification.
Question answering chain with sources over documents.
Question answering with sources over documents.
Implement an LLM driven browser.
Security Note: This toolkit provides code to control a web-browser.
The web-browser can be used to navigate to:
- Any URL (including any internal networ
Combining documents by mapping a chain over them, then combining results.
We first call llm_chain on each document individually, passing in the
page_content and any other kwargs. This is the `map
Chain that splits documents, then analyzes it in pieces.
This chain is parameterized by a TextSplitter and a CombineDocumentsChain. This chain takes a single document as input, and then splits it up
Chain that combines documents by stuffing into context.
This chain takes a list of documents and first combines them into a single string. It does this by formatting each document into a string with
Combine documents by recursively reducing them.
This involves
combine_documents_chaincollapse_documents_chaincombine_documents_chain is ALWAYS provided. This is final chain that is call
Combine documents by doing a first pass and then refining on more documents.
This algorithm first calls initial_llm_chain on the first document, passing
that first document in with the variable nam
Combining documents by mapping a chain over them, then reranking results.
This algorithm calls an LLMChain on each input document. The LLMChain is expected to have an OutputParser that parses the res
Chain to have a conversation and load context from memory.
This class is deprecated in favor of RunnableWithMessageHistory. Please refer
to this tutorial for more detail: https://python.langchain.c
Chain for making a simple request to an API endpoint.
Base class for question-answering chains.
Chain for question-answering against an index.
This class is deprecated. See below for an example implementation using
create_retrieval_chain:
from langchain_classic.chains impor
Chain for question-answering against a vector database.
Chain for having a conversation based on retrieved documents.
This class is deprecated. See below for an example implementation using
create_retrieval_chain. Additional walkthroughs can be found at
Base class for question-answer generation chains.
This class is deprecated. See below for an alternative implementation.
Advantages of this implementation include:
Chain for question-answering with self-verification.
Document compressor that uses Cohere Rerank API.
Abstract base class for chat memory.
ATTENTION This abstraction was created prior to when chat models had native tool calling capabilities. It does NOT support native tool calling cap
Abstract base class for Entity store.
In-memory Entity store.
Upstash Redis backed Entity store.
Entities get a TTL of 1 day by default, and that TTL is extended by 3 days every time the entity is read back.
Redis-backed Entity store.
Entities get a TTL of 1 day by default, and that TTL is extended by 3 days every time the entity is read back.
SQLite-backed Entity store with safe query construction.
Entity extractor & summarizer memory.
Extracts named entities from the recent chat history and generates summaries. With a swappable entity store, persisting entities across conversations. Defaults t
A basic memory implementation that simply stores the conversation history.
This stores the entire conversation history in memory without any additional processing.
Note that additional processing ma
A basic memory implementation that simply stores the conversation history.
This stores the entire conversation history in memory without any additional processing.
Equivalent to ConversationBufferMe
Use to keep track of the last k turns of a conversation.
If the number of messages in the conversation is more than the maximum number of messages to keep, the oldest messages are dropped.
Buffer with summarizer for storing conversation memory.
Provides a running summary of the conversation together with the most recent messages in the conversation under the constraint that the total n
Vector Store Retriever Memory.
Store the conversation history in a vector store and retrieves the relevant parts of past conversation based on the input.
Mixin for summarizer.
Continually summarizes the conversation history.
The summary is updated after each conversation turn. The implementations returns a summary of the conversation history which can be used to provide co
Conversation chat memory with token limit.
Keeps only the most recent messages in the conversation under the constraint that the total number of tokens in the conversation does not exceed a certain l
Get information about the LangChain runtime environment.
Load an output parser.
Run on dataset.
Run the Chain or language model on a dataset and store traces to the specified project name.
For the (usually faster) async version of this function,
see arun_on_dataset.
Run on dataset.
Run the Chain or language model on a dataset and store traces to the specified project name.
For the (usually faster) async version of this function,
see arun_on_dataset.
Generate a random name.
Load a dataset from the LangChainDatasets on HuggingFace.
Load the requested evaluation chain specified by a string.
Parameters
evaluator : EvaluatorType The type of evaluator to load. llm : BaseLanguageModel, optional The language model
Load evaluators specified by a list of evaluator types.
Parameters
evaluators : Sequence[EvaluatorType] The list of evaluator types to load. llm : BaseLanguageModel, optional The l
Resolve the criteria for the pairwise evaluator.
Resolve the criteria to evaluate.
Parameters
criteria : CRITERIA_TYPE The criteria to evaluate the runs against. It can be: - a mapping of a criterion name to its description
Resolve the criteria for the pairwise evaluator.
Create a store for LangChain serializable objects from a bytes store.
Reads from this store are deserialized with `langchain_
Create a store for langchain Document objects from a bytes store.
This store does run time type checking to ensure that the values are
Document objects.
Validate tools for single input.
Create an agent that uses ReAct prompting.
Based on paper "ReAct: Synergizing Reasoning and Acting in Language Models" (https://arxiv.org/abs/2210.03629)
This implementation is base
Create an agent that uses XML to format its logic.
Create an agent aimed at supporting tools with multiple inputs.
Parse an AI message potentially containing tool_calls.
Parse an AI message potentially containing tool_calls.
Create an agent that uses OpenAI function calling.
A convenience method for creating a conversational retrieval agent.
Create an agent that uses tools.
Create an agent that uses self-ask with search prompting.
Create an agent that uses OpenAI tools.
Convert (AgentAction, tool output) tuples into FunctionMessages.
Convert (AgentAction, tool output) tuples into ToolMessage objects.
Construct the scratchpad that lets the agent continue its thought process.
Construct the scratchpad that lets the agent continue its thought process.
Format the intermediate steps as XML.
Create an agent that uses JSON to format its logic, build for Chat Models.
Return another example given a list of examples for a prompt.
Create retrieval chain that retrieves documents and then passes them on.
Create a chain that takes conversation history and returns documents.
If there is no chat_history, then the input is just passed directly to the
retriever. If there is chat_history, then the pr
Import error for load_llm.
Import error for load_llm_from_config.
Check if the language model is a LLM.
Check if the language model is a chat model.
Load summarizing chain.
Fix invalid filter directive.
Construct examples from input-output pairs.
Create query construction prompt.
Load a query constructor runnable chain.
Dummy decorator for when lark is not installed.
Return a parser for the query language.
Create a chain for passing a list of Documents to a model.
Split Document objects to subsets that each meet a cumulative len. constraint.
Execute a collapse function on a set of documents and merge their metadatas.
Execute a collapse function on a set of documents and merge their metadatas.
Return the kwargs for the LLMChain constructor.
Create a citation fuzzy match Runnable.
Example usage:
from langchain_classic.chains import create_citation_fuzzy_match_runnable
from langchain_openai import ChatOpenAI
mo
Create a chain that generates SQL queries.
Security Note: This chain generates SQL queries for the given database.
The SQLDatabase class provides a get_table_info method that can be used
t
Get the appropriate function output parser given the user functions.
Callback Handler that writes to a Streamlit app.
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
Determine if running within IPython or Jupyter.
Create a function that helps retrieve objects from their new locations.
The goal of this function is to help users transition from deprecated imports to new imports.
The function will raise deprecat
Yield unique elements of an iterable based on a key function.
Return the compression chain input.
Return the compression chain input.
Get the major version of Pydantic.
Get the prompt input key.
Push an object to the hub and returns the URL it can be viewed at in a browser.
Pull an object from the hub and returns it as a LangChain object.
Treat every prompt pulled from the hub as untrusted, regardless of the owner.
Initialize a chat model from any supported provider using a unified interface.
langchain.chat_models.init_chat_model insteadThis function lives in langchain-classic and is
Load agent from Config Dict.
Unified method for loading an agent from LangChainHub or local fs.
Load an agent executor given tools and LLM.
This function is no deprecated in favor of
create_agent from the langchain
package, which pro
Construct a VectorStore agent from an LLM and tools.
This class is deprecated. See below for a replacement that uses tool calling methods and LangGraph. Install LangGraph with:
Construct a VectorStore router agent from an LLM and tools.
This class is deprecated. See below for a replacement that uses tool calling methods and LangGraph. Install LangGraph with
Initialize an embeddings model from a model name and optional provider.
Must have the integration package corresponding to the model provider installed.
Load chain from Config Dict.
Unified method for loading a chain from LangChainHub or local fs.
Load question answering chain.
Load a query constructor chain.
Load a question answering with sources chain.
[Legacy] Create an LLM chain that uses OpenAI functions.
[Legacy] Create an LLMChain that uses an OpenAI function to get a structured output.
Create a citation fuzzy match chain.
Creates a chain that extracts information from a passage.
Creates a chain that extracts information from a passage using Pydantic schema.
Create a question answering chain with structure.
Create a question answering chain that returns an answer with sources based on schema.
Create a question answering chain that returns an answer with sources.
Create tagging chain from schema.
Create a chain that extracts information from a passage based on a schema.
This function is deprecated. Please use with_structured_output instead.
See example usa
Create tagging chain from Pydantic schema.
Create a chain that extracts information from a passage based on a Pydantic schema.
This function is deprecated. Please use with_structured_output instea
OpenAPI spec to OpenAI function JSON Schema.
Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI functions.
Create a chain for querying an API from a OpenAPI spec.
This function and all related utilities in this module are deprecated. Use LLM tool calling features directly
Creates a chain that extracts information from a passage.
Create a runnable sequence that uses OpenAI functions.
Create a runnable for extracting structured outputs.
Main entrypoint into package.
Keep here for backwards compatibility.
Deprecated module for BaseLanguageModel class, kept for backwards compatibility.
Keep here for backwards compatibility.
For backwards compatibility.
Interface with the LangChain Hub.
Experiment with different models.
Global values and configuration that apply to all of LangChain.
DEPRECATED: Kept for backwards compatibility.
For backwards compatibility.
Kept for backwards compatibility.
Memory maintains Chain state, incorporating context from past runs.
This module contains memory abstractions from LangChain v0.0.x.
These abstractions are now deprecated and will be removed in L
DEPRECATED: Kept for backwards compatibility.
DEPRECATED: Kept for backwards compatibility.
Prompt is the input to the model.
Prompt is often constructed from multiple components. Prompt classes and functions make constructing and working with prompts easy.
Logic for selecting examples to include in prompts.
LLMs.
LLM classes provide access to the large language model (LLM) APIs and services.
This module provides backward-compatible exports of core language model classes.
These classes are re-exported for compatibility with older versions of LangChain and allow users to import language mo
LangChain Runnable and the LangChain Expression Language (LCEL).
The LangChain Expression Language (LCEL) offers a declarative method to build production-grade programs that harness the power
Vector store stores embedded data and performs vector search.
One of the most common ways to store and search over unstructured data is to embed it and store the resulting embedding vectors, and
OutputParser classes parse the output of an LLM call.
Chat Models are a variation on language models.
While Chat Models use language models under the hood, the interface they expose is a bit different. Rather than expose a "text in, text out" API, t
LangSmith utilities.
This module provides utilities for connecting to LangSmith.
Evaluation
LangSmith helps you evaluate Chains and other langua
LangSmith evaluation utilities.
This module provides utilities for evaluating Chains and other language model applications using LangChain evaluators and LangSmith.
For more information on the LangS
A simple progress bar for the console.
Utilities for running language models or Chains over datasets.
Configuration for run evaluators.
Run evaluator wrapper for string evaluators.
Document Transformers are classes to transform Documents.
Document Transformers usually used to transform a lot of Documents in a single run.
Docstores are classes to store and load Documents.
The Docstore is a simplified version of the Document Loader.
Chat Loaders load chat messages from common communications platforms.
Load chat messages from various communications platforms such as Facebook Messenger, Telegram, and WhatsApp. The loaded chat
Evaluation chains for grading LLM and Chain outputs.
This module contains off-the-shelf evaluation chains for grading the output of LangChain primitives such as language models and chains.
**Loa
Interfaces to be implemented by general evaluators.
Loading datasets and evaluators.
Comparison evaluators.
This module contains evaluators for comparing the output of two models, be they LLMs, Chains, or otherwise. This can be used for scoring preferences, measuring similarity / sem
Prompts for comparing the outputs of two models for a given question.
This prompt is used to compare two responses and evaluate which one best follows the instructions and answers the question. The p
Base classes for comparing the output of two models.
Chains and utils related to evaluating question answering functionality.
LLM Chains for evaluating question answering.
LLM Chain for generating examples for question answering.
Criteria or rubric based evaluators.
These evaluators are useful for evaluating the output of a language model or chain against specified criteria or rubric.
Classes
CriteriaEvalChain : Eval
String distance evaluators.
String distance evaluators based on the RapidFuzz library.
Chains for evaluating ReAct style agents.
Prompt for trajectory evaluation chain.
A chain for evaluating ReAct style agents.
This chain is used to evaluate ReAct style agents by reasoning about the sequence of actions taken and their outcomes. It uses a language model chain (LLMCh
Evaluators for parsing strings.
Scoring evaluators.
This module contains evaluators for scoring on a 1-10 the output of models, be they LLMs, Chains, or otherwise. This can be based on a variety of criteria and or a reference answe
Prompts for scoring the outputs of a models for a given question.
This prompt is used to score the responses and evaluate how it follows the instructions and answers the question. The prompt is based
Base classes for scoring the output of a model on a scale of 1-10.
Evaluators that measure embedding distances.
A chain for comparing the output of two models using embeddings.
Utilities are the integrations with third-part systems and packages.
Other LangChain classes use Utilities to interact with third-part systems and packages.
For backwards compatibility.
DEPRECATED - use asyncio.timeout directly instead.
Graphs provide a natural language interface to graph databases.
Implementations of key-value stores and storage helpers.
Module provides implementations of various key-value stores that conform to a simple key-value interface.
The primary goal of these storages
In memory store that is not thread safe and has no eviction policy.
This is a simple implementation of the BaseStore using a dictionary that is useful primarily for unit testing purposes.
Schemas are the LangChain Base Classes and Interfaces.
LangChain Runnable and the LangChain Expression Language (LCEL).
The LangChain Expression Language (LCEL) offers a declarative method to build production-grade programs that harness the power
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 wh
Module definitions of agent types together with corresponding agents.
Interface for tools.
Chain that takes in an input and produces an action and action input.
Functionality for loading agents.
Load agent.
An agent designed to hold a conversation in addition to using tools.
An agent designed to hold a conversation in addition to using tools.
Implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.
Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.
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
Module implements an agent that uses OpenAI's APIs function enabled API.
Memory used to save agent output AND intermediate steps.
Module implements an agent that uses OpenAI's APIs function enabled API.
An agent designed to hold a conversation in addition to using tools.
An agent designed to hold a conversation in addition to using tools.
Agent toolkits contain integrations with various resources and services.
LangChain has a large ecosystem of integrations with various external resources like local and remote file systems, APIs and d
Jira Toolkit.
Slack toolkit.
OpenAPI spec agent.
Steam Toolkit.
Spark SQL agent.
Agent toolkit for interacting with vector stores.
VectorStore agent.
Toolkit for interacting with a vector store.
GitHub Toolkit.
Json agent.
MultiOn Toolkit.
Office365 toolkit.
Gmail toolkit.
Zapier Toolkit.
Local file management toolkit.
NASA Toolkit.
AINetwork toolkit.
GitLab Toolkit.
Playwright browser toolkit.
SQL agent.
Power BI agent.
Chain that does self ask with search.
Heavily borrowed from https://github.com/ofirpress/self-ask
Chain that does self-ask with search.
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. Dependi
Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.
Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.
Indexes.
Index is used to avoid writing duplicated content into the vectostore and to avoid over-writing content if it's unchanged.
Indexes also :
Create knowledge graphs from data.
Su
Graphs provide a natural language interface to graph databases.
Vectorstore stubs for the indexing api.
Relevant prompts for constructing indexes.
Embedding models.
Embedding models are wrappers around embedding models from different APIs and services.
Embedding models can be LLMs or not.
Module contains code for a cache backed embedder.
The cache backed embedder is a wrapper around an embedder that caches embeddings in a key-value store. The cache is used to avoid recomputing embeddi
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
Pass input through a moderation endpoint.
Base interface that all chains should implement.
Map-reduce chain.
Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one.
Chain pipeline where the outputs of one step feed directly into next.
Chain that just formats a prompt and calls an LLM.
Functionality for loading chains.
Chain that runs an arbitrary python function.
Chain that interprets a prompt and executes python code to do math.
Heavily borrowed from https://replit.com/@amasad/gptpy?v=1#main.py
Chain that interprets a prompt and executes python code to do math.
Base classes for LLM-powered router chains.
Prompt for the router chain in the multi-retrieval qa chain.
Base classes for chain routing.
Use a single chain to route an input to one of multiple llm chains.
Prompt for the router chain in the multi-prompt chain.
Use a single chain to route an input to one of multiple retrieval qa chains.
Load summarizing chains.
Constitutional AI.
The Chain runs self-critique based on the Constitutional AI method proposed by (Bai et al., 2022).
Chain for applying constitutional principles to the outputs of another chain.
Models for the Constitutional AI chain.
Constitutional principles.
Constitutional principles from https://arxiv.org/pdf/2212.08073.pdf (Bai et al. 2022) UnifiedObjectives v0.2 principles ("uo-*") adapted from https://examine.dev/docs/Unifi
Adapted from https://github.com/jzbjyb/FLARE.
Chain that tries to verify assumptions before answering a question.
Heavily borrowed from https://github.com/jagilley/fact-checker
Chain for question-answering with self-verification.
Load question answering chains.
Hypothetical Document Embeddings.
https://arxiv.org/abs/2212.10496
Hypothetical Document Embeddings.
https://arxiv.org/abs/2212.10496
LLM Chain for turning a user text query into a structured query.
Internal representation of a structured query language.
Chain for interacting with Elasticsearch Database.
Load question answering with sources chains.
Question answering with sources over documents.
Question-answering with sources over an index.
Load question answering with sources chains.
Question-answering with sources over a vector database.
Implement a GPT-3 driven browser.
Heavily influenced from https://github.com/nat/natbot
Implement an LLM driven browser.
Different ways to combine documents.
Combining documents by mapping a chain over them first, then combining results.
Base interface for chains combining documents.
Chain that combines documents by stuffing into context.
Combine many documents together by recursively reducing them.
Combine documents by doing a first pass and then refining on more documents.
Combining documents by mapping a chain over them first, then reranking results.
Chain that carries on a conversation from a prompt plus history.
Chain that carries on a conversation and calls an LLM.
Memory modules for conversation prompts.
Methods for creating chains that use OpenAI function-calling APIs.
Chain that makes API calls and summarizes the responses to answer a question.
Chain that makes API calls and summarizes the responses to answer a question.
Chain for question-answering against a vector database.
Chain for question-answering against a vector database.
Chain for chatting with a vector database.
Chain for chatting with a vector database.
Chain for interacting with SQL Database.
Summarization checker chain for verifying accuracy of text generation.
Chain that tries to verify the accuracy of text generation by splitting it into a list of facts, then checking if those facts ar
Chain for summarization with self-verification.
Callback handlers allow listening to events in LangChain.
Base callback handler that can be used to handle callbacks in langchain.
Callback Handler streams to stdout on new llm token.
Callback Handler streams to stdout on new llm token.
Tracers that record execution of LangChain runs.
A Tracer implementation that records to LangChain endpoint.
Base interfaces for tracing runs.
A tracer that runs evaluators over completed runs.
Serialization and deserialization.
Retriever class returns Documents given a text query.
It is more general than a vector store. A retriever does not need to be able to store documents, only to return (or retrieve) it. Vector
Ensemble Retriever.
Ensemble retriever that ensemble the results of multiple retrievers by using weighted Reciprocal Rank Fusion.
DocumentFilter that uses an LLM chain to extract the relevant parts of documents.
Filter that uses an LLM to drop documents that aren't relevant to the query.
Filter that uses an LLM to rerank documents listwise and select top-k.
Retriever that generates and executes structured queries over its own data source.
Utility functions for LangChain.
These functions do not depend on any other LangChain module.
Tools are classes that an Agent uses to interact with the world.
Each tool has a description. Agent uses the description to choose the right tool for the job.
Different methods for rendering Tools to be passed to LLMs.
Depending on the LLM you are using and the prompting strategy you are using, you may want Tools to be rendered in a different way. This mod
Jira Tool.
This module provides dynamic access to deprecated Jira tools.
When attributes like JiraAction are accessed, they are redirected to their new
locations in langchain_community.tools. This ensures b
Slack tools.
Utility functions for parsing an OpenAPI spec. Kept for backwards compat.
SceneXplain API toolkit.
Google Cloud Tools.
Golden API toolkit.
Bing Search API toolkit.
Arxiv API toolkit.
Tool to generate an image.
Steam API toolkit.
Tools for interacting with a GraphQL API.
Tools for interacting with Spark SQL.
Wolfram Alpha API toolkit.
Google Finance API Toolkit.
Simple tool wrapper around VectorDBQA chain.
Merriam-Webster API toolkit.
PubMed API toolkit.
Google Search API Toolkit.
GitHub Tool.
Google Places API Toolkit.
Shell tool.
Tools for interacting with a JSON file.
This module provides dynamic access to deprecated JSON tools in LangChain.
It ensures backward compatibility by forwarding references such as
JsonGetValueTool, JsonListKeysTool, and JsonSpec to
MutliOn Client API tools.
Google Lens API Toolkit.
Wikipedia API toolkit.
DataForSeo API Toolkit.
StackExchange API toolkit.
Google Trends API Toolkit.
O365 tools.
Azure Cognitive Services Tools.
Eleven Labs Services Tools.
Gmail tools.
Zapier Tool.
This module provides dynamic access to deprecated Zapier tools in LangChain.
It supports backward compatibility by forwarding references such as
ZapierNLAListActions and ZapierNLARunAction to the
Sleep tool.
File Management Tools.
Google Scholar API Toolkit.
Edenai Tools.
Amadeus tools.
Tools for making requests to an API endpoint.
Tavily Search API toolkit.
Tool for asking for human input.
OpenWeatherMap API toolkit.
Tools for interacting with the user.
GitLab Tool.
DuckDuckGo Search API toolkit.
Google Jobs API Toolkit.
Tools for interacting with a SQL database.
For backwards compatibility.
Unsupervised learning based memorization.
Browser tools and toolkit.
Metaphor Search API toolkit.
Tools for interacting with a PowerBI dataset.
Memory maintains Chain state, incorporating context from past runs.
Class for a conversation memory buffer with older messages stored in a vectorstore .
This implements a conversation memory in which the messages are stored in a memory buffer up to a specified token
Deprecated as of LangChain v0.3.4 and will be removed in LangChain v1.0.0.
Class for a VectorStore-backed memory object.
Document Loaders are classes to load Documents.
Document Loaders are usually used to load a lot of Documents in a single run.