langchain-core: 0.2.30#

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 universal invocation protocol (Runnables) along with a syntax for combining components (LangChain Expression Language) are also defined here.

No third-party integrations are defined here. The dependencies are kept purposefully very lightweight.

agents#

agents.AgentAction

Represents a request to execute an action by an agent.

agents.AgentActionMessageLog

Representation of an action to be executed by an agent.

agents.AgentFinish

Final return value of an ActionAgent.

agents.AgentStep

Result of running an AgentAction.

beta#

caches#

caches.BaseCache()

Interface for a caching layer for LLMs and Chat models.

caches.InMemoryCache(*[, maxsize])

Cache that stores things in memory.

callbacks#

callbacks.base.AsyncCallbackHandler()

Async callback handler for LangChain.

callbacks.base.BaseCallbackHandler()

Base callback handler for LangChain.

callbacks.base.BaseCallbackManager(handlers)

Base callback manager for LangChain.

callbacks.base.CallbackManagerMixin()

Mixin for callback manager.

callbacks.base.ChainManagerMixin()

Mixin for chain callbacks.

callbacks.base.LLMManagerMixin()

Mixin for LLM callbacks.

callbacks.base.RetrieverManagerMixin()

Mixin for Retriever callbacks.

callbacks.base.RunManagerMixin()

Mixin for run manager.

callbacks.base.ToolManagerMixin()

Mixin for tool callbacks.

callbacks.file.FileCallbackHandler(filename)

Callback Handler that writes to a file.

callbacks.manager.AsyncCallbackManager(handlers)

Async callback manager that handles callbacks from LangChain.

callbacks.manager.AsyncCallbackManagerForChainGroup(...)

Async callback manager for the chain group.

callbacks.manager.AsyncCallbackManagerForChainRun(*, ...)

Async callback manager for chain run.

callbacks.manager.AsyncCallbackManagerForLLMRun(*, ...)

Async callback manager for LLM run.

callbacks.manager.AsyncCallbackManagerForRetrieverRun(*, ...)

Async callback manager for retriever run.

callbacks.manager.AsyncCallbackManagerForToolRun(*, ...)

Async callback manager for tool run.

callbacks.manager.AsyncParentRunManager(*, ...)

Async Parent Run Manager.

callbacks.manager.AsyncRunManager(*, run_id, ...)

Async Run Manager.

callbacks.manager.BaseRunManager(*, run_id, ...)

Base class for run manager (a bound callback manager).

callbacks.manager.CallbackManager(handlers)

Callback manager for LangChain.

callbacks.manager.CallbackManagerForChainGroup(...)

Callback manager for the chain group.

callbacks.manager.CallbackManagerForChainRun(*, ...)

Callback manager for chain run.

callbacks.manager.CallbackManagerForLLMRun(*, ...)

Callback manager for LLM run.

callbacks.manager.CallbackManagerForRetrieverRun(*, ...)

Callback manager for retriever run.

callbacks.manager.CallbackManagerForToolRun(*, ...)

Callback manager for tool run.

callbacks.manager.ParentRunManager(*, ...[, ...])

Sync Parent Run Manager.

callbacks.manager.RunManager(*, run_id, ...)

Sync Run Manager.

callbacks.stdout.StdOutCallbackHandler([color])

Callback Handler that prints to std out.

callbacks.streaming_stdout.StreamingStdOutCallbackHandler()

Callback handler for streaming.

chat_history#

chat_history.BaseChatMessageHistory()

Abstract base class for storing chat message history.

chat_history.InMemoryChatMessageHistory

In memory implementation of chat message history.

chat_loaders#

chat_loaders.BaseChatLoader()

Base class for chat loaders.

chat_sessions#

chat_sessions.ChatSession

Chat Session represents a single conversation, channel, or other group of messages.

document_loaders#

document_loaders.base.BaseBlobParser()

Abstract interface for blob parsers.

document_loaders.base.BaseLoader()

Interface for Document Loader.

document_loaders.blob_loaders.BlobLoader()

Abstract interface for blob loaders implementation.

documents#

documents.base.BaseMedia

Use to represent media content.

documents.base.Blob

Blob represents raw data by either reference or value.

documents.base.Document

Class for storing a piece of text and associated metadata.

documents.compressor.BaseDocumentCompressor

Base class for document compressors.

documents.transformers.BaseDocumentTransformer()

Abstract base class for document transformation.

embeddings#

embeddings.embeddings.Embeddings()

Interface for embedding models.

embeddings.fake.DeterministicFakeEmbedding

Deterministic fake embedding model for unit testing purposes.

embeddings.fake.FakeEmbeddings

Fake embedding model for unit testing purposes.

example_selectors#

example_selectors.base.BaseExampleSelector()

Interface for selecting examples to include in prompts.

example_selectors.length_based.LengthBasedExampleSelector

Select examples based on length.

example_selectors.semantic_similarity.MaxMarginalRelevanceExampleSelector

Select examples based on Max Marginal Relevance.

example_selectors.semantic_similarity.SemanticSimilarityExampleSelector

Select examples based on semantic similarity.

exceptions#

exceptions.LangChainException

General LangChain exception.

exceptions.OutputParserException(error[, ...])

Exception that output parsers should raise to signify a parsing error.

exceptions.TracerException

Base class for exceptions in tracers module.

globals#

graph_vectorstores#

graph_vectorstores.base.GraphVectorStore(...)

graph_vectorstores.base.GraphVectorStoreRetriever

Retriever class for GraphVectorStore.

graph_vectorstores.base.Node

Node in the GraphVectorStore.

graph_vectorstores.links.Link(kind, ...)

A link to/from a tag of a given tag.

indexing#

indexing.api.IndexingResult

Return a detailed a breakdown of the result of the indexing operation.

indexing.base.DeleteResponse

A generic response for delete operation.

indexing.base.DocumentIndex

indexing.base.InMemoryRecordManager(namespace)

An in-memory record manager for testing purposes.

indexing.base.RecordManager(namespace)

Abstract base class representing the interface for a record manager.

indexing.base.UpsertResponse

A generic response for upsert operations.

indexing.in_memory.InMemoryDocumentIndex

language_models#

language_models.base.BaseLanguageModel

Abstract base class for interfacing with language models.

language_models.chat_models.BaseChatModel

Base class for chat models.

language_models.chat_models.LangSmithParams

LangSmith parameters for tracing.

language_models.chat_models.SimpleChatModel

Simplified implementation for a chat model to inherit from.

language_models.fake.FakeListLLM

Fake LLM for testing purposes.

language_models.fake.FakeStreamingListLLM

Fake streaming list LLM for testing purposes.

language_models.fake_chat_models.FakeChatModel

Fake Chat Model wrapper for testing purposes.

language_models.fake_chat_models.FakeListChatModel

Fake ChatModel for testing purposes.

language_models.fake_chat_models.FakeMessagesListChatModel

Fake ChatModel for testing purposes.

language_models.fake_chat_models.GenericFakeChatModel

Generic fake chat model that can be used to test the chat model interface.

language_models.fake_chat_models.ParrotFakeChatModel

Generic fake chat model that can be used to test the chat model interface.

language_models.llms.BaseLLM

Base LLM abstract interface.

language_models.llms.LLM

Simple interface for implementing a custom LLM.

load#

load.load.Reviver([secrets_map, ...])

Reviver for JSON objects.

load.serializable.BaseSerialized

Base class for serialized objects.

load.serializable.Serializable

Serializable base class.

load.serializable.SerializedConstructor

Serialized constructor.

load.serializable.SerializedNotImplemented

Serialized not implemented.

load.serializable.SerializedSecret

Serialized secret.

memory#

memory.BaseMemory

Abstract base class for memory in Chains.

messages#

messages.ai.AIMessage

Message from an AI.

messages.ai.AIMessageChunk

Message chunk from an AI.

messages.ai.UsageMetadata

Usage metadata for a message, such as token counts.

messages.base.BaseMessage

Base abstract message class.

messages.base.BaseMessageChunk

Message chunk, which can be concatenated with other Message chunks.

messages.chat.ChatMessage

Message that can be assigned an arbitrary speaker (i.e.

messages.chat.ChatMessageChunk

Chat Message chunk.

messages.function.FunctionMessage

Message for passing the result of executing a tool back to a model.

messages.function.FunctionMessageChunk

Function Message chunk.

messages.human.HumanMessage

Message from a human.

messages.human.HumanMessageChunk

Human Message chunk.

messages.modifier.RemoveMessage

messages.system.SystemMessage

Message for priming AI behavior.

messages.system.SystemMessageChunk

System Message chunk.

messages.tool.InvalidToolCall

Allowance for errors made by LLM.

messages.tool.ToolCall

Represents a request to call a tool.

messages.tool.ToolCallChunk

A chunk of a tool call (e.g., as part of a stream).

messages.tool.ToolMessage

Message for passing the result of executing a tool back to a model.

messages.tool.ToolMessageChunk

Tool Message chunk.

output_parsers#

output_parsers.base.BaseGenerationOutputParser

Base class to parse the output of an LLM call.

output_parsers.base.BaseLLMOutputParser()

Abstract base class for parsing the outputs of a model.

output_parsers.base.BaseOutputParser

Base class to parse the output of an LLM call.

output_parsers.json.JsonOutputParser

Parse the output of an LLM call to a JSON object.

output_parsers.json.SimpleJsonOutputParser

alias of JsonOutputParser

output_parsers.list.CommaSeparatedListOutputParser

Parse the output of an LLM call to a comma-separated list.

output_parsers.list.ListOutputParser

Parse the output of an LLM call to a list.

output_parsers.list.MarkdownListOutputParser

Parse a Markdown list.

output_parsers.list.NumberedListOutputParser

Parse a numbered list.

output_parsers.openai_functions.JsonKeyOutputFunctionsParser

Parse an output as the element of the Json object.

output_parsers.openai_functions.JsonOutputFunctionsParser

Parse an output as the Json object.

output_parsers.openai_functions.OutputFunctionsParser

Parse an output that is one of sets of values.

output_parsers.openai_functions.PydanticAttrOutputFunctionsParser

Parse an output as an attribute of a pydantic object.

output_parsers.openai_functions.PydanticOutputFunctionsParser

Parse an output as a pydantic object.

output_parsers.openai_tools.JsonOutputKeyToolsParser

Parse tools from OpenAI response.

output_parsers.openai_tools.JsonOutputToolsParser

Parse tools from OpenAI response.

output_parsers.openai_tools.PydanticToolsParser

Parse tools from OpenAI response.

output_parsers.pydantic.PydanticOutputParser

Parse an output using a pydantic model.

output_parsers.string.StrOutputParser

OutputParser that parses LLMResult into the top likely string.

output_parsers.transform.BaseCumulativeTransformOutputParser

Base class for an output parser that can handle streaming input.

output_parsers.transform.BaseTransformOutputParser

Base class for an output parser that can handle streaming input.

output_parsers.xml.XMLOutputParser

Parse an output using xml format.

outputs#

outputs.chat_generation.ChatGeneration

A single chat generation output.

outputs.chat_generation.ChatGenerationChunk

ChatGeneration chunk, which can be concatenated with other ChatGeneration chunks.

outputs.chat_result.ChatResult

Use to represent the result of a chat model call with a single prompt.

outputs.generation.Generation

A single text generation output.

outputs.generation.GenerationChunk

Generation chunk, which can be concatenated with other Generation chunks.

outputs.llm_result.LLMResult

A container for results of an LLM call.

outputs.run_info.RunInfo

Class that contains metadata for a single execution of a Chain or model.

prompt_values#

prompt_values.ChatPromptValue

Chat prompt value.

prompt_values.ChatPromptValueConcrete

Chat prompt value which explicitly lists out the message types it accepts.

prompt_values.ImagePromptValue

Image prompt value.

prompt_values.ImageURL

Image URL.

prompt_values.PromptValue

Base abstract class for inputs to any language model.

prompt_values.StringPromptValue

String prompt value.

prompts#

prompts.base.BasePromptTemplate

Base class for all prompt templates, returning a prompt.

prompts.chat.AIMessagePromptTemplate

AI message prompt template.

prompts.chat.BaseChatPromptTemplate

Base class for chat prompt templates.

prompts.chat.BaseMessagePromptTemplate

Base class for message prompt templates.

prompts.chat.BaseStringMessagePromptTemplate

Base class for message prompt templates that use a string prompt template.

prompts.chat.ChatMessagePromptTemplate

Chat message prompt template.

prompts.chat.ChatPromptTemplate

Prompt template for chat models.

prompts.chat.HumanMessagePromptTemplate

Human message prompt template.

prompts.chat.MessagesPlaceholder

Prompt template that assumes variable is already list of messages.

prompts.chat.SystemMessagePromptTemplate

System message prompt template.

prompts.few_shot.FewShotChatMessagePromptTemplate

Chat prompt template that supports few-shot examples.

prompts.few_shot.FewShotPromptTemplate

Prompt template that contains few shot examples.

prompts.few_shot_with_templates.FewShotPromptWithTemplates

Prompt template that contains few shot examples.

prompts.image.ImagePromptTemplate

Image prompt template for a multimodal model.

prompts.pipeline.PipelinePromptTemplate

Prompt template for composing multiple prompt templates together.

prompts.prompt.PromptTemplate

Prompt template for a language model.

prompts.string.StringPromptTemplate

String prompt that exposes the format method, returning a prompt.

prompts.structured.StructuredPrompt

rate_limiters#

retrievers#

retrievers.BaseRetriever

Abstract base class for a Document retrieval system.

retrievers.LangSmithRetrieverParams

LangSmith parameters for tracing.

runnables#

runnables.base.Runnable()

A unit of work that can be invoked, batched, streamed, transformed and composed.

runnables.base.RunnableBinding

Wrap a Runnable with additional functionality.

runnables.base.RunnableBindingBase

Runnable that delegates calls to another Runnable with a set of kwargs.

runnables.base.RunnableEach

Runnable that delegates calls to another Runnable with each element of the input sequence.

runnables.base.RunnableEachBase

Runnable that delegates calls to another Runnable with each element of the input sequence.

runnables.base.RunnableGenerator(transform)

Runnable that runs a generator function.

runnables.base.RunnableLambda(func[, afunc, ...])

RunnableLambda converts a python callable into a Runnable.

runnables.base.RunnableMap

alias of RunnableParallel

runnables.base.RunnableParallel

Runnable that runs a mapping of Runnables in parallel, and returns a mapping of their outputs.

runnables.base.RunnableSequence

Sequence of Runnables, where the output of each is the input of the next.

runnables.base.RunnableSerializable

Runnable that can be serialized to JSON.

runnables.branch.RunnableBranch

Runnable that selects which branch to run based on a condition.

runnables.config.ContextThreadPoolExecutor([...])

ThreadPoolExecutor that copies the context to the child thread.

runnables.config.EmptyDict

Empty dict type.

runnables.config.RunnableConfig

Configuration for a Runnable.

runnables.configurable.DynamicRunnable

Serializable Runnable that can be dynamically configured.

runnables.configurable.RunnableConfigurableAlternatives

Runnable that can be dynamically configured.

runnables.configurable.RunnableConfigurableFields

Runnable that can be dynamically configured.

runnables.configurable.StrEnum(value[, ...])

String enum.

runnables.fallbacks.RunnableWithFallbacks

Runnable that can fallback to other Runnables if it fails.

runnables.graph.Branch(condition, ends)

Branch in a graph.

runnables.graph.CurveStyle(value[, names, ...])

Enum for different curve styles supported by Mermaid

runnables.graph.Edge(source, target[, data, ...])

Edge in a graph.

runnables.graph.Graph(nodes, ...)

Graph of nodes and edges.

runnables.graph.LabelsDict

Dictionary of labels for nodes and edges in a graph.

runnables.graph.MermaidDrawMethod(value[, ...])

Enum for different draw methods supported by Mermaid

runnables.graph.Node(id, name, data, metadata)

Node in a graph.

runnables.graph.NodeStyles([default, first, ...])

Schema for Hexadecimal color codes for different node types.

runnables.graph.Stringifiable(*args, **kwargs)

runnables.graph_ascii.AsciiCanvas(cols, lines)

Class for drawing in ASCII.

runnables.graph_ascii.VertexViewer(name)

Class to define vertex box boundaries that will be accounted for during graph building by grandalf.

runnables.graph_png.PngDrawer([fontname, labels])

Helper class to draw a state graph into a PNG file.

runnables.history.RunnableWithMessageHistory

Runnable that manages chat message history for another Runnable.

runnables.passthrough.RunnableAssign

Runnable that assigns key-value pairs to Dict[str, Any] inputs.

runnables.passthrough.RunnablePassthrough

Runnable to passthrough inputs unchanged or with additional keys.

runnables.passthrough.RunnablePick

Runnable that picks keys from Dict[str, Any] inputs.

runnables.retry.RunnableRetry

Retry a Runnable if it fails.

runnables.router.RouterInput

Router input.

runnables.router.RouterRunnable

Runnable that routes to a set of Runnables based on Input['key'].

runnables.schema.BaseStreamEvent

Streaming event.

runnables.schema.CustomStreamEvent

Custom stream event created by the user.

runnables.schema.EventData

Data associated with a streaming event.

runnables.schema.StandardStreamEvent

A standard stream event that follows LangChain convention for event data.

runnables.utils.AddableDict

Dictionary that can be added to another dictionary.

runnables.utils.ConfigurableField(id[, ...])

Field that can be configured by the user.

runnables.utils.ConfigurableFieldMultiOption(id, ...)

Field that can be configured by the user with multiple default values.

runnables.utils.ConfigurableFieldSingleOption(id, ...)

Field that can be configured by the user with a default value.

runnables.utils.ConfigurableFieldSpec(id, ...)

Field that can be configured by the user.

runnables.utils.FunctionNonLocals()

Get the nonlocal variables accessed of a function.

runnables.utils.GetLambdaSource()

Get the source code of a lambda function.

runnables.utils.IsFunctionArgDict()

Check if the first argument of a function is a dict.

runnables.utils.IsLocalDict(name, keys)

Check if a name is a local dict.

runnables.utils.NonLocals()

Get nonlocal variables accessed.

runnables.utils.SupportsAdd(*args, **kwargs)

Protocol for objects that support addition.

stores#

stores.BaseStore()

Abstract interface for a key-value store.

stores.InMemoryBaseStore()

In-memory implementation of the BaseStore using a dictionary.

stores.InMemoryByteStore()

In-memory store for bytes.

stores.InMemoryStore()

In-memory store for any type of data.

stores.InvalidKeyException

Raised when a key is invalid; e.g., uses incorrect characters.

structured_query#

structured_query.Comparator(value[, names, ...])

Enumerator of the comparison operators.

structured_query.Comparison

Comparison to a value.

structured_query.Expr

Base class for all expressions.

structured_query.FilterDirective

Filtering expression.

structured_query.Operation

Logical operation over other directives.

structured_query.Operator(value[, names, ...])

Enumerator of the operations.

structured_query.StructuredQuery

Structured query.

structured_query.Visitor()

Defines interface for IR translation using a visitor pattern.

sys_info#

tools#

tools.base.BaseTool

Interface LangChain tools must implement.

tools.base.BaseToolkit

Base Toolkit representing a collection of related tools.

tools.base.InjectedToolArg()

Annotation for a Tool arg that is not meant to be generated by a model.

tools.base.SchemaAnnotationError

Raised when 'args_schema' is missing or has an incorrect type annotation.

tools.base.ToolException

Optional exception that tool throws when execution error occurs.

tools.retriever.RetrieverInput

Input to the retriever.

tools.simple.Tool

Tool that takes in function or coroutine directly.

tools.structured.StructuredTool

Tool that can operate on any number of inputs.

tracers#

tracers.base.AsyncBaseTracer(*[, _schema_format])

Async Base interface for tracers.

tracers.base.BaseTracer(*[, _schema_format])

Base interface for tracers.

tracers.evaluation.EvaluatorCallbackHandler(...)

Tracer that runs a run evaluator whenever a run is persisted.

tracers.event_stream.RunInfo

Information about a run.

tracers.langchain.LangChainTracer([...])

Implementation of the SharedTracer that POSTS to the LangChain endpoint.

tracers.log_stream.LogEntry

A single entry in the run log.

tracers.log_stream.LogStreamCallbackHandler(*)

Tracer that streams run logs to a stream.

tracers.log_stream.RunLog(*ops, state)

Run log.

tracers.log_stream.RunLogPatch(*ops)

Patch to the run log.

tracers.log_stream.RunState

State of the run.

tracers.root_listeners.AsyncRootListenersTracer(*, ...)

Async Tracer that calls listeners on run start, end, and error.

tracers.root_listeners.RootListenersTracer(*, ...)

Tracer that calls listeners on run start, end, and error.

tracers.run_collector.RunCollectorCallbackHandler([...])

Tracer that collects all nested runs in a list.

tracers.schemas.Run

Run schema for the V2 API in the Tracer.

tracers.stdout.ConsoleCallbackHandler(**kwargs)

Tracer that prints to the console.

tracers.stdout.FunctionCallbackHandler(...)

Tracer that calls a function with a single str parameter.

utils#

utils.aiter.NoLock()

Dummy lock that provides the proper interface but no protection.

utils.aiter.Tee(iterable[, n, lock])

Create n separate asynchronous iterators over iterable.

utils.aiter.aclosing(thing)

Async context manager for safely finalizing an asynchronously cleaned-up resource such as an async generator, calling its aclose() method.

utils.aiter.atee

alias of Tee

utils.formatting.StrictFormatter()

Formatter that checks for extra keys.

utils.function_calling.FunctionDescription

Representation of a callable function to send to an LLM.

utils.function_calling.ToolDescription

Representation of a callable function to the OpenAI API.

utils.iter.NoLock()

Dummy lock that provides the proper interface but no protection.

utils.iter.Tee(iterable[, n, lock])

Create n separate asynchronous iterators over iterable

utils.iter.safetee

alias of Tee

utils.mustache.ChevronError

Custom exception for Chevron errors.

vectorstores#

vectorstores.base.VectorStore()

Interface for vector store.

vectorstores.base.VectorStoreRetriever

Base Retriever class for VectorStore.

vectorstores.in_memory.InMemoryVectorStore(...)

In-memory implementation of VectorStore using a dictionary.