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.
pip install 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.
An instance of a runnable stored in the LangChain Hub.
A function description for ChatOpenAI.
A runnable that routes to the selected function.
Interface for caching results from embedding models.
Wraps a store with key and value encoders/decoders.
BaseStore interface that works on the local file system.
Retrieve small chunks then retrieve their parent documents.
Enumerator of the types of search to perform.
Retriever that supports multiple embeddings per parent document.
Time Weighted Vector Store Retriever.
Retriever that ensembles the multiple retrievers.
Retriever that wraps a base retriever and compresses the results.
Retriever that merges the results of multiple retrievers.
Output parser for a list of lines.
Given a query, use an LLM to write a set of queries.
Given a query, use an LLM to re-phrase it.
Interface for cross encoder models.
Parse outputs that could return a null string of some sort.
LLM Chain Extractor.
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.
Embeddings Filter.
Document compressor that uses a pipeline of Transformers.
Self Query Retriever.
Retry chain input for RetryOutputParser.
Retry chain input for RetryWithErrorOutputParser.
Wrap a parser and try to fix parsing errors.
Wrap a parser and try to fix parsing errors.
Parse the output of an LLM call into a Dictionary using a regex.
Parse YAML output using a Pydantic model.
Schema for a response from a structured output parser.
Parse the output of an LLM call to a structured output.
Parse the output of an LLM call using a regex.
Parse the output of an LLM call to a datetime.
Parse an output using Pandas DataFrame format.
Combine multiple output parsers into one.
Parse an output that is one of a set of values.
Input for the retry chain of the OutputFixingParser.
Wrap a parser and try to fix parsing errors.
Parse the output of an LLM call to a boolean.
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.
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.
Configuration for a labeled score string evaluator.
A simple progress bar for the console.
Iterator for AgentExecutor.
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.
Agent powered by Runnables.
Agent powered by Runnables.
Tool that just returns the query.
Agent that is using tools.
Chat prompt template for the agent scratchpad.
Tool that is run when invalid tool name is encountered by agent.
Memory used to save agent output AND intermediate steps.
Output parser for the structured chat agent.
Output parser with retries for the structured chat agent.
Output parser for the ReAct agent.
Output parser for the conversational agent.
Parses ReAct-style LLM calls that have a single tool input in json format.
Parses a message into agent action/finish.
Parses a message into agent actions/finish.
Parses tool invocations and final answers in JSON format.
Parses tool invocations and final answers from XML-formatted agent output.
Parses ReAct-style LLM calls that have a single tool input.
Parses self-ask style LLM calls.
Tool agent action.
Parses a message into agent actions/finish.
Output parser for the conversational agent.
Information about a VectorStore.
Toolkit for interacting with a VectorStore.
Toolkit for routing between Vector Stores.
AgentFinish with run and thread metadata.
AgentAction with info needed to submit custom tool output to existing run.
Run an OpenAI Assistant.
MRKL Output parser for the chat agent.
Configuration for a chain to use in MRKL system.
Output parser for the chat agent.
Chain where the outputs of one chain feed directly into next.
Simple chain where the outputs of one step feed directly into next.
Chain that transforms the chain output.
Pass input through a moderation endpoint.
Base class for prompt selectors.
Prompt collection that goes through conditionals.
Abstract base class for creating structured sequences of calls to components.
Interface for the combine_docs method.
Interface for the combine_docs method.
Base interface for chains combining documents.
Raise an ImportError if APIChain is used without langchain_community.
Chain for interacting with Elasticsearch Database.
Generate hypothetical document for query, and then embed that.
Output parser that checks if the output is finished.
Chain that generates questions from uncertain spans.
Flare chain.
Chain that uses embeddings to route between options.
Multi Retrieval QA Chain.
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.
Interface for loading the combine documents chain.
Question-answering with sources over an index.
Question-answering with sources over a vector database.
A typed dictionary containing information about elements in the viewport.
A crawler for web pages.
Interface for loading the combine documents chain.
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.
Information about a data source attribute.
Output parser that parses a structured query.
Interface for loading the combine documents chain.
Input for a SQL Chain.
Input for a SQL Chain.
Input type for ConversationalRetrievalChain.
Chain for chatting with an index.
Chain for chatting with a vector database.
Class for a constitutional principle.
An answer to the question, with sources.
Chain for making a simple request to an API endpoint.
Class representing a single statement.
A question and its answer as a list of facts.
Callback handler for streaming in agents.
Callback handler that returns an async iterator.
Callback handler that returns an async iterator.
Tracer that logs via the input Logger.
Simple Memory.
Combining multiple memories' data together.
Conversation chat memory with token limit and vectordb backing.
Memory wrapper that is read-only and cannot be changed.
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.
The types of the evaluators.
A base class for evaluators that use an LLM.
String evaluator interface.
Compare the output of two models (or two outputs of the same model).
Interface for evaluating agent trajectories.
Compute an exact match between the prediction and the reference.
A Criteria to evaluate.
A parser for the output of the CriteriaEvalChain.
LLM Chain for evaluating runs against criteria.
Criteria evaluation chain that requires references.
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.
LLM Chain for generating examples for question answering.
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.
Distance metric to use.
Compute string distances between the prediction and the reference.
Compute string edit distances between two predictions.
Embedding Distance Metric.
Embedding distance evaluation chain.
Use embedding distances to score semantic difference between two predictions.
A named tuple containing the score and reasoning for a trajectory.
Trajectory output parser.
A chain for evaluating ReAct style agents.
An evaluator that validates a JSON prediction against a JSON schema reference.
An evaluator that calculates the edit distance between JSON strings.
Evaluate whether the prediction is valid JSON.
Json Equality Evaluator.
A parser for the output of the PairwiseStringEvalChain.
Pairwise String Evaluation Chain.
Labeled Pairwise String Evaluation Chain.
Compute a regex match between the prediction and the reference.
Abstract base class for memory in Chains.
Document compressor that uses Cohere Rerank API.
Base class for single action agents.
Agent that calls the language model and deciding the action.
An enum for agent types.
An Agent driven by OpenAIs function powered API.
Agent that uses XML tags.
Agent driven by OpenAIs function powered API.
Structured Chat Agent.
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.
An agent that holds a conversation in addition to using tools.
An agent designed to hold a conversation in addition to using tools.
Agent for the self-ask-with-search paper.
[Deprecated] Chain that does self-ask with search.
Agent for the MRKL chain.
Chain that implements the MRKL system.
Chat Agent.
Map-reduce chain.
Chain to run queries against LLMs.
Combining documents by mapping a chain over them, then reranking results.
Chain that combines documents by stuffing into context.
Combine documents 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, then combining results.
Chain that splits documents, then analyzes it in pieces.
Chain for question-answering with self-verification.
A multi-route chain that uses an LLM router chain to choose amongst prompts.
A router chain that uses an LLM chain to perform routing.
Base class for question-answer generation chains.
Question answering chain with sources over documents.
Question answering with sources over documents.
Implement an LLM driven browser.
Chain for question-answering with self-verification.
Chain for having a conversation based on retrieved documents.
Chain to have a conversation and load context from memory.
Chain for applying constitutional principles.
Chain that interprets a prompt and executes python code to do math.
Base class for question-answering chains.
Chain for question-answering against an index.
Chain for question-answering against a vector database.
Conversation chat memory with token limit.
Use to keep track of the last k turns of a conversation.
Vector Store Retriever Memory.
Mixin for summarizer.
Continually summarizes the conversation history.
A basic memory implementation that simply stores the conversation history.
A basic memory implementation that simply stores the conversation history.
Abstract base class for chat memory.
Abstract base class for Entity store.
In-memory Entity store.
Upstash Redis backed Entity store.
Redis-backed Entity store.
SQLite-backed Entity store with safe query construction.
Entity extractor & summarizer memory.
Buffer with summarizer for storing conversation memory.
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.
Get information about the LangChain runtime environment.
Get the major version of Pydantic.
Initialize an embeddings model from a model name and optional provider.
Create a store for LangChain serializable objects from a bytes store.
Create a store for langchain Document objects from a bytes store.
Yield unique elements of an iterable based on a key function.
Return the compression chain input.
Return the compression chain input.
Initialize a chat model from any supported provider using a unified interface.
Load an output parser.
Run on dataset.
Run on dataset.
Generate a random name.
Validate tools for single input.
Create an agent that uses OpenAI function calling.
Create an agent that uses XML to format its logic.
Create an agent aimed at supporting tools with multiple inputs.
Create an agent that uses ReAct prompting.
Create an agent that uses JSON to format its logic, build for Chat Models.
Parse an AI message potentially containing tool_calls.
Parse an AI message potentially containing tool_calls.
A convenience method for creating a conversational retrieval agent.
Construct the scratchpad that lets the agent continue its thought process.
Convert (AgentAction, tool output) tuples into FunctionMessages.
Format the intermediate steps as XML.
Construct the scratchpad that lets the agent continue its thought process.
Convert (AgentAction, tool output) tuples into ToolMessage objects.
Create an agent that uses tools.
Create an agent that uses self-ask with search prompting.
Create an agent that uses OpenAI tools.
Import error for load_llm.
Import error for load_llm_from_config.
Create a chain that takes conversation history and returns documents.
Create retrieval chain that retrieves documents and then passes them on.
Return another example given a list of examples for a prompt.
Check if the language model is a LLM.
Check if the language model is a chat model.
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.
Dummy decorator for when lark is not installed.
Return a parser for the query language.
Fix invalid filter directive.
Construct examples from input-output pairs.
Create query construction prompt.
Load a query constructor runnable chain.
Load summarizing chain.
Create a chain that generates SQL queries.
Get the appropriate function output parser given the user functions.
Return the kwargs for the LLMChain constructor.
OpenAPI spec to OpenAI function JSON Schema.
Create a citation fuzzy match Runnable.
Callback Handler that writes to a Streamlit app.
Create a function that helps retrieve objects from their new locations.
Determine if running within IPython or Jupyter.
Get the prompt input key.
Load a dataset from the LangChainDatasets on HuggingFace.
Load the requested evaluation chain specified by a string.
Load evaluators specified by a list of evaluator types.
Resolve the criteria to evaluate.
Resolve the criteria for the pairwise evaluator.
Resolve the criteria for the pairwise evaluator.
Load agent from Config Dict.
Unified method for loading an agent from LangChainHub or local fs.
Load an agent executor given tools and LLM.
Construct a VectorStore agent from an LLM and tools.
Construct a VectorStore router agent from an LLM and tools.
Load chain from Config Dict.
Unified method for loading a chain from LangChainHub or local fs.
Load a question answering with sources chain.
Load question answering chain.
Load a query constructor chain.
Create a runnable sequence that uses OpenAI functions.
Create a runnable for extracting structured outputs.
Creates a chain that extracts information from a passage.
Create a question answering chain with structure.
Create a question answering chain that returns an answer with sources.
Create tagging chain from schema.
Create tagging chain from Pydantic schema.
Create a chain for querying an API from a OpenAPI spec.
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.
[Legacy] Create an LLM chain that uses OpenAI functions.
[Legacy] Create an LLMChain that uses an OpenAI function to get a structured output.
Main entrypoint into package.
Interface with the LangChain Hub.
Experiment with different models.
DEPRECATED: Kept for backwards compatibility.
DEPRECATED: Kept for backwards compatibility.
Memory maintains Chain state, incorporating context from past runs.
For backwards compatibility.
Keep here for backwards compatibility.
Kept for backwards compatibility.
For backwards compatibility.
Keep here for backwards compatibility.
Global values and configuration that apply to all of LangChain.
DEPRECATED: Kept for backwards compatibility.
Deprecated module for BaseLanguageModel class, kept for backwards compatibility.
Document Loaders are classes to load Documents.
Schemas are the LangChain Base Classes and Interfaces.
LangChain Runnable and the LangChain Expression Language (LCEL).
Utility functions for LangChain.
LangChain Runnable and the LangChain Expression Language (LCEL).
Embedding models.
Module contains code for a cache backed embedder.
Implementations of key-value stores and storage helpers.
In memory store that is not thread safe and has no eviction policy.
Retriever class returns Documents given a text query.
Ensemble Retriever.
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.
Serialization and deserialization.
Chat Loaders load chat messages from common communications platforms.
Chat Models are a variation on language models.
OutputParser classes parse the output of an LLM call.
Tools are classes that an Agent uses to interact with the world.
Different methods for rendering Tools to be passed to LLMs.
Jira Tool.
This module provides dynamic access to deprecated Jira tools.
File Management Tools.
Zapier Tool.
This module provides dynamic access to deprecated Zapier tools in LangChain.
OpenWeatherMap API toolkit.
Steam API toolkit.
GitLab Tool.
Tools for interacting with Spark SQL.
Google Scholar API Toolkit.
Tools for interacting with a GraphQL API.
StackExchange API toolkit.
Google Cloud Tools.
Merriam-Webster API toolkit.
Tools for interacting with a PowerBI dataset.
Slack tools.
Tool for asking for human input.
Azure Cognitive Services Tools.
Browser tools and toolkit.
Utility functions for parsing an OpenAPI spec. Kept for backwards compat.
PubMed API toolkit.
Google Search API Toolkit.
Tools for making requests to an API endpoint.
Simple tool wrapper around VectorDBQA chain.
SceneXplain API toolkit.
GitHub Tool.
Amadeus tools.
Google Places API Toolkit.
Tools for interacting with a SQL database.
For backwards compatibility.
O365 tools.
Shell tool.
Tools for interacting with a JSON file.
This module provides dynamic access to deprecated JSON tools in LangChain.
Gmail tools.
Edenai Tools.
Google Trends API Toolkit.
Wikipedia API toolkit.
Eleven Labs Services Tools.
Golden API toolkit.
Google Finance API Toolkit.
Google Lens API Toolkit.
Bing Search API toolkit.
DataForSeo API Toolkit.
MutliOn Client API tools.
Arxiv API toolkit.
Tavily Search API toolkit.
Sleep tool.
Google Jobs API Toolkit.
Unsupervised learning based memorization.
Metaphor Search API toolkit.
Tool to generate an image.
Wolfram Alpha API toolkit.
Tools for interacting with the user.
DuckDuckGo Search API toolkit.
Utilities are the integrations with third-part systems and packages.
Shims for asyncio features that may be missing from older python versions.
For backwards compatibility.
Graphs provide a natural language interface to graph databases.
LangSmith utilities.
LangSmith evaluation utilities.
Run evaluator wrapper for string evaluators.
Utilities for running language models or Chains over datasets.
Configuration for run evaluators.
A simple progress bar for the console.
Agent is a class that uses an LLM to choose a sequence of actions to take.
Functionality for loading agents.
Chain that takes in an input and produces an action and action input.
Module definitions of agent types together with corresponding agents.
Load agent.
Interface for tools.
Memory used to save agent output AND intermediate steps.
Module implements an agent that uses OpenAI's APIs function enabled API.
Module implements an agent that uses OpenAI's APIs function enabled API.
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.
An agent designed to hold a conversation in addition to using tools.
An agent designed to hold a conversation in addition to using tools.
Parsing utils to go from string to AgentAction or Agent Finish.
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.
Jira Toolkit.
Local file management toolkit.
Zapier Toolkit.
Steam Toolkit.
GitLab Toolkit.
Spark SQL agent.
Power BI agent.
Slack toolkit.
SQL agent.
AINetwork toolkit.
Playwright browser toolkit.
OpenAPI spec agent.
Agent toolkit for interacting with vector stores.
Toolkit for interacting with a vector store.
VectorStore agent.
GitHub Toolkit.
Office365 toolkit.
Json agent.
Gmail toolkit.
NASA Toolkit.
MultiOn Toolkit.
Logic for formatting intermediate steps into an agent scratchpad.
Chain that does self ask with search.
Chain that does self-ask with search.
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.
Docstores are classes to store and load Documents.
Document Transformers are classes to transform Documents.
Prompt is the input to the model.
Logic for selecting examples to include in prompts.
Chains are easily reusable components linked together.
Functionality for loading chains.
Map-reduce chain.
Chain pipeline where the outputs of one step feed directly into next.
Chain that runs an arbitrary python function.
Chain that just formats a prompt and calls an LLM.
Pass input through a moderation endpoint.
Base interface that all chains should implement.
Different ways to combine documents.
Combining documents by mapping a chain over them first, then reranking results.
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 combining results.
Base interface for chains combining documents.
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 that tries to verify assumptions before answering a question.
Chain for question-answering with self-verification.
Chain for interacting with Elasticsearch Database.
Hypothetical Document Embeddings.
Hypothetical Document Embeddings.
Adapted from https://github.com/jzbjyb/FLARE.
Prompt for the router chain in the multi-prompt chain.
Use a single chain to route an input to one of multiple llm chains.
Prompt for the router chain in the multi-retrieval qa chain.
Use a single chain to route an input to one of multiple retrieval qa chains.
Base classes for LLM-powered router chains.
Base classes for chain routing.
Load question answering with sources chains.
Load question answering with sources chains.
Question-answering with sources over an index.
Question-answering with sources over a vector database.
Question answering with sources over documents.
Implement a GPT-3 driven browser.
Implement an LLM driven browser.
Load question answering chains.
Internal representation of a structured query language.
LLM Chain for turning a user text query into a structured query.
Load summarizing chains.
Chain for interacting with SQL Database.
Summarization checker chain for verifying accuracy of text generation.
Chain for summarization with self-verification.
Chain for chatting with a vector database.
Chain for chatting with a vector database.
Chain that carries on a conversation from a prompt plus history.
Memory modules for conversation prompts.
Chain that carries on a conversation and calls an LLM.
Constitutional AI.
Constitutional principles.
Models for the Constitutional AI chain.
Chain for applying constitutional principles to the outputs of another chain.
Chain that interprets a prompt and executes python code to do math.
Chain that interprets a prompt and executes python code to do math.
Chain for question-answering against a vector database.
Chain for question-answering against a vector database.
Methods for creating chains that use OpenAI function-calling APIs.
Callback handlers allow listening to events in LangChain.
Callback Handler streams to stdout on new llm token.
Callback Handler streams to stdout on new llm token.
Base callback handler that can be used to handle callbacks in langchain.
Tracers that record execution of LangChain runs.
A tracer that runs evaluators over completed runs.
A Tracer implementation that records to LangChain endpoint.
Base interfaces for tracing runs.
Vector store stores embedded data and performs vector search.
Memory maintains Chain state, incorporating context from past runs.
Class for a VectorStore-backed memory object.
Class for a conversation memory buffer with older messages stored in a vectorstore .
Deprecated as of LangChain v0.3.4 and will be removed in LangChain v1.0.0.
Indexes.
Graphs provide a natural language interface to graph databases.
Vectorstore stubs for the indexing api.
Relevant prompts for constructing indexes.
LLMs.
This module provides backward-compatible exports of core language model classes.
Evaluation chains for grading LLM and Chain outputs.
Loading datasets and evaluators.
Interfaces to be implemented by general evaluators.
Criteria or rubric based evaluators.
Scoring evaluators.
Prompts for scoring the outputs of a models for a given question.
Base classes for scoring the output of a model on a scale of 1-10.
Chains and utils related to evaluating question answering functionality.
LLM Chain for generating examples for question answering.
LLM Chains for evaluating question answering.
String distance evaluators.
String distance evaluators based on the RapidFuzz library.
Evaluators that measure embedding distances.
A chain for comparing the output of two models using embeddings.
Chains for evaluating ReAct style agents.
Prompt for trajectory evaluation chain.
A chain for evaluating ReAct style agents.
Evaluators for parsing strings.
Comparison evaluators.
Prompts for comparing the outputs of two models for a given question.
Base classes for comparing the output of two models.