langchain_core
0.1.31¶
langchain_core.agents
¶
Agent is a class that uses an LLM to choose a sequence of actions to take.
In Chains, a sequence of actions is hardcoded. In Agents, a language model is used as a reasoning engine to determine which actions to take and in which order.
Agents select and use Tools and Toolkits for actions.
Class hierarchy:
BaseSingleActionAgent --> LLMSingleActionAgent
OpenAIFunctionsAgent
XMLAgent
Agent --> <name>Agent # Examples: ZeroShotAgent, ChatAgent
BaseMultiActionAgent --> OpenAIMultiFunctionsAgent
Main helpers:
AgentType, AgentExecutor, AgentOutputParser, AgentExecutorIterator,
AgentAction, AgentFinish, AgentStep
Classes¶
A full description of an action for an ActionAgent to execute. |
|
Override init to support instantiation by position for backward compat. |
|
The final return value of an ActionAgent. |
|
The result of running an AgentAction. |
langchain_core.beta
¶
Some beta features that are not yet ready for production.
Classes¶
Context for a runnable. |
|
[Beta] Get a context value. |
|
[Beta] Set a context value. |
|
|
Context for a runnable with a prefix. |
Functions¶
Asynchronously patch a runnable config with context getters and setters. |
|
Patch a runnable config with context getters and setters. |
langchain_core.caches
¶
Warning
Beta Feature!
Cache provides an optional caching layer for LLMs.
Cache is useful for two reasons:
It can save you money by reducing the number of API calls you make to the LLM provider if you’re often requesting the same completion multiple times.
It can speed up your application by reducing the number of API calls you make to the LLM provider.
Cache directly competes with Memory. See documentation for Pros and Cons.
Class hierarchy:
BaseCache --> <name>Cache # Examples: InMemoryCache, RedisCache, GPTCache
Classes¶
Base interface for cache. |
langchain_core.callbacks
¶
Callback handlers allow listening to events in LangChain.
Class hierarchy:
BaseCallbackHandler --> <name>CallbackHandler # Example: AimCallbackHandler
Classes¶
Async callback handler that handles callbacks from LangChain. |
|
Base callback handler that handles callbacks from LangChain. |
|
|
Base callback manager that handles callbacks from LangChain. |
Mixin for callback manager. |
|
Mixin for chain callbacks. |
|
Mixin for LLM callbacks. |
|
Mixin for Retriever callbacks. |
|
Mixin for run manager. |
|
Mixin for tool callbacks. |
|
|
Async callback manager that handles callbacks from LangChain. |
Async callback manager for the chain group. |
|
Async callback manager for chain run. |
|
Async callback manager for LLM run. |
|
|
Async callback manager for retriever run. |
Async callback manager for tool run. |
|
Async Parent Run Manager. |
|
|
Async Run Manager. |
|
Base class for run manager (a bound callback manager). |
|
Callback manager that handles callbacks from LangChain. |
Callback manager for the chain group. |
|
Callback manager for chain run. |
|
Callback manager for LLM run. |
|
Callback manager for retriever run. |
|
Callback manager for tool run. |
|
|
Sync Parent Run Manager. |
|
Sync Run Manager. |
Callback Handler that prints to std out. |
|
Callback handler for streaming. |
Functions¶
|
Generic event handler for AsyncCallbackManager. |
Get an async callback manager for a chain group in a context manager. |
|
|
Generic event handler for CallbackManager. |
Makes so an awaitable method is always shielded from cancellation |
|
Get a callback manager for a chain group in a context manager. |
langchain_core.chat_history
¶
Chat message history stores a history of the message interactions in a chat.
Class hierarchy:
BaseChatMessageHistory --> <name>ChatMessageHistory # Examples: FileChatMessageHistory, PostgresChatMessageHistory
Main helpers:
AIMessage, HumanMessage, BaseMessage
Classes¶
Abstract base class for storing chat message history. |
langchain_core.chat_sessions
¶
Chat Sessions are a collection of messages and function calls.
Classes¶
Chat Session represents a single conversation, channel, or other group of messages. |
langchain_core.document_loaders
¶
Classes¶
Abstract interface for blob parsers. |
|
Interface for Document Loader. |
|
Blob represents raw data by either reference or value. |
|
Abstract interface for blob loaders implementation. |
langchain_core.documents
¶
Document module is a collection of classes that handle documents and their transformations.
Classes¶
Class for storing a piece of text and associated metadata. |
|
Base class for document compressors. |
|
Abstract base class for document transformation systems. |
langchain_core.embeddings
¶
Embeddings interface.
Classes¶
Interface for embedding models. |
langchain_core.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.
Classes¶
Interface for selecting examples to include in prompts. |
|
Select examples based on length. |
|
|
ExampleSelector that selects examples based on Max Marginal Relevance. |
|
Example selector that selects examples based on SemanticSimilarity. |
Functions¶
Return a list of values in dict sorted by key. |
langchain_core.exceptions
¶
Custom exceptions for LangChain.
Classes¶
General LangChain exception. |
|
|
Exception that output parsers should raise to signify a parsing error. |
Base class for exceptions in tracers module. |
langchain_core.language_models
¶
Language Model is a type of model that can generate text or complete text prompts.
LangChain has two main classes to work with language models: - LLM classes provide access to the large language model (LLM) APIs and services. - Chat Models are a variation on language models.
Class hierarchy:
BaseLanguageModel --> BaseLLM --> LLM --> <name> # Examples: AI21, HuggingFaceHub, OpenAI
--> BaseChatModel --> <name> # Examples: ChatOpenAI, ChatGooglePalm
Main helpers:
LLMResult, PromptValue,
CallbackManagerForLLMRun, AsyncCallbackManagerForLLMRun,
CallbackManager, AsyncCallbackManager,
AIMessage, BaseMessage, HumanMessage
Classes¶
Abstract base class for interfacing with language models. |
|
Base class for Chat models. |
|
A simplified implementation for a chat model to inherit from. |
|
Base LLM abstract interface. |
|
Base LLM abstract class. |
Functions¶
Async generate from a stream. |
|
Generate from a stream. |
|
|
Get prompts that are already cached. |
Update the cache and get the LLM output. |
|
Create a retry decorator for a given LLM and provided list of error types. |
|
|
Get prompts that are already cached. |
Update the cache and get the LLM output. |
langchain_core.load
¶
Load module helps with serialization and deserialization.
Classes¶
|
Reviver for JSON objects. |
Base class for serialized objects. |
|
Serializable base class. |
|
Serialized constructor. |
|
Serialized not implemented. |
|
Serialized secret. |
Functions¶
|
Return a default value for a Serializable object or a SerializedNotImplemented object. |
|
Return a json dict representation of an object. |
|
Return a json string representation of an object. |
|
[Beta] Revive a LangChain class from a JSON object. |
|
[Beta] Revive a LangChain class from a JSON string. |
Serialize a "not implemented" object. |
|
|
Try to determine if a value is different from the default. |
langchain_core.memory
¶
Memory maintains Chain state, incorporating context from past runs.
Class hierarchy for Memory:
BaseMemory --> <name>Memory --> <name>Memory # Examples: BaseChatMemory -> MotorheadMemory
Classes¶
Abstract base class for memory in Chains. |
langchain_core.messages
¶
Messages are objects used in prompts and chat conversations.
Class hierarchy:
BaseMessage --> SystemMessage, AIMessage, HumanMessage, ChatMessage, FunctionMessage, ToolMessage
--> BaseMessageChunk --> SystemMessageChunk, AIMessageChunk, HumanMessageChunk, ChatMessageChunk, FunctionMessageChunk, ToolMessageChunk
Main helpers:
ChatPromptTemplate
Classes¶
Message from an AI. |
|
Message chunk from an AI. |
|
Base abstract Message class. |
|
Message chunk, which can be concatenated with other Message chunks. |
|
Message that can be assigned an arbitrary speaker (i.e. |
|
Chat Message chunk. |
|
Message for passing the result of executing a function back to a model. |
|
Function Message chunk. |
|
Message from a human. |
|
Human Message chunk. |
|
Message for priming AI behavior, usually passed in as the first of a sequence of input messages. |
|
System Message chunk. |
|
Message for passing the result of executing a tool back to a model. |
|
Tool Message chunk. |
Functions¶
|
Get a title representation for a message. |
|
Merge two message contents. |
|
Convert a Message to a dictionary. |
|
Convert a sequence of Messages to a list of dictionaries. |
langchain_core.output_parsers
¶
OutputParser classes parse the output of an LLM call.
Class hierarchy:
BaseLLMOutputParser --> BaseOutputParser --> <name>OutputParser # ListOutputParser, PydanticOutputParser
Main helpers:
Serializable, Generation, PromptValue
Classes¶
Base class to parse the output of an LLM call. |
|
Abstract base class for parsing the outputs of a model. |
|
Base class to parse the output of an LLM call. |
|
Parse the output of an LLM call to a JSON object. |
|
alias of |
|
Parse the output of an LLM call to a comma-separated list. |
|
Parse the output of an LLM call to a list. |
|
Parse a markdown list. |
|
Parse a numbered list. |
|
|
Parse an output as the element of the Json object. |
Parse an output as the Json object. |
|
Parse an output that is one of sets of values. |
|
|
Parse an output as an attribute of a pydantic object. |
|
Parse an output as a pydantic object. |
Parse tools from OpenAI response. |
|
Parse tools from OpenAI response. |
|
Parse tools from OpenAI response. |
|
Parse an output using a pydantic model. |
|
OutputParser that parses LLMResult into the top likely string. |
|
|
Base class for an output parser that can handle streaming input. |
Base class for an output parser that can handle streaming input. |
|
Parse an output using xml format. |
Functions¶
Parse a JSON string from a Markdown string and check that it contains the expected keys. |
|
Parse a JSON string from a Markdown string. |
|
Parse a JSON string that may be missing closing braces. |
|
|
Drop the last n elements of an iterator. |
|
Get nested element from path. |
langchain_core.outputs
¶
Output classes are used to represent the output of a language model call and the output of a chat.
Classes¶
A single chat generation output. |
|
ChatGeneration chunk, which can be concatenated with other |
|
Class that contains all results for a single chat model call. |
|
A single text generation output. |
|
Generation chunk, which can be concatenated with other Generation chunks. |
|
Class that contains all results for a batched LLM call. |
|
Class that contains metadata for a single execution of a Chain or model. |
langchain_core.prompt_values
¶
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.
Classes¶
Chat prompt value. |
|
Chat prompt value which explicitly lists out the message types it accepts. |
|
Image prompt value. |
|
Base abstract class for inputs to any language model. |
|
String prompt value. |
langchain_core.prompts
¶
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.
Class hierarchy:
BasePromptTemplate --> PipelinePromptTemplate
StringPromptTemplate --> PromptTemplate
FewShotPromptTemplate
FewShotPromptWithTemplates
BaseChatPromptTemplate --> AutoGPTPrompt
ChatPromptTemplate --> AgentScratchPadChatPromptTemplate
BaseMessagePromptTemplate --> MessagesPlaceholder
BaseStringMessagePromptTemplate --> ChatMessagePromptTemplate
HumanMessagePromptTemplate
AIMessagePromptTemplate
SystemMessagePromptTemplate
Classes¶
Base class for all prompt templates, returning a prompt. |
|
AI message prompt template. |
|
Base class for chat prompt templates. |
|
Base class for message prompt templates. |
|
Base class for message prompt templates that use a string prompt template. |
|
Chat message prompt template. |
|
Prompt template for chat models. |
|
Human message prompt template. |
|
Prompt template that assumes variable is already list of messages. |
|
System message prompt template. |
|
Chat prompt template that supports few-shot examples. |
|
Prompt template that contains few shot examples. |
|
Prompt template that contains few shot examples. |
|
An image prompt template for a multimodal model. |
|
Prompt template for composing multiple prompt templates together. |
|
A prompt template for a language model. |
|
String prompt that exposes the format method, returning a prompt. |
Functions¶
|
Format a document into a string based on a prompt template. |
Unified method for loading a prompt from LangChainHub or local fs. |
|
Load prompt from Config Dict. |
|
Check that template string is valid. |
|
Get the variables from the template. |
|
|
Format a template using jinja2. |
|
Validate that the input variables are valid for the template. |
langchain_core.retrievers
¶
Retriever class returns Documents given a text query.
It is more general than a vector store. A retriever does not need to be able to store documents, only to return (or retrieve) it. Vector stores can be used as the backbone of a retriever, but there are other types of retrievers as well.
Class hierarchy:
BaseRetriever --> <name>Retriever # Examples: ArxivRetriever, MergerRetriever
Main helpers:
RetrieverInput, RetrieverOutput, RetrieverLike, RetrieverOutputLike,
Document, Serializable, Callbacks,
CallbackManagerForRetrieverRun, AsyncCallbackManagerForRetrieverRun
Classes¶
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.
Batch operations allow for processing multiple inputs in parallel.
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¶
A unit of work that can be invoked, batched, streamed, transformed and composed. |
|
Wrap a Runnable with additional functionality. |
|
Runnable that delegates calls to another Runnable with a set of kwargs. |
|
Runnable that delegates calls to another Runnable with each element of the input sequence. |
|
Runnable that delegates calls to another Runnable with each element of the input sequence. |
|
|
Runnable that runs a generator function. |
|
RunnableLambda converts a python callable into a Runnable. |
alias of |
|
Runnable that runs a mapping of Runnables in parallel, and returns a mapping of their outputs. |
|
Sequence of Runnables, where the output of each is the input of the next. |
|
Runnable that can be serialized to JSON. |
|
Runnable that selects which branch to run based on a condition. |
|
ThreadPoolExecutor that copies the context to the child thread. |
|
Empty dict type. |
|
Configuration for a Runnable. |
|
Serializable Runnable that can be dynamically configured. |
|
Runnable that can be dynamically configured. |
|
Runnable that can be dynamically configured. |
|
|
String enum. |
Runnable that can fallback to other Runnables if it fails. |
|
|
Edge in a graph. |
|
Graph of nodes and edges. |
|
Node in a graph. |
|
Class for drawing in ASCII. |
Class to define vertex box boundaries that will be accounted for during graph building by grandalf. |
|
|
A helper class to draw a state graph into a PNG file. Requires graphviz and pygraphviz to be installed. :param fontname: The font to use for the labels :param labels: A dictionary of label overrides. The dictionary should have the following format: { "nodes": { "node1": "CustomLabel1", "node2": "CustomLabel2", "__end__": "End Node" }, "edges": { "continue": "ContinueLabel", "end": "EndLabel" } } The keys are the original labels, and the values are the new labels. Usage: drawer = PngDrawer() drawer.draw(state_graph, 'graph.png'). |
Runnable that manages chat message history for another Runnable. |
|
A runnable that assigns key-value pairs to Dict[str, Any] inputs. |
|
Runnable to passthrough inputs unchanged or with additional keys. |
|
Runnable that picks keys from Dict[str, Any] inputs. |
|
Retry a Runnable if it fails. |
|
Router input. |
|
Runnable that routes to a set of Runnables based on Input['key']. |
|
Data associated with a streaming event. |
|
Streaming event. |
|
Dictionary that can be added to another dictionary. |
|
|
Field that can be configured by the user. |
Field that can be configured by the user with multiple default values. |
|
Field that can be configured by the user with a default value. |
|
Field that can be configured by the user. |
|
Get the nonlocal variables accessed of a function. |
|
Get the source code of a lambda function. |
|
Check if the first argument of a function is a dict. |
|
|
Check if a name is a local dict. |
Get nonlocal variables accessed. |
|
|
Protocol for objects that support addition. |
Functions¶
Decorate a function to make it a Runnable. |
|
Coerce a runnable-like object into a Runnable. |
|
Call function that may optionally accept a run_manager and/or config. |
|
Call function that may optionally accept a run_manager and/or config. |
|
|
Ensure that a config is a dict with all keys present. |
|
Get an async callback manager for a config. |
Get a callback manager for a config. |
|
|
Get a list of configs from a single config or a list of configs. |
Get an executor for a config. |
|
|
Merge multiple configs into one. |
|
Patch a config with new values. |
Run a function in an executor. |
|
Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption. |
|
Prefix the id of a ConfigurableFieldSpec. |
|
|
|
|
Build a DAG and draw it in ASCII. |
Async identity function |
|
Identity function |
|
|
Asynchronously add a sequence of addable objects together. |
|
Check if a callable accepts a config argument. |
|
Check if a callable accepts a context argument. |
|
Check if a callable accepts a run_manager argument. |
|
Add a sequence of addable objects together. |
|
|
|
Run a coroutine with a semaphore. |
Gather coroutines with a limit on the number of concurrent coroutines. |
|
Get the keys of the first argument of a function if it is a dict. |
|
Get the nonlocal variables accessed by a function. |
|
Get the source code of a lambda function. |
|
Get the unique config specs from a sequence of config specs. |
|
Indent all lines of text after the first line. |
langchain_core.stores
¶
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 storages is to support implementation of caching.
Classes¶
Abstract interface for a key-value store. |
langchain_core.sys_info
¶
sys_info prints information about the system and langchain packages for debugging purposes.
Functions¶
|
Print information about the environment for debugging purposes. |
langchain_core.tools
¶
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.
Class hierarchy:
RunnableSerializable --> BaseTool --> <name>Tool # Examples: AIPluginTool, BaseGraphQLTool
<name> # Examples: BraveSearch, HumanInputRun
Main helpers:
CallbackManagerForToolRun, AsyncCallbackManagerForToolRun
Classes¶
Interface LangChain tools must implement. |
|
Raised when 'args_schema' is missing or has an incorrect type annotation. |
|
Tool that can operate on any number of inputs. |
|
Tool that takes in function or coroutine directly. |
|
Optional exception that tool throws when execution error occurs. |
Functions¶
Create a pydantic schema from a function's signature. |
|
|
Make tools out of functions, can be used with or without arguments. |
langchain_core.tracers
¶
Tracers are classes for tracing runs.
Class hierarchy:
BaseCallbackHandler --> BaseTracer --> <name>Tracer # Examples: LangChainTracer, RootListenersTracer
--> <name> # Examples: LogStreamCallbackHandler
Classes¶
|
Base interface for tracers. |
Tracer that runs a run evaluator whenever a run is persisted. |
|
Implementation of the SharedTracer that POSTS to the LangChain endpoint. |
|
|
[Deprecated] Implementation of the SharedTracer that POSTS to the langchain endpoint. |
A single entry in the run log. |
|
Tracer that streams run logs to a stream. |
|
|
Run log. |
Patch to the run log. |
|
State of the run. |
|
Tracer that calls listeners on run start, end, and error. |
|
Tracer that collects all nested runs in a list. |
|
[Deprecated] Base class for Run. |
|
[Deprecated] Class for ChainRun. |
|
[Deprecated] Class for LLMRun. |
|
Run schema for the V2 API in the Tracer. |
|
[Deprecated] Class for ToolRun. |
|
[Deprecated] TracerSessionV1 schema for the V2 API. |
|
[Deprecated] Base class for TracerSession. |
|
[Deprecated] TracerSessionV1 schema. |
|
[Deprecated] Base class for TracerSessionV1. |
|
[Deprecated] Create class for TracerSessionV1. |
|
|
Tracer that prints to the console. |
Tracer that calls a function with a single str parameter. |
Functions¶
Collect all run traces in context. |
|
Register a configure hook. |
|
|
[Deprecated] Get the Deprecated LangChainTracer in a context manager. |
Instruct LangChain to log all runs in context to LangSmith. |
|
Wait for all tracers to finish. |
|
Get the client. |
|
|
Log an error once. |
Wait for all tracers to finish. |
|
Get the headers for the LangChain API. |
|
[Deprecated] RunTypeEnum. |
|
Get the elapsed time of a run. |
|
|
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¶
Dummy lock that provides the proper interface but no protection |
|
|
Create |
alias of |
|
Formatter that checks for extra keys. |
|
Representation of a callable function to send to an LLM. |
|
Representation of a callable function to the OpenAI API. |
|
Dummy lock that provides the proper interface but no protection |
|
|
Create |
alias of |
Functions¶
|
Pure-Python implementation of anext() for testing purposes. |
|
An individual iterator of a |
|
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. |
|
[Deprecated] Converts a Pydantic model to a function description for the OpenAI API. |
[Deprecated] Converts a Pydantic model to a function description for the OpenAI API. |
|
|
[Deprecated] Convert a Python function to an OpenAI function-calling API compatible dict. |
Convert a raw function/class to an OpenAI function. |
|
Convert a raw function/class to an OpenAI tool. |
|
[Deprecated] Format tool into the OpenAI function API. |
|
[Deprecated] Format tool into the OpenAI function API. |
|
|
Extract all links from a raw html string and convert into absolute paths. |
|
Extract all links from a raw html string. |
|
Get base64 string from image URI. |
|
|
Get bolded text. |
|
|
Get mapping for items to a support color. |
|
Get colored text. |
|
Print text with highlighting and no end characters. |
Determine if running within IPython or Jupyter. |
|
|
Utility batching function. |
|
An individual iterator of a |
|
Try to substitute $refs in JSON Schema. |
|
[Deprecated] Load configuration from hub. |
Get the major version of Pydantic. |
|
|
Convert a list to a comma-separated string. |
Stringify a dictionary. |
|
Stringify a value. |
|
|
Build extra kwargs from values and extra_kwargs. |
|
Check the version of a package. |
Convert a string to a SecretStr if needed. |
|
Get field names, including aliases, for a pydantic class. |
|
|
Dynamically imports a module and raises a helpful exception if the module is not installed. |
|
Context manager for mocking out datetime.now() in unit tests. |
|
Raise an error with the response text. |
|
Validate specified keyword args are mutually exclusive. |
langchain_core.vectorstores
¶
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 then query the store and retrieve the data that are ‘most similar’ to the embedded query.
Class hierarchy:
VectorStore --> <name> # Examples: Annoy, FAISS, Milvus
BaseRetriever --> VectorStoreRetriever --> <name>Retriever # Example: VespaRetriever
Main helpers:
Embeddings, Document
Classes¶
Interface for vector store. |
|
Base Retriever class for VectorStore. |