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-core
LangChain Core contains the base abstractions that power the LangChain ecosystem.
These abstractions are designed to be as modular and simple as possible.
The benefit of having these abstractions is that any provider can implement the required interface and then easily be used in the rest of the LangChain ecosystem.
The LangChain ecosystem is built on top of langchain-core. Some of the benefits:
For full documentation, see the API reference. For conceptual guides, tutorials, and examples on using LangChain, see the LangChain Docs. You can also chat with the docs using Chat LangChain.
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.
Defines interface for IR translation using a visitor pattern.
Base class for all expressions.
Enumerator of the operations.
Enumerator of the comparison operators.
Filtering expression.
Comparison to a value.
Logical operation over other directives.
Structured query.
Base abstract class for inputs to any language model.
PromptValues can be converted to both LLM (pure text-generation) inputs and
chat model inputs.
String prompt value.
Chat prompt value.
A type of a prompt value that is built from messages.
Image URL for multimodal model inputs (OpenAI format).
Represents the inner image_url object in OpenAI's Chat Completion API format. This
is used by ImagePromptTemplate and ChatPromptTemplate.
Image prompt value.
Chat prompt value which explicitly lists out the message types it accepts.
For use in external schemas.
Base class for chat loaders.
Abstract interface for a key-value store.
This is an interface that's meant to abstract away the details of different key-value stores. It provides a simple interface for getting, setting, and deleti
In-memory implementation of the BaseStore using a dictionary.
In-memory store for any type of data.
In-memory store for bytes.
Raised when a key is invalid; e.g., uses incorrect characters.
Chat Session.
Chat Session represents a single conversation, channel, or other group of messages.
Base class for rate limiters.
Usage of the base limiter is through the acquire and aacquire methods depending on whether running in a sync or async context.
Implementations are free to add a timeout
An in memory rate limiter based on a token bucket algorithm.
This is an in memory rate limiter, so it cannot rate limit across different processes.
The rate limiter only allows time-based rate limit
Interface for cross encoder models.
Interface for a caching layer for LLMs and Chat models.
The cache interface consists of the following methods:
llm_string.Cache that stores things in memory.
Represents a request to execute an action by an agent.
The action consists of the name of the tool to execute and the input to pass to the tool. The log is used to pass along extra information about
Representation of an action to be executed by an agent.
This is similar to AgentAction, but includes a message log consisting of
chat messages.
This is useful when working with ChatModels, and i
Result of running an AgentAction.
Final return value of an ActionAgent.
Agents return an AgentFinish when they have reached a stopping condition.
General LangChain exception.
Base class for exceptions in tracers module.
Exception that output parsers should raise to signify a parsing error.
This exists to differentiate parsing errors from other code or execution errors that also may arise inside the output parser.
`
Base exception for failures related to model invocation.
Subclasses correspond to conditions that model providers report consistently, so the same condition maps to the same exception type regardless
Exception raised when model provider authentication fails (HTTP 401).
Exception raised when credentials lack permission for a request (HTTP 403).
Exception raised when a provider rejects a request as invalid (e.g. HTTP 400).
Exception raised when the requested model cannot be found (HTTP 404).
Exception raised when a model provider rate limit is exceeded (HTTP 429).
Exception raised when a model provider reports a server failure (HTTP 5xx).
Exception raised when a model provider cannot be reached.
Exception raised when a model request times out.
Exception raised when input exceeds the model's context limit.
This exception is raised by chat models when the input tokens exceed the maximum context window supported by the model.
Exception raised when a model declines to produce the requested output.
Providers report a refusal as a successful response rather than an HTTP error
(for example Anthropic's stop_reason="refusal",
Error codes.
LangSmith parameters for tracing.
Abstract base class for a document retrieval system.
A retrieval system is defined as something that can take string queries and return the most 'relevant' documents from some source.
Usage:
A retr
Runnable to passthrough inputs unchanged or with additional keys.
This Runnable behaves almost like the identity function, except that it
can be configured to add additional keys to the output, if
Runnable that assigns key-value pairs to dict[str, Any] inputs.
The RunnableAssign class takes input dictionaries and, through a
RunnableParallel instance, applies transformations, then combine
Runnable that picks keys from dict[str, Any] inputs.
RunnablePick class represents a Runnable that selectively picks keys from a
dictionary input. It allows you to specify one or more keys to
Serializable Runnable that can be dynamically configured.
A DynamicRunnable should be initiated using the configurable_fields or
configurable_alternatives method of a Runnable.
Runnable that can be dynamically configured.
A RunnableConfigurableFields should be initiated using the
configurable_fields method of a Runnable.
Here is an example of using a `RunnableConfi
String enum.
Runnable that can be dynamically configured.
A RunnableConfigurableAlternatives should be initiated using the
configurable_alternatives method of a Runnable or can be
initiated directly as we
Parameters for tenacity.wait_exponential_jitter.
Retry a Runnable if it fails.
RunnableRetry can be used to add retry logic to any object that subclasses the base Runnable.
Such retries are especially useful for network calls that may fail due to
Runnable that can fallback to other Runnable objects if it fails.
External APIs (e.g., APIs for a language model) may at times experience degraded performance or even downtime.
In these cases, i
Data associated with a streaming event.
Streaming event.
Schema of a streaming event which is produced from the astream_events method.
A standard stream event that follows LangChain convention for event data.
Custom stream event created by the user.
VertexViewer class.
Class to define vertex box boundaries that will be accounted for during graph building by grandalf.
Class for drawing in ASCII.
Check if a name is a local dict.
Check if the first argument of a function is a dict.
Get nonlocal variables accessed.
Get the nonlocal variables accessed of a function.
Get the source code of a lambda function.
Dictionary that can be added to another dictionary.
Protocol for objects that support addition.
Field that can be configured by the user.
Field that can be configured by the user with a default value.
Field that can be configured by the user with multiple default values.
Field that can be configured by the user. It is a specification of a field.
Router input.
Runnable that routes to a set of Runnable based on Input['key'].
Returns the output of the selected Runnable.
Runnable that selects which branch to run based on a condition.
The Runnable is initialized with a list of (condition, Runnable) pairs and
a default branch.
When operating on an input, the fir
Runnable that manages chat message history for another Runnable.
A chat message history is a sequence of messages that represent a conversation.
RunnableWithMessageHistory wraps another `Runna
Helper class to draw a state graph into a PNG file.
It requires graphviz and pygraphviz to be installed.
A unit of work that can be invoked, batched, streamed, transformed and composed.
Key Methods
invoke/ainvoke: Transforms a single input into an output.batch/abatch: EfficientRunnable that can be serialized to JSON.
Sequence of Runnable objects, where the output of one is the input of the next.
RunnableSequence is the most important composition operator in LangChain
as it is used in virtually every chain
Runnable that runs a mapping of Runnables in parallel.
Returns a mapping of their outputs.
RunnableParallel is one of the two main composition primitives,
alongside RunnableSequence. It invoke
Runnable that runs a generator function.
RunnableGenerators can be instantiated directly or by using a generator within
a sequence.
RunnableGenerators can be used to implement custom behavior,
RunnableLambda converts a python callable into a Runnable.
Wrapping a callable in a RunnableLambda makes the callable usable
within either a sync or async context.
RunnableLambda can be comp
RunnableEachBase class.
Runnable that calls another Runnable for each element of the input sequence.
Use only if creating a new RunnableEach subclass with different __init__
args.
See docum
RunnableEach class.
Runnable that calls another Runnable for each element of the input sequence.
It allows you to call multiple inputs with the bounded Runnable.
RunnableEach makes it easy
Runnable that delegates calls to another Runnable with a set of **kwargs.
Use only if creating a new RunnableBinding subclass with different __init__
args.
See documentation for `RunnableB
Wrap a Runnable with additional functionality.
A RunnableBinding can be thought of as a "runnable decorator" that
preserves the essential features of Runnable; i.e., batching, streaming,
and as
Protocol for objects that can be converted to a string.
Dictionary of labels for nodes and edges in a graph.
Edge in a graph.
Node in a graph.
Branch in a graph.
Enum for different curve styles supported by Mermaid.
Schema for Hexadecimal color codes for different node types.
Enum for different draw methods supported by Mermaid.
Graph of nodes and edges.
Empty dict type.
Configuration for a Runnable.
Custom values
The TypedDict has total=False set intentionally to:
merge_configsThreadPoolExecutor that copies the context to the child thread.
Use to represent the result of a chat model call with a single prompt.
This container is used internally by some implementations of chat model, it will eventually be mapped to a more general `LLMResu
A single text generation output.
Generation represents the response from an "old-fashioned" LLM (string-in, string-out) that generates regular text (not chat messages).
This model is used internally
GenerationChunk, which can be concatenated with other Generation chunks.
A container for results of an LLM call.
Both chat models and LLMs generate an LLMResult object. This object contains the
generated outputs and any additional information that the model provider wan
A single chat generation output.
A subclass of Generation that represents the response from a chat model that
generates chat messages.
The message attribute is a structured representation of the
ChatGeneration chunk.
ChatGeneration chunks can be concatenated with other ChatGeneration chunks.
Class that contains metadata for a single execution of a chain or model.
Defined for backwards compatibility with older versions of langchain_core.
"This model will likely be deprecate
Interface for embedding models.
This is an interface meant for implementing text embedding models.
Text embedding models are used to map text to a vector (a point in n-dimensional space).
Texts tha
Fake embedding model for unit testing purposes.
This embedding model creates embeddings by sampling from a normal distribution.
Do not use this outside of testing, as it i
Deterministic fake embedding model for unit testing purposes.
This embedding model creates embeddings by sampling from a normal distribution with a seed based on the hash of the text.
"To
Abstract base class for document transformation.
A document transformation takes a sequence of Document objects and returns a
sequence of transformed Document objects.
Base class for content used in retrieval and data processing workflows.
Provides common fields for content that needs to be stored, indexed, or searched.
For multimodal content in **ch
Raw data abstraction for document loading and file processing.
Represents raw bytes or text, either in-memory or by file reference. Used primarily by document loaders to decouple data loading from pa
Class for storing a piece of text and associated metadata.
Document is for retrieval workflows, not chat I/O. For sending text
to an LLM in a conversation, use message types f
Base class for document compressors.
This abstraction is primarily used for post-processing of retrieved documents.
Document objects matching a given query are first retrieved.
Then the list of d
Tool that can operate on any number of inputs.
Raised when args_schema is missing or has an incorrect type annotation.
Exception thrown when a tool execution error occurs.
This exception allows tools to signal errors without stopping the agent.
The error is handled according to the tool's handle_tool_error setting
Base class for all LangChain tools.
This abstract class defines the interface that all LangChain tools must implement.
Tools are components that can be called by agents to perform specific actions.
Annotation for tool arguments that are injected at runtime.
Tool arguments annotated with this class are not included in the tool schema sent to language models and are instead injected during execut
Annotation for injecting the tool call ID.
This annotation is used to mark a tool parameter that should receive the tool call ID at runtime.
from typing import Annotated
from langchain_cor
Base class for toolkits containing related tools.
A toolkit is a collection of related tools that can be used together to accomplish a specific task or work with a particular system.
Tool that takes in function or coroutine directly.
Input to the retriever.
Information about a run.
This is used to keep track of the metadata associated with a run.
Tracer that collects all nested runs in a list.
This tracer is useful for inspection and evaluation purposes.
Implementation of the SharedTracer that POSTS to the LangChain endpoint.
A single entry in the run log.
State of the run.
Patch to the run log.
Run log.
Tracer that streams run logs to a stream.
Base interface for tracers.
Async base interface for tracers.
Tracer that calls a function with a single str parameter.
Tracer that prints to the console.
Tracer that runs a run evaluator whenever a run is persisted.
Tracer that calls listeners on run start, end, and error.
Async tracer that calls listeners on run start, end, and error.
Reviver for JSON objects.
Used as the object_hook for json.loads to reconstruct LangChain objects from
their serialized JSON representation.
Only classes in the allowlist can be instantiated.
Base class for serialized objects.
Serialized constructor.
Serialized secret.
Serialized not implemented.
Serializable base class.
This class is used to serialize objects to JSON.
It relies on the following methods and properties:
is_lc_serializable][langchain_core.load.serializable.Serializable.iSelect examples based on semantic similarity.
Select examples based on Max Marginal Relevance.
This was shown to improve performance in this paper: https://arxiv.org/pdf/2211.13892.pdf
Select examples based on length.
Interface for selecting examples to include in prompts.
In-memory vector store implementation.
Uses a dictionary, and computes cosine similarity for search using numpy.
Interface for vector store.
Base Retriever class for VectorStore.
Base class for run manager (a bound callback manager).
Synchronous run manager.
Synchronous parent run manager.
Async run manager.
Async parent run manager.
Callback manager for LLM run.
Async callback manager for LLM run.
Callback manager for chain run.
Async callback manager for chain run.
Callback manager for tool run.
Async callback manager for tool run.
Callback manager for retriever run.
Async callback manager for retriever run.
Callback manager for LangChain.
Callback manager for the chain group.
Async callback manager that handles callbacks from LangChain.
Async callback manager for the chain group.
Callback handler that writes to a file.
This handler supports both context manager usage (recommended) and direct instantiation (deprecated) for backwards compatibility.
Callback Handler that tracks AIMessage.usage_metadata.
Callback handler for streaming.
Mixin for Retriever callbacks.
Mixin for LLM callbacks.
Mixin for chain callbacks.
Mixin for tool callbacks.
Mixin for callback manager.
Mixin for run manager.
Base callback handler.
Base async callback handler.
Base callback manager.
Callback handler that prints to std out.
Message from the user.
A HumanMessage is a message that is passed in from a user to the model.
Human Message chunk.
Message for priming AI behavior.
The system message is usually passed in as the first of a sequence of input messages.
System Message chunk.
Breakdown of input token counts.
Does not need to sum to full input token count. Does not need to have all keys.
Breakdown of output token counts.
Does not need to sum to full output token count. Does not need to have all keys.
Usage metadata for a message, such as token counts.
This is a standard representation of token usage that is consistent across models.
Message from an AI.
An AIMessage is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both the raw output as returned by the mod
Message chunk from an AI (yielded when streaming).
Message for passing the result of executing a tool back to a model.
FunctionMessage are an older version of the ToolMessage schema, and
do not contain the tool_call_id field.
The `tool_call_id
Function Message chunk.
Which feature added a message, and that feature's fields.
Message responsible for deleting other messages.
Annotation for citing data from a document.
start/end indices refer to the response text,
not the source text. This means that the indices are relative to the model's
re
Provider-specific annotation format.
Text output from a LLM.
This typically represents the main text content of a message, such as the response from a language model or the text of a user message.
`crea
Represents an AI's request to call a tool.
A chunk of a tool call (yielded when streaming).
When merging ToolCallChunks (e.g., via AIMessageChunk.__add__),
all string attributes are concatenated. Chunks are only merged if their
values of
Allowance for errors made by LLM.
Here we add an error key to surface errors made during generation
(e.g., invalid JSON arguments.)
Tool call that is executed server-side.
For example: code execution, web search, etc.
A chunk of a server-side tool call (yielded when streaming).
Result of a server-side tool call.
Reasoning output from a LLM.
create_reasoning_block may also be used as a factory to create a
ReasoningContentBlock. Benefits include:
An explicit refusal reported by the model provider.
Providers report refusals differently: OpenAI returns refusal content, while Anthropic reports a refusal stop reason on the response. Both are repr
Image data.
create_image_block may also be used as a factory to create an
ImageContentBlock. Benefits include:
Video data.
create_video_block may also be used as a factory to create a
VideoContentBlock. Benefits include:
Audio data.
create_audio_block may also be used as a factory to create an
AudioContentBlock. Benefits include:
Plaintext data (e.g., from a .txt or .md document).
A PlainTextContentBlock existed in langchain-core<1.0.0. Although the
name has carried over, the structure has changed si
File data that doesn't fit into other multimodal block types.
This block is intended for files that are not images, audio, or plaintext. For example, it can be used for PDFs, Word documents, etc.
If
Provider-specific content data.
This block contains data for which there is not yet a standard type.
The purpose of this block should be to simply hold a provider-specific payload. If a provider's n
Mixin for objects that tools can return directly.
If a custom BaseTool is invoked with a ToolCall and the output of custom code is
not an instance of ToolOutputMixin, the output will automaticall
Message for passing the result of executing a tool back to a model.
ToolMessage objects contain the result of a tool invocation. Typically, the result
is encoded inside the content field.
`tool_
Tool Message chunk.
Represents an AI's request to call a tool.
A chunk of a tool call (yielded when streaming).
When merging ToolCallChunk objects (e.g., via AIMessageChunk.__add__), all
string attributes are concatenated. Chunks are only merged if their val
String-like object that supports both property and method access patterns.
Exists to maintain backward compatibility while transitioning from method-based to property-based text access in message obj
Base abstract message class.
Messages are the inputs and outputs of a chat model.
Examples include HumanMessage,
AIMessage, and
Message chunk, which can be concatenated with other Message chunks.
Message that can be assigned an arbitrary speaker (i.e. role).
Chat Message chunk.
Representation of a callable function to send to an LLM.
Representation of a callable function to the OpenAI API.
Resolved gateway configuration.
Custom exception for Chevron errors.
A string formatter that enforces keyword-only argument substitution.
This formatter extends Python's built-in string.Formatter to provide stricter
validation for prompt template formatting. It ensu
Dummy lock that provides the proper interface but no protection.
Create n separate asynchronous iterators over iterable.
This splits a single iterable into multiple iterators, each providing the same
items in the same order.
All child iterators may advance
Dummy lock that provides the proper interface but no protection.
Create n separate asynchronous iterators over iterable.
This splits a single iterable into multiple iterators, each providing
the same items in the same order.
All child iterators may advance
Async context manager to wrap an AsyncGenerator that has a aclose() method.
Code like this:
async with aclosing(<module>.fetch(<arguments>)) as agen:
<block>
...is equivalent
Structured prompt template for a language model.
Prompt template that contains few shot examples.
Base class for message prompt templates.
Prompt template for a language model.
A prompt template consists of a string template. It accepts a set of parameters from the user that can be used to generate a prompt for a language model.
The te
String prompt that exposes the format method, returning a prompt.
Prompt template that contains few shot examples.
Chat prompt template that supports few-shot examples.
The high level structure of produced by this prompt template is a list of messages consisting of prefix message(s), example message(s), and suffi
Image prompt template for a multimodal model.
Template represented by a dictionary.
Recognizes variables in f-string or mustache formatted string dict values.
Does NOT recognize variables in dict keys. Applies recursively.
Base class for all prompt templates, returning a prompt.
Prompt template that assumes variable is already list of messages.
A placeholder which can be used to pass in a list of messages.
from langchain_core.pr
<!--/ADMON-->
Base class for message prompt templates that use a string prompt template.
Chat message prompt template.
Human message prompt template.
This is a message sent from the user.
AI message prompt template.
This is a message sent from the AI.
System message prompt template.
This is a message that is not sent to the user.
Base class for chat prompt templates.
Prompt template for chat models.
Use to create flexible templated prompts for chat models.
from langchain_core.prompts import ChatPromptTemplate
template = ChatPr
<!--/ADMON-->
Parse an output that is one of sets of values.
Parse an output as the JSON object.
Parse an output as the element of the JSON object.
Parse an output as a Pydantic object.
This parser is used to parse the output of a chat model that uses OpenAI function format to invoke functions.
The parser extracts the function call invocation a
Parse an output as an attribute of a Pydantic object.
Parse an output using xml format.
Returns a dictionary of tags.
Parse the output of an LLM call to a JSON object.
Probably the most reliable output parser for getting structured data that does not use function calling.
When used in streaming mode, it will yiel
Base class for an output parser that can handle streaming input.
Base class for an output parser that can handle streaming input.
Extract text content from model outputs as a string.
Converts model outputs (such as AIMessage or AIMessageChunk objects) into plain
text strings. It's the simplest output parser and is useful wh
Parse an output using a Pydantic model.
Parse tools from OpenAI response.
Parse tools from OpenAI response.
Parse tools from OpenAI response.
Abstract base class for parsing the outputs of a model.
Base class to parse the output of an LLM call.
Base class to parse the output of an LLM call.
Output parsers help structure language model responses.
Parse the output of a model to a list.
Parse the output of a model to a comma-separated list.
Parse a numbered list.
Parse a Markdown list.
A class for issuing deprecation warnings for LangChain users.
A class for issuing deprecation warnings for LangChain users.
A class for issuing beta warnings for LangChain users.
Description of a chat model's capabilities, exposed via model.profile.
See the model profiles guide for concepts and usage.
Base LLM abstract interface.
It should take in a prompt and return a string.
Simple interface for implementing a custom LLM.
You should subclass this class and implement the following:
_call method: Run the LLM on the given prompt and input (used by invoke).Fake LLM for testing purposes.
Fake error for testing purposes.
Fake streaming list LLM for testing purposes.
An LLM that will return responses from a list in order.
This model also supports optionally sleeping between successive chunks in a streaming implementa
Sync iterable of deltas with pull-based backpressure.
Follows the same _request_more convention as langgraph's
EventLog: when the cursor catches up to the buffer and the
projection is not done, i
String-specialized sync projection.
Adds typed string producers and consumers, plus __str__, __bool__,
__repr__ for ergonomic use with .text and .reasoning projections.
Async iterable of deltas that is also awaitable for the final value.
Uses an asyncio.Event to notify consumers of state changes. Each
waiter โ the awaitable (__await__) and each async iterator cu
String-specialized async projection for .text and .reasoning.
Synchronous per-message streaming object for a single LLM response.
Returned by BaseChatModel.stream_events(version="v3"). Content-block protocol
events are fed into this object and accumulated in
Asynchronous per-message streaming object for a single LLM response.
Returned by BaseChatModel.astream_events(version="v3"). Content-block events
are fed into this object by a background producer
Fake chat model for testing purposes.
Fake error for testing purposes.
Fake chat model for testing purposes.
Fake Chat Model wrapper for testing purposes.
Generic fake chat model that can be used to test the chat model interface.
on_llm_new_token to allow for testing of callback relGeneric fake chat model that can be used to test the chat model interface.
Base class for chat models.
Simplified implementation for a chat model to inherit from.
This implementation is primarily here for backwards compatibility. For new
implementations, please use BaseChatModel dir
LangSmith parameters for tracing.
Abstract base class for interfacing with language models.
All language model wrappers inherited from BaseLanguageModel.
Optional descriptions for the two outcomes of a Noul question.
Criteria clarify what should count as yes and no when the instruction alone leaves room for interpretation. Both values accept any JSO
Ask a binary question and receive the probability that its answer is yes.
Use Noul when the probability itself is useful to application code, such as
deciding whether a message reports a bug or req
Select one label from a fixed set of alternatives.
Use Choice for categorical decisions with no inherent ordering, such as routing a
support request, detecting a document type, or selecting an inte
Evaluate state against an ordered rubric.
Use Score when the answer lies on a spectrum whose levels can be described, such
as severity, urgency, or customer frustration. Criteria are numbered from
Locate what the instructions describe in an image in the state.
The answer gives the edges of a box as fractions of the image height and width.
Complete input for one decision model invocation.
Keeping the state and questions in the Runnable input ensures both values participate in composition, batching, and tracing.
Probability that a Noul question's answer is yes.
Selected Choice label with its probability distribution and confidence.
Expected Score value with its rubric, distribution, and confidence.
Edges of a box as fractions of the image height and width, from 0 to 1.
Location of what a Box question describes.
Typed answers and metadata returned from one classification request.
Access every answer through answers, or use nouls, choices, scores, and
boxes for views filtered by answer type. Each ma
Answer typed questions about text, messages, or structured state.
A decision model evaluates shared state against one or more questions and returns
typed answers: a probability for a Noul, a select
httpx async transport that validates DNS results against an SSRF policy.
For every outgoing request the transport:
policy.allowed_schemes.httpx sync transport that validates DNS results against an SSRF policy.
Sync mirror of SSRFSafeTransport. See that class for full documentation.
Immutable policy controlling which URLs/IPs are considered safe.
Raised when a request is blocked by SSRF protection policy.
In memory document index.
This is an in-memory document index that stores documents in a dictionary.
It provides a simple search API that returns documents by the number of counts the given query ap
Raised when an indexing operation fails.
Return a detailed a breakdown of the result of the indexing operation.
Abstract base class representing the interface for a record manager.
The record manager abstraction is used by the langchain indexing API.
The record manager keeps track of which documents have been
An in-memory record manager for testing purposes.
A generic response for upsert operations.
The upsert response will be used by abstractions that implement an upsert operation for content that can be upserted by ID.
Upsert APIs that accept inputs w
A generic response for delete operation.
The fields in this response are optional and whether the VectorStore
returns them or not is up to the implementation.
A document retriever that supports indexing operations.
This indexing interface is designed to be a generic abstraction for storing and querying documents that has an ID and metadata associated with
Abstract interface for blob loaders implementation.
Implementer should be able to load raw content from a storage system according to some criteria and return the raw content lazily as a stream of bl
Interface for document loader.
Implementations should implement the lazy-loading method using generators to avoid loading all documents into memory at once.
load is provided just for user convenie
Abstract interface for blob parsers.
A blob parser provides a way to parse raw data stored in a blob into one or more
Document objects.
The parser can be composed with blob loaders, making it easy
Load LangSmith Dataset examples as Document objects.
Loads the example inputs as the Document page content and places the entire
example into the Document metadata. This allows you to easily cr
Abstract base class for storing chat message history.
Implementations guidelines:
Implementations are expected to over-ride all or some of the following methods:
add_messages: sync variant forIn memory implementation of chat message history.
Stores messages in a memory list.
Set a new value for the verbose global setting.
Get the value of the verbose global setting.
Set a new value for the debug global setting.
Get the value of the debug global setting.
Set a new LLM cache, overwriting the previous value, if any.
Get the value of the llm_cache global setting.
Import an attribute from a module located in a package.
This utility function is used in custom __getattr__ methods within __init__.py
files to dynamically import attributes.
Print information about the environment for debugging purposes.
Get information about the LangChain runtime environment.
Create a message with a link to the LangChain troubleshooting guide.
Identity function.
Async identity function.
Prefix the id of a ConfigurableFieldSpec.
This is useful when a RunnableConfigurableAlternatives is used as a
ConfigurableField of another RunnableConfigurableAlternatives.
Make options spec.
Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or
ConfigurableFieldMultiOption.
Build a DAG and draw it in ASCII.
Run a coroutine with a semaphore.
Gather coroutines with a limit on the number of concurrent coroutines.
Check if a callable accepts a run_manager argument.
Check if a callable accepts a config argument.
Check if a callable accepts a context argument.
Check if asyncio.create_task accepts a context arg.
Await a coroutine with a context.
Get the keys of the first argument of a function if it is a dict.
Get the source code of a lambda function.
Get the nonlocal variables accessed by a function.
Indent all lines of text after the first line.
Add a sequence of addable objects together.
Asynchronously add a sequence of addable objects together.
Get the unique config specs from a sequence of config specs.
Check if a function is an async generator.
Check if a function is async.
Draws a Mermaid graph using the provided graph data.
Draws a Mermaid graph as PNG using provided syntax.
Coerce a Runnable-like object into a Runnable.
Decorate a function to make it a Runnable.
Sets the name of the Runnable to the name of the function.
Any runnables called by the function will be traced as dependencies.
Check if a string is a valid UUID.
Convert the data of a node to a string.
Convert the data of a node to a JSON-serializable format.
Set the child Runnable config + tracing context.
Ensure that a config is a dict with all keys present.
Get a list of configs from a single config or a list of configs.
It is useful for subclasses overriding batch() or abatch().
Patch a config with new values.
Merge multiple configs into one.
Call function that may optionally accept a run_manager and/or config.
Async call function that may optionally accept a run_manager and/or config.
Get a callback manager for a config.
Get an async callback manager for a config.
Get an executor for a config.
Run a function in an executor.
Merge a list of ChatGenerationChunks into a single ChatGenerationChunk.
Render the tool name and description in plain text.
Render the tool name, description, and args in plain text.
Convert Python functions and Runnables to LangChain tools.
Can be used as a decorator with or without arguments to create tools from functions.
Functions can have any signature - the tool will aut
Convert a Runnable into a BaseTool.
Create a Pydantic schema from a function's signature.
Get all annotations from a Pydantic BaseModel and its parents.
Create a tool to do retrieval of documents.
Log an error once.
Wait for all tracers to finish.
Get the client.
Convert run to dict, compatible with both Pydantic v1 and v2.
Copy run, compatible with both Pydantic v1 and v2.
Construct run without validation, compatible with both Pydantic v1 and v2.
Convert any Pydantic model to dict, compatible with both v1 and v2.
Copy any Pydantic model, compatible with both v1 and v2.
Try to stringify an object to JSON.
Get the elapsed time of a run.
Wait for all tracers to finish.
Instruct LangChain to log all runs in context to LangSmith.
Collect all run traces in context.
Register a configure hook.
Default init validator that blocks jinja2 templates.
This is the default validator used by load() and loads() when no custom
validator is provided.
Revive a LangChain class from a JSON string.
Equivalent to load(json.loads(text)).
Only classes in the allowlist can be instantiated. The default allowlist includes core LangChain types (messages,
Revive a LangChain class from a JSON object.
Use this if you already have a parsed JSON object, eg. from json.load or
orjson.loads.
Only classes in the allowlist can be instantiated. The default
Return a default value for an object.
Return a JSON string representation of an object.
Return a dict representation of an object.
Try to determine if a value is different from the default.
Serialize a "not implemented" object.
Return a list of values in dict sorted by key.
Calculate maximal marginal relevance.
Get a callback manager for a chain group in a context manager.
Useful for grouping different calls together as a single run even if they aren't composed in a single chain.
Get an async callback manager for a chain group in a context manager.
Useful for grouping different async calls together as a single run even if they aren't composed in a single chain.
Makes so an awaitable method is always shielded from cancellation.
Generic event handler for CallbackManager.
Async generic event handler for AsyncCallbackManager.
Dispatch an adhoc event to the handlers.
Dispatch an adhoc event.
Get usage metadata callback.
Get context manager for tracking usage metadata across chat model calls using
AIMessage.usage_metadata.
Add multiple AIMessageChunks together.
Recursively add two UsageMetadata objects.
Recursively subtract two UsageMetadata objects.
Token counts cannot be negative so the actual operation is max(left - right, 0).
Return a copy of message marked as added by the agent harness.
Use it for a human message the user didn't type, such as a background task update or a conversation summary, or a tool message generat
Return the notification metadata of message.
Convert a sequence of messages to strings and concatenate them into one string.
Convert a sequence of messages from dicts to Message objects.
Convert a message chunk to a Message.
Convert a sequence of messages to a list of messages.
Filter messages based on name, type or id.
Merge consecutive Messages of the same type.
ToolMessage objects are not merged, as each has a distinct tool call id that
can't be merged.
Trim messages to be below a token count.
trim_messages can be used to reduce the size of a chat history to a specified
token or message count.
In either case, if passing the trimmed chat history b
Convert LangChain messages into OpenAI message dicts.
Approximate the total number of tokens in messages.
The token count includes stringified message content, role, and (optionally) name.
Check if the provided content block is a data content block.
Returns True for both v0 (old-style) and v1 (new-style) multimodal data blocks.
Create a TextContentBlock.
Create an ImageContentBlock.
Create a VideoContentBlock.
Create an AudioContentBlock.
Create a FileContentBlock.
Create a PlainTextContentBlock.
Create a ToolCall.
Create a ReasoningContentBlock.
Create a Citation.
Create a NonStandardContentBlock.
Create a tool call.
Create a tool call chunk.
Create an invalid tool call.
Best-effort parsing of tools.
Best-effort parsing of tool chunks.
Merge multiple message contents.
Convert a Message to a dictionary.
Convert a sequence of Messages to a list of dictionaries.
Get a title representation for a message.
Register content translators for a provider in PROVIDER_TRANSLATORS.
Get the translator functions for a provider.
Translate Google AI grounding metadata to LangChain Citations.
Derive standard content blocks from a message with Google (GenAI) content.
Derive standard content blocks from a chunk with Google (GenAI) content.
Derive standard content blocks from a message with Anthropic content.
Derive standard content blocks from a message chunk with Anthropic content.
Derive standard content blocks from a message with groq content.
Derive standard content blocks from a message chunk with groq content.
Derive standard content blocks from a message with Bedrock content.
Derive standard content blocks from a message chunk with Bedrock content.
Derive standard content blocks from a message with Bedrock Converse content.
Derive standard content blocks from a chunk with Bedrock Converse content.
Convert ImageContentBlock to format expected by OpenAI Chat Completions.
Format standard data content block to format expected by OpenAI.
"Standard data content block" can include old-style LangChain v0 blocks (URLContentBlock, Base64ContentBlock, IDContentBlock) or new o
Derive standard content blocks from a message with OpenAI content.
Derive standard content blocks from a message chunk with OpenAI content.
Convert a raw function/class to an OpenAI function.
Convert a tool-like object to an OpenAI tool schema.
OpenAI tool schema reference
Convert a schema representation to a JSON schema.
Convert an example into a list of messages that can be fed into an LLM.
This code is an adapter that converts a single example to a list of messages that can be fed into a chat model.
The list of me
Route chat models built in this context through the LangSmith gateway.
Unlike the LANGSMITH_GATEWAY env var, which applies to the whole process,
this applies only to the current context (thread or
Merge dictionaries.
Merge many dicts, handling specific scenarios where a key exists in both
dictionaries but has a value of None in 'left'. In such cases, the method uses
the value from `'right'
Add many lists, handling None.
Merge two objects.
It handles specific scenarios where a key exists in both dictionaries but has a
value of None in 'left'. In such cases, the method uses the value from 'right'
for that key in
Parse a literal from the template.
Do a preliminary check to see if a tag could be a standalone.
Do a final check to see if a tag could be a standalone.
Parse a tag from a template.
Tokenize a mustache template.
Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template.
Render a mustache template.
Renders a mustache template with a data scope and inline partial capability.
An individual iterator of a .tee.
This function is a generator that yields items from the shared iterator iterator.
It buffers items until the least advanced iterator has yielded them as well. Th
Utility batching function.
Validate specified keyword args are mutually exclusive.
Raise an error with the response text.
Context manager for mocking out datetime.now() in unit tests.
Dynamically import a module.
Raise an exception if the module is not installed.
Check the version of a package.
Get field names, including aliases, for a pydantic class.
Build extra kwargs from values and extra_kwargs.
Kept for backwards-compatibility but should never have been public. Use the
internal _build_model_kwargs function in
Convert a string to a SecretStr if needed.
Create a factory method that gets a value from an environment variable.
Secret from env.
Ensure the ID is a valid string, generating a new UUID if not provided.
Auto-generated UUIDs are prefixed by 'lc_' to indicate they are
LangChain-generated IDs.
Parse a JSON string that may be missing closing braces.
Parse a JSON string from a Markdown string.
Parse and check a JSON string from a Markdown string.
Checks that it contains the expected keys.
Resolve and inline JSON Schema $ref references in a schema object.
This function processes a JSON Schema and resolves all $ref references by
replacing them with the actual referenced content.
Ha
Get mapping for items to a support color.
Get colored text.
Get bolded text.
Print text with highlighting and no end characters.
If a color is provided, the text will be printed in that color.
If a file is provided, the text will be written to that file.
Extract all links from a raw HTML string.
Extract all links from a raw HTML string and convert into absolute paths.
Generate a UUID from a Unix timestamp in nanoseconds and random bits.
UUIDv7 objects feature monotonicity within a millisecond.
An individual iterator of a tee.
This function is a generator that yields items from the shared iterator
iterator. It buffers items until the least advanced iterator has yielded them as
well.
Th
Utility batching function for async iterables.
Determine if running within IPython or Jupyter.
Check if the given class is Pydantic v1-like.
Check if the given class is Pydantic v2-like.
Check if the given class is a subclass of Pydantic BaseModel.
Check if the given class is a subclass of any of the following:
pydantic.BaseModel in Pydantic 2.xpydantic.v1.BaseModel in PyCheck if the given class is an instance of Pydantic BaseModel.
Check if the given class is an instance of any of the following:
pydantic.BaseModel in Pydantic 2.xpydantic.v1.BaseModel inDecorator to run a function before model initialization.
Return the field names of a Pydantic model.
Return the JSON schema of a Pydantic model class of either major version.
Dispatches to the correct method for Pydantic v1 (schema) or v2
(model_json_schema), so callers holding a TypeBaseModel
Validate obj against a Pydantic model class of either major version.
Dispatches to the correct method for Pydantic v1 (parse_obj) or v2
(model_validate), so callers holding a TypeBaseModel do
Create a Pydantic model with the given field definitions.
Please use create_model_v2 instead of this function.
Create a Pydantic model with the given field definitions.
Do not use outside of langchain packages. This API is subject to change at any time.
Check if an environment variable is set.
Get a value from a dictionary or an environment variable.
Get a value from a dictionary or an environment variable.
Stringify a value.
Stringify a dictionary.
Convert an iterable to a comma-separated string.
Sanitize text by removing NUL bytes that are incompatible with PostgreSQL.
PostgreSQL text fields cannot contain NUL (0x00) bytes, which can cause
psycopg.DataError when inserting documents. This
Format a template using jinja2.
As of LangChain 0.0.329, this method uses Jinja2's SandboxedEnvironment by
default. However, this sandboxing should be treated as a b
Validate that the input variables are valid for the template.
Issues a warning if missing or extra variables are found.
Format a template using mustache.
Get the top-level variables from a mustache template.
For nested variables like {{person.name}}, only the top-level key (person) is
returned.
Get the variables from a mustache template.
Validate an f-string template and return its input variables.
Check that template string is valid.
Get the variables from the template.
Return True if child is subsequence of parent.
Format a document into a string based on a prompt template.
First, this pulls information from the document from two sources:
page_content: This takes the information from the `document.page_coAsync format a document into a string based on a prompt template.
First, this pulls information from the document from two sources:
page_content: This takes the information from the `document.pGet nested element from path.
Parse a single tool call.
Create an InvalidToolCall from a raw tool call.
Parse a list of tool calls.
Raise ModelRefusalError if the model refused instead of answering.
Drop the last n elements of an iterator.
Return whether the caller at depth of this function is internal.
Decorator to mark a function, a class, or a property as deprecated.
When deprecating a classmethod, a staticmethod, or a property, the @deprecated
decorator should go under @classmethod and `@s
Suppress LangChain deprecation warnings within the current context.
Silences warnings emitted through warn_deprecated and @deprecated. It does not
modify the global warnings filters, so calling
Display a standardized deprecation.
Unmute LangChain deprecation warnings.
Decorator indicating that parameter old of func is renamed to new.
The actual implementation of func should use new, not old. If old is passed
to func, a DeprecationWarning is emitt
Decorator to mark a function, a class, or a property as beta.
When marking a classmethod, a staticmethod, or a property, the @beta decorator
should go under @classmethod and @staticmethod (i.
Suppress LangChain beta warnings within the current context.
Silences warnings emitted through warn_beta and @beta. It does not modify the
global warnings filters, so calling warnings.warn di
Display a standardized beta annotation.
Unmute LangChain beta warnings.
Get the path of the file as a relative path to the package directory.
Path of the file as a LangChain import exclude langchain top namespace.
Create a retry decorator for a given LLM and provided a list of error types.
Get prompts that are already cached.
Get prompts that are already cached. Async version.
Update the cache and get the LLM output.
Update the cache and get the LLM output. Async version.
Check whether a block contains multimodal data in OpenAI Chat Completions format.
Supports both data and ID-style blocks (e.g. 'file_data' and 'file_id')
If additional keys are present, they are
Generate from a stream.
Async generate from a stream.
Parse accumulated tool-chunk args into a finalized block.
Shared between the compat bridge's _finalize_block and the
ChatModelStream end-of-stream sweep. Parses raw_args as JSON:
on success bui
Convert a stream of ChatGenerationChunk to protocol events.
Blocks are tracked independently by source-side identifier. Providers such as Anthropic can interleave parallel tool-call chunks by index
Async variant of chunks_to_events.
Replay a finalized message as a synthetic event lifecycle.
For a message returned whole (from a graph node, checkpoint, or
cache), produce the same message-start / per-block /
message-finish even
Async variant of message_to_events.
Get a GPT-2 tokenizer instance.
This function is cached to avoid re-loading the tokenizer every time it is called.
Create an httpx.Client with SSRF protection.
Create an httpx.AsyncClient with SSRF protection.
Drop-in replacement for httpx.AsyncClient(...) - callers just swap
the constructor call. Transport-specific kwargs (verify, cert,
retries,
Validate a resolved IP address against the SSRF policy.
Raises SSRFBlockedError if the IP is blocked.
Validate a hostname against the SSRF policy.
Raises SSRFBlockedError if the hostname is blocked.
Validate a URL against the SSRF policy, including DNS resolution.
This is the primary entry-point for async code paths. It delegates
scheme/hostname/allowed-hosts checks to validate_url_sync, then
Synchronous URL validation (no DNS resolution).
Suitable for Pydantic validators and other sync contexts. Checks scheme
and hostname patterns only - use validate_url for full DNS-aware checking.
Validate a URL for SSRF protection.
This function validates URLs to prevent Server-Side Request Forgery (SSRF) attacks by blocking requests to private networks and cloud metadata endpoints.
Non-throwing version of validate_safe_url.
Index data from the loader into the vector store.
Indexing functionality uses a manager to keep track of which documents are in the vector store.
This allows us to keep track of which documents were
Async index data from the loader into the vector store.
Indexing functionality uses a manager to keep track of which documents are in the vector store.
This allows us to keep track of which document
Pure-Python implementation of anext() for testing purposes.
Closely matches the builtin anext() C implementation.
Can be used to compare the built-in implementation of the inner coroutines machi
DEPRECATED - Get the major version of Pydantic.
Use PYDANTIC_VERSION.major instead.
Load prompt from config dict.
Unified method for loading a prompt from LangChainHub or local filesystem.
langchain-core defines the base abstractions for the LangChain ecosystem.
The interfaces for core components like chat models, LLMs, vector stores, retrievers, and more are defined here. The univer
Global values and configuration that apply to all of LangChain.
Chat message history stores a history of the message interactions in a chat.
Internal representation of a structured query language.
Version information for langchain-core.
Prompt values for language model prompts.
Prompt values are used to represent different pieces of prompts. They can be used to represent text, images, or chat message pieces.
Chat loaders.
Store implements the 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 sto
Chat Sessions are a collection of messages and function calls.
Print information about the system and langchain packages for debugging purposes.
Utilities for getting information about the runtime environment.
Interface for a rate limiter and an in-memory rate limiter.
Cross Encoder interface.
Optional caching layer for language models.
Distinct from provider-based prompt caching.
This
Schema definitions for representing agent actions, observations, and return values.
The schema definitions are provided for backwards compatibility.
New agents shou
Custom exceptions for LangChain.
Retriever class returns Document objects 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
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
Implementation of the RunnablePassthrough.
Runnable objects that can be dynamically configured.
Runnable that retries a Runnable if it fails.
Runnable that can fallback to other Runnable objects if it fails.
Module contains typedefs that are used with Runnable objects.
Draws DAG in ASCII.
Adapted from https://github.com/iterative/dvc/blob/main/dvc/dagascii.py.
Utility code for Runnable objects.
Runnable that routes to a set of Runnable objects.
Runnable that selects which branch to run based on a condition.
Mermaid graph drawing utilities.
Runnable that manages chat message history for another Runnable.
Helper class to draw a state graph into a PNG file.
Base classes and utilities for Runnable objects.
Graph used in Runnable objects.
Configuration utilities for Runnable objects.
Output classes.
Used to represent the output of a language model call and the output of a chat.
The top container for information is the LLMResult object. LLMResult is used by both
chat models a
Chat result schema.
Generation output schema.
LLMResult class.
Chat generation output classes.
RunInfo class.
Embeddings.
Embeddings interface.
Module contains a few fake embedding models for testing purposes.
Documents module for data retrieval and processing workflows.
This module provides core abstractions for handling data in retrieval-augmented generation (RAG) pipelines, vector stores, and document p
Document transformers.
Base classes for media and documents.
This module contains core abstractions for data retrieval and processing workflows:
BaseMedia: Base class providing id and metadata fieldsBlob:Document compressor.
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.
Structured tool.
Utilities to render tools.
Convert functions and runnables to tools.
Base classes and utilities for LangChain tools.
Tool that takes in function or coroutine directly.
Retriever tool.
Tracers are classes for tracing runs.
Module implements a memory stream for communication between two co-routines.
This module provides a way to communicate between two co-routines using a memory channel. The writer and reader can be in
Utilities for the root listener.
Internal tracer to power the event stream API.
A tracer that collects all nested runs in a list.
A tracer implementation that records to LangChain endpoint.
Tracer that streams run logs to a stream.
Schemas for tracers.
Base interfaces for tracing runs.
Tracers that print to the console.
A tracer that runs evaluators over completed runs.
Context management for tracers.
Tracers that call listeners.
Load module helps with serialization and deserialization.
Load LangChain objects from JSON strings or objects.
How it works
Each Serializable LangChain object has a unique identifier (its "class path"), which
is a list of strings representing the modu
Serialize LangChain objects to JSON.
Provides dumps (to JSON string) and dumpd (to dict) for serializing
Serializable objects.
Escaping
During serialization, plain dicts (user data) that c
Serialization mapping.
This file contains a mapping between the lc_namespace path for a given
subclass that implements from Serializable to the namespace
where that class is actually located.
Th
Serializable base class.
Example selectors.
Example selector implements logic for selecting examples to include them in prompts. This allows us to select examples that are most relevant to the input.
Example selector that selects examples based on SemanticSimilarity.
Select examples based on length.
Interface for selecting examples to include in prompts.
Vector stores.
In-memory vector store.
Internal utilities for the in memory implementation of VectorStore.
These are part of a private API, and users should not use them directly as they can change without notice.
A 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 th
Callback handlers allow listening to events in LangChain.
Run managers.
Callback handler that writes to a file.
Callback Handler that tracks AIMessage.usage_metadata.
Callback Handler streams to stdout on new llm token.
Base callback handler for LangChain.
Callback handler that prints to std out.
Messages are objects used in prompts and chat conversations.
Human message.
System message.
AI message.
Function Message.
Metadata for messages the agent harness adds to a conversation.
Message responsible for deleting other messages.
Module contains utility functions for working with messages.
Some examples of what you can do with these functions include:
Standard, multimodal content blocks for Large Language Model I/O.
This module provides standardized data structures for representing inputs to and outputs from LLMs. The core abstraction is the **Con
Messages for tools.
Base message.
Chat Message.
Derivations of standard content blocks from provider content.
AIMessage will first attempt to use a provider-specific translator if
model_provider is set in response_metadata on the message. Co
Derivations of standard content blocks from Google (GenAI) content.
Derivations of standard content blocks from Google (VertexAI) content.
Derivations of standard content blocks from Anthropic content.
Derivations of standard content blocks from Groq content.
Derivations of standard content blocks from Bedrock content.
Derivations of standard content blocks from LangChain v0 multimodal content.
Derivations of standard content blocks from Amazon (Bedrock Converse) content.
Derivations of standard content blocks from OpenAI content.
Utility functions for LangChain.
These functions do not depend on any other LangChain module.
Methods for creating function specs in the style of OpenAI Functions.
Adapted from https://github.com/noahmorrison/chevron.
MIT License.
Utilities for formatting strings.
Utilities for working with iterators.
Generic utility functions.
Utilities for JSON.
Utilities for JSON Schema.
Handle chained inputs.
Usage utilities.
Utilities for working with HTML.
UUID utility functions.
This module exports a uuid7 function to generate monotonic, time-ordered UUIDs for tracing and similar operations.
Asynchronous iterator utilities.
Adapted from https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py MIT License.
Utilities for working with interactive environments.
Utilities for image processing.
Utilities for pydantic.
Utilities for environment variables.
String utilities.
A prompt is the input to the model.
Prompt is often constructed from multiple components and prompt values. Prompt classes and functions make constructing and working with prompts easy.
Structured prompt template for a language model.
Prompt template that contains few shot examples.
Message prompt templates.
Prompt schema definition.
Load prompts.
BasePrompt schema definition.
Prompt template that contains few shot examples.
Image prompt template for a multimodal model.
Dictionary prompt template.
Base class for prompt templates.
Chat prompt template.
OutputParser classes parse the output of an LLM call into structured data.
Output parsers emerged as an early solution to the challenge of obtaining structured
Parsers for OpenAI functions output.
Output parser for XML format.
Parser for JSON output.
Base classes for output parsers that can handle streaming input.
String output parser.
Format instructions.
Output parsers using Pydantic.
Parse tools for OpenAI tools output.
Base parser for language model outputs.
Parsers for list output.
Helper functions for deprecating parts of the LangChain API.
This module was adapted from matplotlib's [_api/deprecation.py](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/d
Helper functions for marking parts of the LangChain API as beta.
This module was loosely adapted from matplotlib's [_api/deprecation.py](https://github.com/matplotlib/matplotlib/blob/main/lib/matpl
Core language model abstractions.
LangChain has two main classes to work with language models: chat models and "old-fashioned" LLMs (string-in, string-out).
Chat models
Language models that use
Model profile types and utilities.
Base interface for traditional large language models (LLMs) to expose.
These are traditionally older models (newer models generally are chat models).
Fake LLMs for testing purposes.
Per-message streaming objects for content-block protocol events.
ChatModelStream is the synchronous variant returned by
BaseChatModel.stream_events(version="v3"). AsyncChatModelStream is the
a
Fake chat models for testing purposes.
Chat models for conversational AI.
Base language models class.
Decision models: typed probabilistic answers about text, messages, or state.
Question and response types shared by decision models.
Base class for decision models.
Code to help indexing data into a vectorstore.
This package contains helper logic to help deal with indexing data into
a VectorStore while avoiding duplicated content and over-writing content
if it
In memory document index.
Module contains logic for indexing documents into vector stores.
Base classes for indexing.
Document loaders.
Schema for Blobs and Blob Loaders.
The goal is to facilitate decoupling of content loading from content parsing code. In addition, content loading code should provide a lazy loading interface by defa
Abstract interface for document loader implementations.
LangSmith document loader.
A single message content block: plain text or a structured block.
A dict block is only considered valid at runtime when its type key is one of
TOOL_MESSAGE_BLOCK_TYPES (see `_is_message_content_b
Content returned by a handle_tool_error callable.
Error handlers may return plain text or a sequence of structured message
content blocks. When the original tool call includes a tool_call_id, thi
A type representing the various ways a message can be represented.
A union of all defined Annotation types.
A union of all defined multimodal data ContentBlock types.
A union of all defined ContentBlock types and aliases.
Input to a language model.
Output from a language model.
Text, a JSON object, or a JSON array used in question instructions.
As in State, LangChain standard media blocks may appear anywhere in instructions and
criteria. Providers send them as media, or r
Root state accepted by decision models.
State is a string, JSON object, or JSON array. LangChain BaseMessage objects and
message sequences can appear at the root or at any depth inside objects and