langchain_core API Reference¶

langchain_core.agents¶

Classes¶

agents.AgentAction

A full description of an action for an ActionAgent to execute.

agents.AgentActionMessageLog

Override init to support instantiation by position for backward compat.

agents.AgentFinish

The final return value of an ActionAgent.

langchain_core.caches¶

Classes¶

caches.BaseCache()

Base interface for cache.

langchain_core.callbacks¶

Classes¶

callbacks.base.AsyncCallbackHandler()

Async callback handler that handles callbacks from LangChain.

callbacks.base.BaseCallbackHandler()

Base callback handler that handles callbacks from LangChain.

callbacks.base.BaseCallbackManager(handlers)

Base callback manager that handles callbacks from LangChain.

callbacks.base.CallbackManagerMixin()

Mixin for callback manager.

callbacks.base.ChainManagerMixin()

Mixin for chain callbacks.

callbacks.base.LLMManagerMixin()

Mixin for LLM callbacks.

callbacks.base.RetrieverManagerMixin()

Mixin for Retriever callbacks.

callbacks.base.RunManagerMixin()

Mixin for run manager.

callbacks.base.ToolManagerMixin()

Mixin for tool callbacks.

callbacks.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 that handles callbacks from 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.

Functions¶

callbacks.manager.ahandle_event(handlers, ...)

Generic event handler for AsyncCallbackManager.

callbacks.manager.atrace_as_chain_group(...)

Get an async callback manager for a chain group in a context manager.

callbacks.manager.handle_event(handlers, ...)

Generic event handler for CallbackManager.

callbacks.manager.trace_as_chain_group(...)

Get a callback manager for a chain group in a context manager.

langchain_core.chat_history¶

Classes¶

chat_history.BaseChatMessageHistory()

Abstract base class for storing chat message history.

langchain_core.chat_sessions¶

Classes¶

chat_sessions.ChatSession

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

langchain_core.documents¶

Classes¶

documents.base.Document

Class for storing a piece of text and associated metadata.

documents.transformers.BaseDocumentTransformer()

Abstract base class for document transformation systems.

langchain_core.embeddings¶

Classes¶

embeddings.Embeddings()

Interface for embedding models.

langchain_core.example_selectors¶

Logic for selecting examples to include in prompts.

Classes¶

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

ExampleSelector that selects examples based on Max Marginal Relevance.

example_selectors.semantic_similarity.SemanticSimilarityExampleSelector

Example selector that selects examples based on SemanticSimilarity.

Functions¶

example_selectors.semantic_similarity.sorted_values(values)

Return a list of values in dict sorted by key.

langchain_core.exceptions¶

Classes¶

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.

langchain_core.language_models¶

Classes¶

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.SimpleChatModel

Simple Chat Model.

language_models.llms.BaseLLM

Base LLM abstract interface.

language_models.llms.LLM

Base LLM abstract class.

Functions¶

language_models.llms.create_base_retry_decorator(...)

Create a retry decorator for a given LLM and provided list of error types.

language_models.llms.get_prompts(params, prompts)

Get prompts that are already cached.

language_models.llms.update_cache(...)

Update the cache and get the LLM output.

langchain_core.load¶

Serialization and deserialization.

Classes¶

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.

Functions¶

load.dump.default(obj)

Return a default value for a Serializable object or a SerializedNotImplemented object.

load.dump.dumpd(obj)

Return a json dict representation of an object.

load.dump.dumps(obj, *[, pretty])

Return a json string representation of an object.

load.load.load(obj, *[, secrets_map, ...])

Revive a LangChain class from a JSON object.

load.load.loads(text, *[, secrets_map, ...])

Revive a LangChain class from a JSON string.

load.serializable.to_json_not_implemented(obj)

Serialize a "not implemented" object.

load.serializable.try_neq_default(value, ...)

langchain_core.memory¶

Classes¶

memory.BaseMemory

Abstract base class for memory in Chains.

langchain_core.messages¶

Classes¶

messages.ai.AIMessage

A Message from an AI.

messages.ai.AIMessageChunk

A Message chunk from an AI.

messages.base.BaseMessage

The base abstract Message class.

messages.base.BaseMessageChunk

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

messages.chat.ChatMessage

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

messages.chat.ChatMessageChunk

A Chat Message chunk.

messages.function.FunctionMessage

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

messages.function.FunctionMessageChunk

A Function Message chunk.

messages.human.HumanMessage

A Message from a human.

messages.human.HumanMessageChunk

A Human Message chunk.

messages.system.SystemMessage

A Message for priming AI behavior, usually passed in as the first of a sequence of input messages.

messages.system.SystemMessageChunk

A System Message chunk.

messages.tool.ToolMessage

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

messages.tool.ToolMessageChunk

A Tool Message chunk.

Functions¶

messages.base.merge_content(first_content, ...)

messages.base.message_to_dict(message)

messages.base.messages_to_dict(messages)

Convert a sequence of Messages to a list of dictionaries.

langchain_core.output_parsers¶

Classes¶

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.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.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.

langchain_core.outputs¶

Classes¶

outputs.chat_generation.ChatGeneration

A single chat generation output.

outputs.chat_generation.ChatGenerationChunk

A ChatGeneration chunk, which can be concatenated with other

outputs.chat_result.ChatResult

Class that contains all results for a single chat model call.

outputs.generation.Generation

A single text generation output.

outputs.generation.GenerationChunk

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

outputs.llm_result.LLMResult

Class that contains all results for a batched LLM call.

outputs.run_info.RunInfo

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

langchain_core.prompt_values¶

Classes¶

prompt_values.ChatPromptValue

Chat prompt value.

prompt_values.ChatPromptValueConcrete

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

prompt_values.PromptValue

Base abstract class for inputs to any language model.

prompt_values.StringPromptValue

String prompt value.

langchain_core.prompts¶

Prompt is the input to the model.

Prompt is often constructed from multiple components. Prompt classes and functions make constructing

and working with prompts easy.

Class hierarchy:

BasePromptTemplate --> PipelinePromptTemplate
                       StringPromptTemplate --> PromptTemplate
                                                FewShotPromptTemplate
                                                FewShotPromptWithTemplates
                       BaseChatPromptTemplate --> AutoGPTPrompt
                                                  ChatPromptTemplate --> AgentScratchPadChatPromptTemplate



BaseMessagePromptTemplate --> MessagesPlaceholder
                              BaseStringMessagePromptTemplate --> ChatMessagePromptTemplate
                                                                  HumanMessagePromptTemplate
                                                                  AIMessagePromptTemplate
                                                                  SystemMessagePromptTemplate

Classes¶

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

A 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.pipeline.PipelinePromptTemplate

A prompt template for composing multiple prompt templates together.

prompts.prompt.PromptTemplate

A prompt template for a language model.

prompts.string.StringPromptTemplate

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

Functions¶

prompts.base.format_document(doc, prompt)

Format a document into a string based on a prompt template.

prompts.loading.load_prompt(path)

Unified method for loading a prompt from LangChainHub or local fs.

prompts.loading.load_prompt_from_config(config)

Load prompt from Config Dict.

prompts.string.check_valid_template(...)

Check that template string is valid.

prompts.string.get_template_variables(...)

Get the variables from the template.

prompts.string.jinja2_formatter(template, ...)

Format a template using jinja2.

prompts.string.validate_jinja2(template, ...)

Validate that the input variables are valid for the template.

langchain_core.retrievers¶

Classes¶

retrievers.BaseRetriever

Abstract base class for a Document retrieval system.

langchain_core.runnables¶

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 of LLMs.

Programs created using LCEL and LangChain Runnables inherently support synchronous, asynchronous, batch, and streaming operations.

Support for async allows servers hosting LCEL based programs to scale better for higher concurrent loads.

Streaming of intermediate outputs as they’re being generated allows for creating more responsive UX.

This module contains schema and implementation of LangChain Runnables primitives.

Classes¶

runnables.base.Runnable()

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

runnables.base.RunnableBinding

A runnable that delegates calls to another runnable with a set of kwargs.

runnables.base.RunnableBindingBase

A runnable that delegates calls to another runnable with a set of kwargs.

runnables.base.RunnableEach

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

runnables.base.RunnableEachBase

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

runnables.base.RunnableGenerator(transform)

A 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

A runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.

runnables.base.RunnableSequence

A sequence of runnables, where the output of each is the input of the next.

runnables.base.RunnableSerializable

A Runnable that can be serialized to JSON.

runnables.branch.RunnableBranch

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

runnables.config.EmptyDict

Empty dict type.

runnables.config.RunnableConfig

Configuration for a Runnable.

runnables.configurable.DynamicRunnable

A Serializable Runnable that can be dynamically configured.

runnables.configurable.RunnableConfigurableAlternatives

A Runnable that can be dynamically configured.

runnables.configurable.RunnableConfigurableFields

A Runnable that can be dynamically configured.

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

A string enum.

runnables.fallbacks.RunnableWithFallbacks

A Runnable that can fallback to other Runnables if it fails.

runnables.history.RunnableWithMessageHistory

A runnable that manages chat message history for another runnable.

runnables.passthrough.RunnableAssign

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

runnables.passthrough.RunnablePassthrough

A runnable to passthrough inputs unchanged or with additional keys.

runnables.retry.RunnableRetry

Retry a Runnable if it fails.

runnables.router.RouterInput

A Router input.

runnables.router.RouterRunnable

A runnable that routes to a set of runnables based on Input['key'].

runnables.utils.AddableDict

Dictionary that can be added to another dictionary.

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

A field that can be configured by the user.

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

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

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

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

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

A field that can be configured by the user.

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.SupportsAdd(*args, **kwargs)

Protocol for objects that support addition.

Functions¶

runnables.base.coerce_to_runnable(thing)

Coerce a runnable-like object into a Runnable.

runnables.config.acall_func_with_variable_args(...)

Call function that may optionally accept a run_manager and/or config.

runnables.config.call_func_with_variable_args(...)

Call function that may optionally accept a run_manager and/or config.

runnables.config.ensure_config([config])

Ensure that a config is a dict with all keys present.

runnables.config.get_async_callback_manager_for_config(config)

Get an async callback manager for a config.

runnables.config.get_callback_manager_for_config(config)

Get a callback manager for a config.

runnables.config.get_config_list(config, length)

Get a list of configs from a single config or a list of configs.

runnables.config.get_executor_for_config(config)

Get an executor for a config.

runnables.config.merge_configs(*configs)

Merge multiple configs into one.

runnables.config.patch_config(config, *[, ...])

Patch a config with new values.

runnables.configurable.make_options_spec(...)

Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.

runnables.passthrough.aidentity(x)

An async identity function

runnables.passthrough.identity(x)

An identity function

runnables.utils.aadd(addables)

Asynchronously add a sequence of addable objects together.

runnables.utils.accepts_config(callable)

Check if a callable accepts a config argument.

runnables.utils.accepts_run_manager(callable)

Check if a callable accepts a run_manager argument.

runnables.utils.add(addables)

Add a sequence of addable objects together.

runnables.utils.gated_coro(semaphore, coro)

Run a coroutine with a semaphore.

runnables.utils.gather_with_concurrency(n, ...)

Gather coroutines with a limit on the number of concurrent coroutines.

runnables.utils.get_function_first_arg_dict_keys(func)

Get the keys of the first argument of a function if it is a dict.

runnables.utils.get_lambda_source(func)

Get the source code of a lambda function.

runnables.utils.get_unique_config_specs(specs)

Get the unique config specs from a sequence of config specs.

runnables.utils.indent_lines_after_first(...)

Indent all lines of text after the first line.

langchain_core.stores¶

Classes¶

stores.BaseStore()

Abstract interface for a key-value store.

langchain_core.tools¶

Base implementation for tools or skills.

Classes¶

tools.BaseTool

Interface LangChain tools must implement.

tools.SchemaAnnotationError

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

tools.StructuredTool

Tool that can operate on any number of inputs.

tools.Tool

Tool that takes in function or coroutine directly.

tools.ToolException

An optional exception that tool throws when execution error occurs.

Functions¶

tools.create_schema_from_function(...)

Create a pydantic schema from a function's signature.

tools.tool(*args[, return_direct, ...])

Make tools out of functions, can be used with or without arguments.

langchain_core.tracers¶

Classes¶

tracers.base.BaseTracer(**kwargs)

Base interface for tracers.

tracers.evaluation.EvaluatorCallbackHandler(...)

A tracer that runs a run evaluator whenever a run is persisted.

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

An implementation of the SharedTracer that POSTS to the langchain endpoint.

tracers.langchain_v1.LangChainTracerV1(**kwargs)

An 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(*)

A tracer that streams run logs to a stream.

tracers.log_stream.RunLog(*ops, state)

A run log.

tracers.log_stream.RunLogPatch(*ops)

A patch to the run log.

tracers.log_stream.RunState

State of the run.

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

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

A tracer that collects all nested runs in a list.

tracers.schemas.BaseRun

Base class for Run.

tracers.schemas.ChainRun

Class for ChainRun.

tracers.schemas.LLMRun

Class for LLMRun.

tracers.schemas.Run

Run schema for the V2 API in the Tracer.

tracers.schemas.ToolRun

Class for ToolRun.

tracers.schemas.TracerSession

TracerSessionV1 schema for the V2 API.

tracers.schemas.TracerSessionBase

Base class for TracerSession.

tracers.schemas.TracerSessionV1

TracerSessionV1 schema.

tracers.schemas.TracerSessionV1Base

Base class for TracerSessionV1.

tracers.schemas.TracerSessionV1Create

Create class for TracerSessionV1.

tracers.stdout.ConsoleCallbackHandler(**kwargs)

Tracer that prints to the console.

tracers.stdout.FunctionCallbackHandler(...)

Tracer that calls a function with a single str parameter.

Functions¶

tracers.context.collect_runs()

Collect all run traces in context.

tracers.context.register_configure_hook(...)

tracers.context.tracing_enabled([session_name])

Get the Deprecated LangChainTracer in a context manager.

tracers.context.tracing_v2_enabled([...])

Instruct LangChain to log all runs in context to LangSmith.

tracers.evaluation.wait_for_all_evaluators()

Wait for all tracers to finish.

tracers.langchain.get_client()

Get the client.

tracers.langchain.log_error_once(method, ...)

Log an error once.

tracers.langchain.wait_for_all_tracers()

Wait for all tracers to finish.

tracers.langchain_v1.get_headers()

Get the headers for the LangChain API.

tracers.schemas.RunTypeEnum()

RunTypeEnum.

tracers.stdout.elapsed(run)

Get the elapsed time of a run.

tracers.stdout.try_json_stringify(obj, fallback)

Try to stringify an object to JSON.

langchain_core.utils¶

Utility functions for LangChain.

These functions do not depend on any other LangChain module.

Classes¶

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.atee

alias of Tee

utils.formatting.StrictFormatter()

A subclass of formatter that checks for extra keys.

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

Functions¶

utils.aiter.py_anext(iterator[, default])

Pure-Python implementation of anext() for testing purposes.

utils.aiter.tee_peer(iterator, buffer, ...)

An individual iterator of a tee()

utils.env.env_var_is_set(env_var)

Check if an environment variable is set.

utils.input.get_bolded_text(text)

Get bolded text.

utils.input.get_color_mapping(items[, ...])

Get mapping for items to a support color.

utils.input.get_colored_text(text, color)

Get colored text.

utils.input.print_text(text[, color, end, file])

Print text with highlighting and no end characters.

utils.iter.batch_iterate(size, iterable)

Utility batching function.

utils.iter.tee_peer(iterator, buffer, peers, ...)

An individual iterator of a tee()

utils.loading.try_load_from_hub(path, ...)

Load configuration from hub.

utils.pydantic.get_pydantic_major_version()

Get the major version of Pydantic.

utils.utils.build_extra_kwargs(extra_kwargs, ...)

Build extra kwargs from values and extra_kwargs.

utils.utils.check_package_version(package[, ...])

Check the version of a package.

utils.utils.convert_to_secret_str(value)

Convert a string to a SecretStr if needed.

utils.utils.get_pydantic_field_names(...)

Get field names, including aliases, for a pydantic class.

utils.utils.guard_import(module_name, *[, ...])

Dynamically imports a module and raises a helpful exception if the module is not installed.

utils.utils.mock_now(dt_value)

Context manager for mocking out datetime.now() in unit tests.

utils.utils.raise_for_status_with_text(response)

Raise an error with the response text.

utils.utils.xor_args(*arg_groups)

Validate specified keyword args are mutually exclusive.

langchain_core.vectorstores¶

Classes¶

vectorstores.VectorStore()

Interface for vector store.

vectorstores.VectorStoreRetriever

Base Retriever class for VectorStore.