langchain
0.2.17¶
langchain.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
Classes¶
Agent that is using tools. |
|
Base class for parsing agent output into agent action/finish. |
|
Base Multi Action Agent class. |
|
Base Single Action Agent class. |
|
Tool that just returns the query. |
|
Base class for parsing agent output into agent actions/finish. |
|
Agent powered by Runnables. |
|
Agent powered by Runnables. |
|
Iterator for AgentExecutor. |
|
Information about a VectorStore. |
|
|
Toolkit for routing between Vector Stores. |
|
Toolkit for interacting with a Vector Store. |
Output parser for the chat agent. |
|
Output parser for the conversational agent. |
|
Output parser for the conversational agent. |
|
|
Configuration for a chain to use in MRKL system. |
MRKL Output parser for the chat agent. |
|
AgentAction with info needed to submit custom tool output to existing run. |
|
AgentFinish with run and thread metadata. |
|
Run an OpenAI Assistant. |
|
|
Memory used to save agent output AND intermediate steps. |
Parses tool invocations and final answers in JSON format. |
|
|
Parses a message into agent action/finish. |
|
Parses a message into agent actions/finish. |
|
Parses ReAct-style LLM calls that have a single tool input in json format. |
|
Parses ReAct-style LLM calls that have a single tool input. |
Parses self-ask style LLM calls. |
|
|
|
Parses a message into agent actions/finish. |
|
Parses tool invocations and final answers in XML format. |
|
Output parser for the ReAct agent. |
|
Chat prompt template for the agent scratchpad. |
|
|
Output parser for the structured chat agent. |
|
Output parser with retries for the structured chat agent. |
Tool that is run when invalid tool name is encountered by agent. |
Functions¶
A convenience method for creating a conversational retrieval agent. |
|
Construct the scratchpad that lets the agent continue its thought process. |
|
|
Construct the scratchpad that lets the agent continue its thought process. |
|
Convert (AgentAction, tool output) tuples into FunctionMessages. |
|
Convert (AgentAction, tool output) tuples into FunctionMessages. |
Convert (AgentAction, tool output) tuples into ToolMessages. |
|
Format the intermediate steps as XML. |
|
Create an agent that uses JSON to format its logic, build for Chat Models. |
|
|
Create an agent that uses OpenAI function calling. |
Create an agent that uses OpenAI tools. |
|
|
Parse an AI message potentially containing tool_calls. |
|
Parse an AI message potentially containing tool_calls. |
|
Create an agent that uses ReAct prompting. |
|
Create an agent that uses self-ask with search prompting. |
|
Create an agent aimed at supporting tools with multiple inputs. |
|
Create an agent that uses tools. |
Validate tools for single input. |
|
|
Create an agent that uses XML to format its logic. |
Deprecated classes¶
Deprecated since version 0.1.0: Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. |
|
Deprecated since version 0.1.0: Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. |
|
|
Deprecated since version 0.1.0: Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. |
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0. |
|
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0: Use |
|
|
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0. |
Deprecated since version 0.1.0. |
|
Deprecated since version 0.1.0. |
|
Deprecated since version 0.1.0. |
|
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0. |
|
Deprecated since version 0.1.0: Use |
|
Deprecated since version 0.1.0: Use |
Deprecated functions¶
langchain.callbacks
¶
Callback handlers allow listening to events in LangChain.
Class hierarchy:
BaseCallbackHandler --> <name>CallbackHandler # Example: AimCallbackHandler
Classes¶
Callback handler that returns an async iterator. |
|
|
Callback handler that returns an async iterator. |
|
Callback handler for streaming in agents. |
Tracer that logs via the input Logger. |
langchain.chains
¶
Chains are easily reusable components linked together.
Chains encode a sequence of calls to components like models, document retrievers, other Chains, etc., and provide a simple interface to this sequence.
The Chain interface makes it easy to create apps that are:
Stateful: add Memory to any Chain to give it state,
Observable: pass Callbacks to a Chain to execute additional functionality, like logging, outside the main sequence of component calls,
Composable: combine Chains with other components, including other Chains.
Class hierarchy:
Chain --> <name>Chain # Examples: LLMChain, MapReduceChain, RouterChain
Classes¶
Abstract base class for creating structured sequences of calls to components. |
|
Base interface for chains combining documents. |
|
Combining documents by mapping a chain over them, then combining results. |
|
Combining documents by mapping a chain over them, then reranking results. |
|
|
Interface for the combine_docs method. |
Interface for the combine_docs method. |
|
Combine documents by recursively reducing them. |
|
Combine documents by doing a first pass and then refining on more documents. |
|
Class for a constitutional principle. |
|
|
Chain for chatting with an index. |
Chain for chatting with a vector database. |
|
Input type for ConversationalRetrievalChain. |
|
|
Chain for interacting with Elasticsearch Database. |
Chain that combines a retriever, a question generator, and a response generator. |
|
Chain that generates questions from uncertain spans. |
|
Output parser that checks if the output is finished. |
|
Generate hypothetical document for query, and then embed that. |
|
Pass input through a moderation endpoint. |
|
A crawler for web pages. |
|
A typed dictionary containing information about elements in the viewport. |
|
|
Class representing a single statement. |
A question and its answer as a list of facts each one should have a source. |
|
Chain for making a simple request to an API endpoint. |
|
An answer to the question, with sources. |
|
Base class for prompt selectors. |
|
Prompt collection that goes through conditionals. |
|
Interface for loading the combine documents chain. |
|
|
Question-answering with sources over an index. |
Question-answering with sources over a vector database. |
|
Output parser that parses a structured query. |
|
A date in ISO 8601 format (YYYY-MM-DD). |
|
A datetime in ISO 8601 format (YYYY-MM-DDTHH:MM:SS). |
|
Information about a data source attribute. |
|
Interface for loading the combine documents chain. |
|
Use a single chain to route an input to one of multiple candidate chains. |
|
|
Create new instance of Route(destination, next_inputs) |
Chain that outputs the name of a destination chain and the inputs to it. |
|
Chain that uses embeddings to route between options. |
|
Parser for output of router chain in the multi-prompt chain. |
|
A multi-route chain that uses an LLM router chain to choose amongst retrieval qa chains. |
|
Chain where the outputs of one chain feed directly into next. |
|
Simple chain where the outputs of one step feed directly into next. |
|
Input for a SQL Chain. |
|
Input for a SQL Chain. |
|
Interface for loading the combine documents chain. |
|
Chain that transforms the chain output. |
Functions¶
Execute a collapse function on a set of documents and merge their metadatas. |
|
Execute a collapse function on a set of documents and merge their metadatas. |
|
Split Documents into subsets that each meet a cumulative length constraint. |
|
|
Create a chain for passing a list of Documents to a model. |
Return another example given a list of examples for a prompt. |
|
|
Create a chain that takes conversation history and returns documents. |
|
Create a citation fuzzy match Runnable. |
|
Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI |
Return the kwargs for the LLMChain constructor. |
|
Check if the language model is a chat model. |
|
Check if the language model is a LLM. |
|
Construct examples from input-output pairs. |
|
Fix invalid filter directive. |
|
|
Create query construction prompt. |
|
Load a query constructor runnable chain. |
Return a parser for the query language. |
|
Dummy decorator for when lark is not installed. |
|
Create retrieval chain that retrieves documents and then passes them on. |
|
Create a chain that generates SQL queries. |
|
Get the appropriate function output parser given the user functions. |
|
Load summarizing chain. |
Deprecated classes¶
Deprecated since version 0.2.13: This class is deprecated and will be removed in langchain 1.0. See API reference for replacement: https://api.python.langchain.com/en/latest/chains/langchain.chains.api.base.APIChain.html |
|
Deprecated since version 0.2.7: Use |
|
Deprecated since version 0.2.13: This class is deprecated. Use the create_stuff_documents_chain constructor instead. See migration guide here: https://python.langchain.com/v0.2/docs/versions/migrating_chains/stuff_docs_chain/ |
|
Deprecated since version 0.2.13: This class is deprecated and will be removed in langchain 1.0. See API reference for replacement: https://api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.html |
|
Deprecated since version 0.2.7: Use |
|
|
Deprecated since version 0.1.17: Use |
Deprecated since version 0.1.17: Use |
|
Deprecated since version 0.2.13: See LangGraph guides for a variety of self-reflection and corrective strategies for question-answering and other tasks: https://langchain-ai.github.io/langgraph/tutorials/rag/langgraph_self_rag/ |
|
Deprecated since version 0.2.13: This class is deprecated and will be removed in langchain 1.0. See API reference for replacement: https://api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.html |
|
|
Deprecated since version 0.2.13: See LangGraph guides for a variety of self-reflection and corrective strategies for question-answering and other tasks: https://langchain-ai.github.io/langgraph/tutorials/rag/langgraph_self_rag/ |
Deprecated since version 0.2.13: Refer here for a recommended map-reduce implementation using langgraph: https://langchain-ai.github.io/langgraph/how-tos/map-reduce/. See also migration guide: https://python.langchain.com/v0.2/docs/versions/migrating_chains/map_reduce_chain/ |
|
Deprecated since version 0.2.13: Importing NatBotChain from langchain is deprecated and will be removed in langchain 1.0. Please import from langchain_community instead: from langchain_community.chains.natbot import NatBotChain. You may need to pip install -U langchain-community. |
|
Deprecated since version 0.2.7: Use |
|
Deprecated since version 0.2.13: This class is deprecated. Refer to this guide on retrieval and question answering with sources: https://python.langchain.com/v0.2/docs/how_to/qa_sources/ |
|
Deprecated since version 0.2.13: This class is deprecated. Refer to this guide on retrieval and question answering with sources: https://python.langchain.com/v0.2/docs/how_to/qa_sources/ |
|
Deprecated since version 0.2.13: This class is deprecated. Use the create_retrieval_chain constructor instead. See migration guide here: https://python.langchain.com/v0.2/docs/versions/migrating_chains/retrieval_qa/ |
|
Deprecated since version 0.1.17: This class is deprecated. Use the create_retrieval_chain constructor instead. See migration guide here: https://python.langchain.com/v0.2/docs/versions/migrating_chains/retrieval_qa/ |
|
Deprecated since version 0.2.13: This class is deprecated. Use the create_retrieval_chain constructor instead. See migration guide here: https://python.langchain.com/v0.2/docs/versions/migrating_chains/retrieval_qa/ |
|
Deprecated since version 0.2.12: Use RunnableLambda to select from multiple prompt templates. See example in API reference: https://api.python.langchain.com/en/latest/chains/langchain.chains.router.llm_router.LLMRouterChain.html |
|
Deprecated since version 0.2.12: Use RunnableLambda to select from multiple prompt templates. See example in API reference: https://api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html |
Deprecated functions¶
|
Deprecated since version 0.2.13: This function is deprecated and will be removed in langchain 1.0. At that point chains must be imported from their respective modules. |
Deprecated since version 0.2.13: This function is deprecated and will be removed in langchain 1.0. At that point chains must be imported from their respective modules. |
|
Deprecated since version 0.1.1: Use |
|
|
Deprecated since version 0.1.1: Use |
|
Deprecated since version 0.2.13: Use |
|
Deprecated since version 0.1.14: LangChain has introduced a method called with_structured_output thatis available on ChatModels capable of tool calling.You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>. Please follow our extraction use case documentation for more guidelineson how to do information extraction with LLMs.<https://python.langchain.com/docs/use_cases/extraction/>. If you notice other issues, please provide feedback here:<https://github.com/langchain-ai/langchain/discussions/18154> Use `` |
|
Deprecated since version 0.1.14: LangChain has introduced a method called with_structured_output thatis available on ChatModels capable of tool calling.You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>. Please follow our extraction use case documentation for more guidelineson how to do information extraction with LLMs.<https://python.langchain.com/docs/use_cases/extraction/>. If you notice other issues, please provide feedback here:<https://github.com/langchain-ai/langchain/discussions/18154> Use `` |
Deprecated since version 0.2.13: This function is deprecated and will be removed in langchain 1.0. See API reference for replacement: https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.openapi.get_openapi_chain.html |
|
|
Deprecated since version 0.2.13: This function is deprecated. Refer to this guide on retrieval and question answering with sources: https://python.langchain.com/v0.2/docs/how_to/qa_sources/#structure-sources-in-model-response |
|
Deprecated since version 0.2.13: This function is deprecated. Refer to this guide on retrieval and question answering with structured responses: https://python.langchain.com/v0.2/docs/how_to/qa_sources/#structure-sources-in-model-response |
Deprecated since version 0.2.13: LangChain has introduced a method called with_structured_output that is available on ChatModels capable of tool calling. See API reference for this function for replacement: <https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain.html> You can read more about with_structured_output here: <https://python.langchain.com/v0.2/docs/how_to/structured_output/>. If you notice other issues, please provide feedback here: <https://github.com/langchain-ai/langchain/discussions/18154> |
|
|
Deprecated since version 0.2.13: LangChain has introduced a method called with_structured_output that is available on ChatModels capable of tool calling. See API reference for this function for replacement: <https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain_pydantic.html> You can read more about with_structured_output here: <https://python.langchain.com/v0.2/docs/how_to/structured_output/>. If you notice other issues, please provide feedback here: <https://github.com/langchain-ai/langchain/discussions/18154> |
|
Deprecated since version 0.1.14: LangChain has introduced a method called with_structured_output thatis available on ChatModels capable of tool calling.You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>. Please follow our extraction use case documentation for more guidelineson how to do information extraction with LLMs.<https://python.langchain.com/docs/use_cases/extraction/>. with_structured_output does not currently support a list of pydantic schemas. If this is a blocker or if you notice other issues, please provide feedback here:<https://github.com/langchain-ai/langchain/discussions/18154> Use `` |
|
Deprecated since version 0.2.13: This function is deprecated. Refer to this guide on retrieval and question answering with sources: https://python.langchain.com/v0.2/docs/how_to/qa_sources/ |
|
Deprecated since version 0.2.13: Use |
Deprecated since version 0.2.13: This class is deprecated. See the following migration guides for replacements based on chain_type: |
|
|
Deprecated since version 0.1.14: LangChain has introduced a method called with_structured_output that is available on ChatModels capable of tool calling. You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>. Please follow our extraction use case documentation for more guidelines on how to do information extraction with LLMs. <https://python.langchain.com/docs/use_cases/extraction/>. If you notice other issues, please provide feedback here: <https://github.com/langchain-ai/langchain/discussions/18154> Use `` |
|
Deprecated since version 0.1.17: LangChain has introduced a method called with_structured_output that is available on ChatModels capable of tool calling. You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>.Please follow our extraction use case documentation for more guidelines on how to do information extraction with LLMs. <https://python.langchain.com/docs/use_cases/extraction/>. If you notice other issues, please provide feedback here: <https://github.com/langchain-ai/langchain/discussions/18154> Use `` |
langchain.chat_models
¶
Chat Models are a variation on language models.
While Chat Models use language models under the hood, the interface they expose is a bit different. Rather than expose a “text in, text out” API, they expose an interface where “chat messages” are the inputs and outputs.
Class hierarchy:
BaseLanguageModel --> BaseChatModel --> <name> # Examples: ChatOpenAI, ChatGooglePalm
Main helpers:
AIMessage, BaseMessage, HumanMessage
Functions¶
langchain.embeddings
¶
Embedding models are wrappers around embedding models from different APIs and services.
Embedding models can be LLMs or not.
Class hierarchy:
Embeddings --> <name>Embeddings # Examples: OpenAIEmbeddings, HuggingFaceEmbeddings
Classes¶
Interface for caching results from embedding models. |
langchain.evaluation
¶
Evaluation chains for grading LLM and Chain outputs.
This module contains off-the-shelf evaluation chains for grading the output of LangChain primitives such as language models and chains.
Loading an evaluator
To load an evaluator, you can use the load_evaluators
or
load_evaluator
functions with the
names of the evaluators to load.
from langchain.evaluation import load_evaluator
evaluator = load_evaluator("qa")
evaluator.evaluate_strings(
prediction="We sold more than 40,000 units last week",
input="How many units did we sell last week?",
reference="We sold 32,378 units",
)
The evaluator must be one of EvaluatorType
.
Datasets
To load one of the LangChain HuggingFace datasets, you can use the load_dataset
function with the
name of the dataset to load.
from langchain.evaluation import load_dataset
ds = load_dataset("llm-math")
Some common use cases for evaluation include:
Grading the accuracy of a response against ground truth answers:
QAEvalChain
Comparing the output of two models:
PairwiseStringEvalChain
orLabeledPairwiseStringEvalChain
when there is additionally a reference label.Judging the efficacy of an agent’s tool usage:
TrajectoryEvalChain
Checking whether an output complies with a set of criteria:
CriteriaEvalChain
orLabeledCriteriaEvalChain
when there is additionally a reference label.Computing semantic difference between a prediction and reference:
EmbeddingDistanceEvalChain
or between two predictions:PairwiseEmbeddingDistanceEvalChain
Measuring the string distance between a prediction and reference
StringDistanceEvalChain
or between two predictionsPairwiseStringDistanceEvalChain
Low-level API
These evaluators implement one of the following interfaces:
StringEvaluator
: Evaluate a prediction string against a reference label and/or input context.PairwiseStringEvaluator
: Evaluate two prediction strings against each other. Useful for scoring preferences, measuring similarity between two chain or llm agents, or comparing outputs on similar inputs.AgentTrajectoryEvaluator
Evaluate the full sequence of actions taken by an agent.
These interfaces enable easier composability and usage within a higher level evaluation framework.
Classes¶
A named tuple containing the score and reasoning for a trajectory. |
|
A chain for evaluating ReAct style agents. |
|
|
Trajectory output parser. |
|
A chain for comparing two outputs, such as the outputs |
A chain for comparing two outputs, such as the outputs |
|
|
A parser for the output of the PairwiseStringEvalChain. |
A Criteria to evaluate. |
|
LLM Chain for evaluating runs against criteria. |
|
A parser for the output of the CriteriaEvalChain. |
|
Criteria evaluation chain that requires references. |
|
Embedding Distance Metric. |
|
|
Use embedding distances to score semantic difference between a prediction and reference. |
|
Use embedding distances to score semantic difference between two predictions. |
Compute an exact match between the prediction and the reference. |
|
Evaluate whether the prediction is equal to the reference after |
|
Evaluate whether the prediction is valid JSON. |
|
|
An evaluator that calculates the edit distance between JSON strings. |
An evaluator that validates a JSON prediction against a JSON schema reference. |
|
LLM Chain for evaluating QA w/o GT based on context |
|
LLM Chain for evaluating QA using chain of thought reasoning. |
|
LLM Chain for evaluating question answering. |
|
LLM Chain for generating examples for question answering. |
|
Compute a regex match between the prediction and the reference. |
|
Interface for evaluating agent trajectories. |
|
The types of the evaluators. |
|
A base class for evaluators that use an LLM. |
|
Compare the output of two models (or two outputs of the same model). |
|
Grade, tag, or otherwise evaluate predictions relative to their inputs and/or reference labels. |
|
A chain for scoring the output of a model on a scale of 1-10. |
|
A chain for scoring on a scale of 1-10 the output of a model. |
|
A parser for the output of the ScoreStringEvalChain. |
|
|
Compute string edit distances between two predictions. |
Distance metric to use. |
|
Compute string distances between the prediction and the reference. |
Functions¶
|
Resolve the criteria for the pairwise evaluator. |
Resolve the criteria to evaluate. |
|
Load a dataset from the LangChainDatasets on HuggingFace. |
|
|
Load the requested evaluation chain specified by a string. |
|
Load evaluators specified by a list of evaluator types. |
Resolve the criteria for the pairwise evaluator. |
langchain.globals
¶
Global values and configuration that apply to all of LangChain.
Functions¶
Get the value of the debug global setting. |
|
Get the value of the llm_cache global setting. |
|
Get the value of the verbose global setting. |
|
|
Set a new value for the debug global setting. |
|
Set a new LLM cache, overwriting the previous value, if any. |
|
Set a new value for the verbose global setting. |
langchain.hub
¶
Interface with the LangChain Hub.
Functions¶
|
Pull an object from the hub and returns it as a LangChain object. |
|
Push an object to the hub and returns the URL it can be viewed at in a browser. |
langchain.indexes
¶
Index is used to avoid writing duplicated content into the vectostore and to avoid over-writing content if it’s unchanged.
Indexes also :
Create knowledge graphs from data.
Support indexing workflows from LangChain data loaders to vectorstores.
Importantly, Index keeps on working even if the content being written is derived via a set of transformations from some source content (e.g., indexing children documents that were derived from parent documents by chunking.)
Classes¶
Wrapper around a vectorstore for easy access. |
|
Logic for creating indexes. |
langchain.memory
¶
Memory maintains Chain state, incorporating context from past runs.
Class hierarchy for Memory:
BaseMemory --> BaseChatMemory --> <name>Memory # Examples: ZepMemory, MotorheadMemory
Main helpers:
BaseChatMessageHistory
Chat Message History stores the chat message history in different stores.
Class hierarchy for ChatMessageHistory:
BaseChatMessageHistory --> <name>ChatMessageHistory # Example: ZepChatMessageHistory
Main helpers:
AIMessage, BaseMessage, HumanMessage
Classes¶
Buffer for storing conversation memory. |
|
Buffer for storing conversation memory. |
|
Buffer for storing conversation memory inside a limited size window. |
|
Abstract base class for chat memory. |
|
Combining multiple memories' data together. |
|
Abstract base class for Entity store. |
|
Entity extractor & summarizer memory. |
|
In-memory Entity store. |
|
Redis-backed Entity store. |
|
SQLite-backed Entity store |
|
Upstash Redis backed Entity store. |
|
Memory wrapper that is read-only and cannot be changed. |
|
Simple memory for storing context or other information that shouldn't ever change between prompts. |
|
Conversation summarizer to chat memory. |
|
Buffer with summarizer for storing conversation memory. |
|
Conversation chat memory with token limit. |
|
VectorStoreRetriever-backed memory. |
|
|
Conversation chat memory with token limit and vectordb backing. |
Functions¶
|
Get the prompt input key. |
Deprecated classes¶
Deprecated since version 0.2.12: Refer here for how to incorporate summaries of conversation history: https://langchain-ai.github.io/langgraph/how-tos/memory/add-summary-conversation-history/ |
langchain.model_laboratory
¶
Experiment with different models.
Classes¶
|
Experiment with different models. |
langchain.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¶
Parse the output of an LLM call to a boolean. |
|
Combine multiple output parsers into one. |
|
Parse the output of an LLM call to a datetime. |
|
Parse an output that is one of a set of values. |
|
Wrap a parser and try to fix parsing errors. |
|
Parse an output using Pandas DataFrame format. |
|
Parse the output of an LLM call using a regex. |
|
Parse the output of an LLM call into a Dictionary using a regex. |
|
Wrap a parser and try to fix parsing errors. |
|
Wrap a parser and try to fix parsing errors. |
|
|
|
Schema for a response from a structured output parser. |
|
Parse the output of an LLM call to a structured output. |
|
Parse YAML output using a pydantic model. |
Functions¶
Load an output parser. |
langchain.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:
Document, Serializable, Callbacks,
CallbackManagerForRetrieverRun, AsyncCallbackManagerForRetrieverRun
Classes¶
|
Retriever that wraps a base retriever and compresses the results. |
|
Document compressor that uses a pipeline of Transformers. |
|
Document compressor that uses an LLM chain to extract the relevant parts of documents. |
|
Parse outputs that could return a null string of some sort. |
Filter that drops documents that aren't relevant to the query. |
|
|
Interface for cross encoder models. |
|
Document compressor that uses CrossEncoder for reranking. |
|
Document compressor that uses embeddings to drop documents unrelated to the query. |
|
Document compressor that uses Zero-Shot Listwise Document Reranking. |
Retriever that ensembles the multiple retrievers. |
|
Retriever that merges the results of multiple retrievers. |
|
Output parser for a list of lines. |
|
Given a query, use an LLM to write a set of queries. |
|
Retrieve from a set of multiple embeddings for the same document. |
|
Enumerator of the types of search to perform. |
|
|
Retrieve small chunks then retrieve their parent documents. |
Given a query, use an LLM to re-phrase it. |
|
Retriever that uses a vector store and an LLM to generate the vector store queries. |
|
|
Retriever that combines embedding similarity with recency in retrieving values. |
Functions¶
|
Return the compression chain input. |
|
Return the compression chain input. |
|
Yield unique elements of an iterable based on a key function. |
Deprecated classes¶
Deprecated since version 0.0.30: Use |
langchain.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 the 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 non-core Runnable classes.
Classes¶
An instance of a runnable stored in the LangChain Hub. |
|
A function description for ChatOpenAI |
|
A runnable that routes to the selected function. |
langchain.smith
¶
LangSmith utilities.
This module provides utilities for connecting to LangSmith. For more information on LangSmith, see the LangSmith documentation.
Evaluation
LangSmith helps you evaluate Chains and other language model application components using a number of LangChain evaluators.
An example of this is shown below, assuming you’ve created a LangSmith dataset called <my_dataset_name>
:
from langsmith import Client
from langchain_community.chat_models import ChatOpenAI
from langchain.chains import LLMChain
from langchain.smith import RunEvalConfig, run_on_dataset
# Chains may have memory. Passing in a constructor function lets the
# evaluation framework avoid cross-contamination between runs.
def construct_chain():
llm = ChatOpenAI(temperature=0)
chain = LLMChain.from_string(
llm,
"What's the answer to {your_input_key}"
)
return chain
# Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)
evaluation_config = RunEvalConfig(
evaluators=[
"qa", # "Correctness" against a reference answer
"embedding_distance",
RunEvalConfig.Criteria("helpfulness"),
RunEvalConfig.Criteria({
"fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
}),
]
)
client = Client()
run_on_dataset(
client,
"<my_dataset_name>",
construct_chain,
evaluation=evaluation_config,
)
You can also create custom evaluators by subclassing the
StringEvaluator
or LangSmith’s RunEvaluator classes.
from typing import Optional
from langchain.evaluation import StringEvaluator
class MyStringEvaluator(StringEvaluator):
@property
def requires_input(self) -> bool:
return False
@property
def requires_reference(self) -> bool:
return True
@property
def evaluation_name(self) -> str:
return "exact_match"
def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:
return {"score": prediction == reference}
evaluation_config = RunEvalConfig(
custom_evaluators = [MyStringEvaluator()],
)
run_on_dataset(
client,
"<my_dataset_name>",
construct_chain,
evaluation=evaluation_config,
)
Primary Functions
arun_on_dataset
: Asynchronous function to evaluate a chain, agent, or other LangChain component over a dataset.run_on_dataset
: Function to evaluate a chain, agent, or other LangChain component over a dataset.RunEvalConfig
: Class representing the configuration for running evaluation. You can select evaluators byEvaluatorType
or config, or you can pass in custom_evaluators
Classes¶
Configuration for a given run evaluator. |
|
Configuration for a run evaluation. |
|
Configuration for a run evaluator that only requires a single key. |
|
A simple progress bar for the console. |
|
Input for a chat model. |
|
Your architecture raised an error. |
|
Raised when the input format is invalid. |
|
A dictionary of the results of a single test run. |
|
Extract items to evaluate from the run object from a chain. |
|
Extract items to evaluate from the run object. |
|
Map an example, or row in the dataset, to the inputs of an evaluation. |
|
|
Evaluate Run and optional examples. |
Extract items to evaluate from the run object. |
|
Map an input to the tool. |
Functions¶
Generate a random name. |
|
Run the Chain or language model on a dataset and store traces to the specified project name. |
|
Run the Chain or language model on a dataset and store traces to the specified project name. |
langchain.storage
¶
Implementations of 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¶
Wraps a store with key and value encoders/decoders. |
|
|
BaseStore interface that works on the local file system. |