Chat message history that stores history in Cassandra.
memory.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory(...)
Chat message history backed by Azure CosmosDB.
memory.chat_message_histories.dynamodb.DynamoDBChatMessageHistory(...)
Chat message history that stores history in AWS DynamoDB.
memory.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory(...)
Chat message history that stores history in Elasticsearch.
memory.chat_message_histories.file.FileChatMessageHistory(...)
Chat message history that stores history in a local file.
memory.chat_message_histories.firestore.FirestoreChatMessageHistory(...)
Chat message history backed by Google Firestore.
memory.chat_message_histories.in_memory.ChatMessageHistory
In memory implementation of chat message history.
memory.chat_message_histories.momento.MomentoChatMessageHistory(...)
Chat message history cache that uses Momento as a backend.
memory.chat_message_histories.mongodb.MongoDBChatMessageHistory(...)
Chat message history that stores history in MongoDB.
memory.chat_message_histories.neo4j.Neo4jChatMessageHistory(...)
Chat message history stored in a Neo4j database.
memory.chat_message_histories.postgres.PostgresChatMessageHistory(...)
Chat message history stored in a Postgres database.
memory.chat_message_histories.redis.RedisChatMessageHistory(...)
Chat message history stored in a Redis database.
memory.chat_message_histories.rocksetdb.RocksetChatMessageHistory(...)
Uses Rockset to store chat messages.
memory.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory(...)
Chat message history stored in a SingleStoreDB database.
memory.chat_message_histories.sql.BaseMessageConverter()
The class responsible for converting BaseMessage to your SQLAlchemy model.
memory.chat_message_histories.sql.DefaultMessageConverter(...)
The default message converter for SQLChatMessageHistory.
memory.chat_message_histories.sql.SQLChatMessageHistory(...)


memory.chat_message_histories.sql.SQLChatMessageHistory(...)
Chat message history stored in an SQL database.
memory.chat_message_histories.streamlit.StreamlitChatMessageHistory([key])
Chat message history that stores messages in Streamlit session state.
memory.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory(...)
Chat message history stored in an Upstash Redis database.
memory.chat_message_histories.xata.XataChatMessageHistory(...)
Chat message history stored in a Xata database.
memory.chat_message_histories.zep.ZepChatMessageHistory(...)
Chat message history that uses Zep as a backend.
memory.combined.CombinedMemory
Combining multiple memories' data together.
memory.entity.BaseEntityStore
Abstract base class for Entity store.
memory.entity.ConversationEntityMemory
Entity extractor & summarizer memory.
memory.entity.InMemoryEntityStore
In-memory Entity store.
memory.entity.RedisEntityStore
Redis-backed Entity store.
memory.entity.SQLiteEntityStore
SQLite-backed Entity store
memory.entity.UpstashRedisEntityStore
Upstash Redis backed Entity store.
memory.kg.ConversationKGMemory
Knowledge graph conversation memory.
memory.motorhead_memory.MotorheadMemory
Chat message memory backed by Motorhead service.
memory.readonly.ReadOnlySharedMemory
A memory wrapper that is read-only and cannot be changed.
memory.simple.SimpleMemory
Simple memory for storing context or other information that shouldn't ever change between prompts.
memory.summary.ConversationSummaryMemory
Conversation summarizer to chat memory.
memory.summary.SummarizerMixin
Mixin for summarizer.
memory.summary_buffer.ConversationSummaryBufferMemory
Buffer with summarizer for storing conversation memory.
memory.token_buffer.ConversationTokenBufferMemory
Conversation chat memory with token limit.
memory.vectorstore.VectorStoreRetrieverMemory
VectorStoreRetriever-backed memory.
memory.zep_memory.ZepMemory


VectorStoreRetriever-backed memory.
memory.zep_memory.ZepMemory
Persist your chain history to the Zep MemoryStore.
Functions¶
memory.chat_message_histories.sql.create_message_model(...)
Create a message model for a given table name.
memory.utils.get_prompt_input_key(inputs, ...)
Get the prompt input key.
langchain.model_laboratory¶
Experiment with different models.
Classes¶
model_laboratory.ModelLaboratory(chains[, names])
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¶
output_parsers.boolean.BooleanOutputParser
Parse the output of an LLM call to a boolean.
output_parsers.combining.CombiningOutputParser
Combine multiple output parsers into one.
output_parsers.datetime.DatetimeOutputParser
Parse the output of an LLM call to a datetime.
output_parsers.enum.EnumOutputParser
Parse an output that is one of a set of values.
output_parsers.fix.OutputFixingParser
Wraps a parser and tries to fix parsing errors.
output_parsers.json.SimpleJsonOutputParser
Parse the output of an LLM call to a JSON object.
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 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.rail_parser.GuardrailsOutputParser
Parse the output of an LLM call using Guardrails.
output_parsers.regex.RegexParser
Parse the output of an LLM call using a regex.
output_parsers.regex_dict.RegexDictParser
Parse the output of an LLM call into a Dictionary using a regex.
output_parsers.retry.RetryOutputParser
Wraps a parser and tries to fix parsing errors.
output_parsers.retry.RetryWithErrorOutputParser
Wraps a parser and tries to fix parsing errors.
output_parsers.structured.ResponseSchema
A schema for a response from a structured output parser.
output_parsers.structured.StructuredOutputParser
Parse the output of an LLM call to a structured output.
output_parsers.xml.XMLOutputParser
Parse an output using xml format.
Functions¶
output_parsers.json.parse_and_check_json_markdown(...)


Functions¶
output_parsers.json.parse_and_check_json_markdown(...)
Parse a JSON string from a Markdown string and check that it contains the expected keys.
output_parsers.json.parse_json_markdown(...)
Parse a JSON string from a Markdown string.
output_parsers.json.parse_partial_json(s, *)
Parse a JSON string that may be missing closing braces.
output_parsers.loading.load_output_parser(config)
Load an output parser.
langchain.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
PromptValue --> StringPromptValue
                ChatPromptValue
Classes¶
prompts.base.StringPromptTemplate
String prompt that exposes the format method, returning a prompt.
prompts.base.StringPromptValue
String prompt value.
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.ChatPromptValue
Chat prompt value.
prompts.chat.ChatPromptValueConcrete


prompts.chat.ChatPromptValue
Chat prompt value.
prompts.chat.ChatPromptValueConcrete
Chat prompt value which explicitly lists out the message types it accepts.
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.example_selector.base.BaseExampleSelector()
Interface for selecting examples to include in prompts.
prompts.example_selector.length_based.LengthBasedExampleSelector
Select examples based on length.
prompts.example_selector.ngram_overlap.NGramOverlapExampleSelector
Select and order examples based on ngram overlap score (sentence_bleu score).
prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector
ExampleSelector that selects examples based on Max Marginal Relevance.
prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector
Example selector that selects examples based on SemanticSimilarity.
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.Prompt
alias of PromptTemplate
prompts.prompt.PromptTemplate
A prompt template for a language model.
Functions¶
prompts.base.check_valid_template(template, ...)
Check that template string is valid.
prompts.base.get_template_variables(...)
Get the variables from the template.
prompts.base.jinja2_formatter(template, **kwargs)
Format a template using jinja2.
prompts.base.validate_jinja2(template, ...)
Validate that the input variables are valid for the template.


Validate that the input variables are valid for the template.
prompts.example_selector.ngram_overlap.ngram_overlap_score(...)
Compute ngram overlap score of source and example as sentence_bleu score.
prompts.example_selector.semantic_similarity.sorted_values(values)
Return a list of values in dict sorted by key.
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.
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¶
retrievers.arcee.ArceeRetriever
Document retriever for Arcee's Domain Adapted Language Models (DALMs).
retrievers.arxiv.ArxivRetriever
Arxiv retriever.
retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever
Azure Cognitive Search service retriever.
retrievers.bm25.BM25Retriever
BM25 retriever without Elasticsearch.
retrievers.chaindesk.ChaindeskRetriever
Chaindesk API retriever.
retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever
ChatGPT plugin retriever.
retrievers.cohere_rag_retriever.CohereRagRetriever


retrievers.cohere_rag_retriever.CohereRagRetriever
Cohere Chat API with RAG.
retrievers.contextual_compression.ContextualCompressionRetriever
Retriever that wraps a base retriever and compresses the results.
retrievers.databerry.DataberryRetriever
Databerry API retriever.
retrievers.docarray.DocArrayRetriever
DocArray Document Indices retriever.
retrievers.docarray.SearchType(value[, ...])
Enumerator of the types of search to perform.
retrievers.document_compressors.base.BaseDocumentCompressor
Base class for document compressors.
retrievers.document_compressors.base.DocumentCompressorPipeline
Document compressor that uses a pipeline of Transformers.
retrievers.document_compressors.chain_extract.LLMChainExtractor
Document compressor that uses an LLM chain to extract the relevant parts of documents.
retrievers.document_compressors.chain_extract.NoOutputParser
Parse outputs that could return a null string of some sort.
retrievers.document_compressors.chain_filter.LLMChainFilter
Filter that drops documents that aren't relevant to the query.
retrievers.document_compressors.cohere_rerank.CohereRerank
Document compressor that uses Cohere Rerank API.
retrievers.document_compressors.embeddings_filter.EmbeddingsFilter
Document compressor that uses embeddings to drop documents unrelated to the query.
retrievers.elastic_search_bm25.ElasticSearchBM25Retriever
Elasticsearch retriever that uses BM25.
retrievers.ensemble.EnsembleRetriever
Retriever that ensembles the multiple retrievers.
retrievers.google_cloud_documentai_warehouse.GoogleDocumentAIWarehouseRetriever
A retriever based on Document AI Warehouse.
retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever


retrievers.google_vertex_ai_search.GoogleCloudEnterpriseSearchRetriever
Google Vertex Search API retriever alias for backwards compatibility.
retrievers.google_vertex_ai_search.GoogleVertexAIMultiTurnSearchRetriever
Google Vertex AI Search retriever for multi-turn conversations.
retrievers.google_vertex_ai_search.GoogleVertexAISearchRetriever
Google Vertex AI Search retriever.
retrievers.kay.KayAiRetriever
Retriever for Kay.ai datasets.
retrievers.kendra.AdditionalResultAttribute
Additional result attribute.
retrievers.kendra.AdditionalResultAttributeValue
Value of an additional result attribute.
retrievers.kendra.AmazonKendraRetriever
Amazon Kendra Index retriever.
retrievers.kendra.DocumentAttribute
Document attribute.
retrievers.kendra.DocumentAttributeValue
Value of a document attribute.
retrievers.kendra.Highlight
Information that highlights the keywords in the excerpt.
retrievers.kendra.QueryResult
Amazon Kendra Query API search result.
retrievers.kendra.QueryResultItem
Query API result item.
retrievers.kendra.ResultItem
Base class of a result item.
retrievers.kendra.RetrieveResult
Amazon Kendra Retrieve API search result.
retrievers.kendra.RetrieveResultItem
Retrieve API result item.
retrievers.kendra.TextWithHighLights
Text with highlights.
retrievers.knn.KNNRetriever
KNN retriever.
retrievers.llama_index.LlamaIndexGraphRetriever
LlamaIndex graph data structure retriever.
retrievers.llama_index.LlamaIndexRetriever
LlamaIndex retriever.
retrievers.merger_retriever.MergerRetriever
Retriever that merges the results of multiple retrievers.
retrievers.metal.MetalRetriever


retrievers.metal.MetalRetriever
Metal API retriever.
retrievers.milvus.MilvusRetriever
Milvus API retriever.
retrievers.multi_query.LineList
List of lines.
retrievers.multi_query.LineListOutputParser
Output parser for a list of lines.
retrievers.multi_query.MultiQueryRetriever
Given a query, use an LLM to write a set of queries.
retrievers.multi_vector.MultiVectorRetriever
Retrieve from a set of multiple embeddings for the same document.
retrievers.parent_document_retriever.ParentDocumentRetriever
Retrieve small chunks then retrieve their parent documents.
retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever
Pinecone Hybrid Search retriever.
retrievers.pubmed.PubMedRetriever
PubMed API retriever.
retrievers.re_phraser.RePhraseQueryRetriever
Given a query, use an LLM to re-phrase it.
retrievers.remote_retriever.RemoteLangChainRetriever
LangChain API retriever.
retrievers.self_query.base.SelfQueryRetriever
Retriever that uses a vector store and an LLM to generate the vector store queries.
retrievers.self_query.chroma.ChromaTranslator()
Translate Chroma internal query language elements to valid filters.
retrievers.self_query.dashvector.DashvectorTranslator()
Logic for converting internal query language elements to valid filters.
retrievers.self_query.deeplake.DeepLakeTranslator()
Translate DeepLake internal query language elements to valid filters.
retrievers.self_query.elasticsearch.ElasticsearchTranslator()
Translate Elasticsearch internal query language elements to valid filters.
retrievers.self_query.milvus.MilvusTranslator()


retrievers.self_query.milvus.MilvusTranslator()
Translate Milvus internal query language elements to valid filters.
retrievers.self_query.myscale.MyScaleTranslator([...])
Translate MyScale internal query language elements to valid filters.
retrievers.self_query.opensearch.OpenSearchTranslator()
Translate OpenSearch internal query domain-specific language elements to valid filters.
retrievers.self_query.pinecone.PineconeTranslator()
Translate Pinecone internal query language elements to valid filters.
retrievers.self_query.qdrant.QdrantTranslator(...)
Translate Qdrant internal query language elements to valid filters.
retrievers.self_query.redis.RedisTranslator(schema)
Translate
retrievers.self_query.supabase.SupabaseVectorTranslator()
Translate Langchain filters to Supabase PostgREST filters.
retrievers.self_query.timescalevector.TimescaleVectorTranslator()
Translate the internal query language elements to valid filters.
retrievers.self_query.vectara.VectaraTranslator()
Translate Vectara internal query language elements to valid filters.
retrievers.self_query.weaviate.WeaviateTranslator()
Translate Weaviate internal query language elements to valid filters.
retrievers.svm.SVMRetriever
SVM retriever.
retrievers.tavily_search_api.SearchDepth(value)
Search depth as enumerator.
retrievers.tavily_search_api.TavilySearchAPIRetriever
Tavily Search API retriever.
retrievers.tfidf.TFIDFRetriever
TF-IDF retriever.
retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever
Retriever that combines embedding similarity with recency in retrieving values.
retrievers.vespa_retriever.VespaRetriever
Vespa retriever.


Vespa retriever.
retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever
Weaviate hybrid search retriever.
retrievers.web_research.LineList
List of questions.
retrievers.web_research.QuestionListOutputParser
Output parser for a list of numbered questions.
retrievers.web_research.SearchQueries
Search queries to research for the user's goal.
retrievers.web_research.WebResearchRetriever
Google Search API retriever.
retrievers.wikipedia.WikipediaRetriever
Wikipedia API retriever.
retrievers.you.YouRetriever
You retriever that uses You.com's search API.
retrievers.zep.SearchScope(value[, names, ...])
Which documents to search.
retrievers.zep.SearchType(value[, names, ...])
Enumerator of the types of search to perform.
retrievers.zep.ZepRetriever
Zep MemoryStore Retriever.
retrievers.zilliz.ZillizRetriever
Zilliz API retriever.
Functions¶
retrievers.bm25.default_preprocessing_func(text)
retrievers.document_compressors.chain_extract.default_get_input(...)
Return the compression chain input.
retrievers.document_compressors.chain_filter.default_get_input(...)
Return the compression chain input.
retrievers.kendra.clean_excerpt(excerpt)
Clean an excerpt from Kendra.
retrievers.kendra.combined_text(item)
Combine a ResultItem title and excerpt into a single string.
retrievers.knn.create_index(contexts, embeddings)
Create an index of embeddings for a list of contexts.
retrievers.milvus.MilvusRetreiver(*args, ...)
Deprecated MilvusRetreiver.


Deprecated MilvusRetreiver.
retrievers.pinecone_hybrid_search.create_index(...)
Create an index from a list of contexts.
retrievers.pinecone_hybrid_search.hash_text(text)
Hash a text using SHA256.
retrievers.self_query.deeplake.can_cast_to_float(string)
Check if a string can be cast to a float.
retrievers.self_query.milvus.process_value(value)
Convert a value to a string and add double quotes if it is a string.
retrievers.self_query.vectara.process_value(value)
Convert a value to a string and add single quotes if it is a string.
retrievers.svm.create_index(contexts, embeddings)
Create an index of embeddings for a list of contexts.
retrievers.zilliz.ZillizRetreiver(*args, ...)
Deprecated ZillizRetreiver.
langchain.runnables¶
Classes¶
runnables.hub.HubRunnable
An instance of a runnable stored in the LangChain Hub.
runnables.openai_functions.OpenAIFunction
A function description for ChatOpenAI
runnables.openai_functions.OpenAIFunctionsRouter
A runnable that routes to the selected function.
langchain.schema¶
Schemas are the LangChain Base Classes and Interfaces.
Classes¶
schema.agent.AgentAction
A full description of an action for an ActionAgent to execute.
schema.agent.AgentActionMessageLog
Override init to support instantiation by position for backward compat.
schema.agent.AgentFinish
The final return value of an ActionAgent.
schema.cache.BaseCache()
Base interface for cache.
schema.callbacks.base.AsyncCallbackHandler()
Async callback handler that handles callbacks from LangChain.
schema.callbacks.base.BaseCallbackHandler()
Base callback handler that handles callbacks from LangChain.


schema.callbacks.base.BaseCallbackHandler()
Base callback handler that handles callbacks from LangChain.
schema.callbacks.base.BaseCallbackManager(...)
Base callback manager that handles callbacks from LangChain.
schema.callbacks.base.CallbackManagerMixin()
Mixin for callback manager.
schema.callbacks.base.ChainManagerMixin()
Mixin for chain callbacks.
schema.callbacks.base.LLMManagerMixin()
Mixin for LLM callbacks.
schema.callbacks.base.RetrieverManagerMixin()
Mixin for Retriever callbacks.
schema.callbacks.base.RunManagerMixin()
Mixin for run manager.
schema.callbacks.base.ToolManagerMixin()
Mixin for tool callbacks.
schema.callbacks.manager.AsyncCallbackManager(...)
Async callback manager that handles callbacks from LangChain.
schema.callbacks.manager.AsyncCallbackManagerForChainGroup(...)
Async callback manager for the chain group.
schema.callbacks.manager.AsyncCallbackManagerForChainRun(*, ...)
Async callback manager for chain run.
schema.callbacks.manager.AsyncCallbackManagerForLLMRun(*, ...)
Async callback manager for LLM run.
schema.callbacks.manager.AsyncCallbackManagerForRetrieverRun(*, ...)
Async callback manager for retriever run.
schema.callbacks.manager.AsyncCallbackManagerForToolRun(*, ...)
Async callback manager for tool run.
schema.callbacks.manager.AsyncParentRunManager(*, ...)
Async Parent Run Manager.
schema.callbacks.manager.AsyncRunManager(*, ...)
Async Run Manager.
schema.callbacks.manager.BaseRunManager(*, ...)
Base class for run manager (a bound callback manager).
schema.callbacks.manager.CallbackManager(...)
Callback manager that handles callbacks from LangChain.
schema.callbacks.manager.CallbackManagerForChainGroup(...)
Callback manager for the chain group.
schema.callbacks.manager.CallbackManagerForChainRun(*, ...)
Callback manager for chain run.
schema.callbacks.manager.CallbackManagerForLLMRun(*, ...)
Callback manager for LLM run.


Callback manager for LLM run.
schema.callbacks.manager.CallbackManagerForRetrieverRun(*, ...)
Callback manager for retriever run.
schema.callbacks.manager.CallbackManagerForToolRun(*, ...)
Callback manager for tool run.
schema.callbacks.manager.ParentRunManager(*, ...)
Sync Parent Run Manager.
schema.callbacks.manager.RunManager(*, ...)
Sync Run Manager.
schema.callbacks.stdout.StdOutCallbackHandler([color])
Callback Handler that prints to std out.
schema.callbacks.tracers.base.BaseTracer(...)
Base interface for tracers.
schema.callbacks.tracers.base.TracerException
Base class for exceptions in tracers module.
schema.callbacks.tracers.evaluation.EvaluatorCallbackHandler(...)
A tracer that runs a run evaluator whenever a run is persisted.
schema.callbacks.tracers.langchain.LangChainTracer([...])
An implementation of the SharedTracer that POSTS to the langchain endpoint.
schema.callbacks.tracers.langchain_v1.LangChainTracerV1(...)
An implementation of the SharedTracer that POSTS to the langchain endpoint.
schema.callbacks.tracers.log_stream.LogEntry
A single entry in the run log.
schema.callbacks.tracers.log_stream.LogStreamCallbackHandler(*)
A tracer that streams run logs to a stream.
schema.callbacks.tracers.log_stream.RunLog(...)
A run log.
schema.callbacks.tracers.log_stream.RunLogPatch(*ops)
A patch to the run log.
schema.callbacks.tracers.log_stream.RunState
State of the run.
schema.callbacks.tracers.root_listeners.RootListenersTracer(*, ...)
schema.callbacks.tracers.run_collector.RunCollectorCallbackHandler([...])
A tracer that collects all nested runs in a list.
schema.callbacks.tracers.schemas.BaseRun
Base class for Run.
schema.callbacks.tracers.schemas.ChainRun
Class for ChainRun.


schema.callbacks.tracers.schemas.ChainRun
Class for ChainRun.
schema.callbacks.tracers.schemas.LLMRun
Class for LLMRun.
schema.callbacks.tracers.schemas.Run
Run schema for the V2 API in the Tracer.
schema.callbacks.tracers.schemas.ToolRun
Class for ToolRun.
schema.callbacks.tracers.schemas.TracerSession
TracerSessionV1 schema for the V2 API.
schema.callbacks.tracers.schemas.TracerSessionBase
Base class for TracerSession.
schema.callbacks.tracers.schemas.TracerSessionV1
TracerSessionV1 schema.
schema.callbacks.tracers.schemas.TracerSessionV1Base
Base class for TracerSessionV1.
schema.callbacks.tracers.schemas.TracerSessionV1Create
Create class for TracerSessionV1.
schema.callbacks.tracers.stdout.ConsoleCallbackHandler(...)
Tracer that prints to the console.
schema.callbacks.tracers.stdout.FunctionCallbackHandler(...)
Tracer that calls a function with a single str parameter.
schema.chat.ChatSession
Chat Session represents a single conversation, channel, or other group of messages.
schema.chat_history.BaseChatMessageHistory()
Abstract base class for storing chat message history.
schema.document.BaseDocumentTransformer()
Abstract base class for document transformation systems.
schema.document.Document
Class for storing a piece of text and associated metadata.
schema.embeddings.Embeddings()
Interface for embedding models.
schema.exceptions.LangChainException
General LangChain exception.
schema.language_model.BaseLanguageModel
Abstract base class for interfacing with language models.
schema.memory.BaseMemory
Abstract base class for memory in Chains.
schema.messages.AIMessage
A Message from an AI.
schema.messages.AIMessageChunk
A Message chunk from an AI.
schema.messages.BaseMessage
The base abstract Message class.
schema.messages.BaseMessageChunk


schema.messages.BaseMessage
The base abstract Message class.
schema.messages.BaseMessageChunk
A Message chunk, which can be concatenated with other Message chunks.
schema.messages.ChatMessage
A Message that can be assigned an arbitrary speaker (i.e.
schema.messages.ChatMessageChunk
A Chat Message chunk.
schema.messages.FunctionMessage
A Message for passing the result of executing a function back to a model.
schema.messages.FunctionMessageChunk
A Function Message chunk.
schema.messages.HumanMessage
A Message from a human.
schema.messages.HumanMessageChunk
A Human Message chunk.
schema.messages.SystemMessage
A Message for priming AI behavior, usually passed in as the first of a sequence of input messages.
schema.messages.SystemMessageChunk
A System Message chunk.
schema.messages.ToolMessage
A Message for passing the result of executing a tool back to a model.
schema.messages.ToolMessageChunk
A Tool Message chunk.
schema.output.ChatGeneration
A single chat generation output.
schema.output.ChatGenerationChunk
A ChatGeneration chunk, which can be concatenated with other
schema.output.ChatResult
Class that contains all results for a single chat model call.
schema.output.Generation
A single text generation output.
schema.output.GenerationChunk
A Generation chunk, which can be concatenated with other Generation chunks.
schema.output.LLMResult
Class that contains all results for a batched LLM call.
schema.output.RunInfo
Class that contains metadata for a single execution of a Chain or model.
schema.output_parser.BaseCumulativeTransformOutputParser
Base class for an output parser that can handle streaming input.
schema.output_parser.BaseGenerationOutputParser
Base class to parse the output of an LLM call.
schema.output_parser.BaseLLMOutputParser()
Abstract base class for parsing the outputs of a model.
schema.output_parser.BaseOutputParser
Base class to parse the output of an LLM call.


schema.output_parser.BaseOutputParser
Base class to parse the output of an LLM call.
schema.output_parser.BaseTransformOutputParser
Base class for an output parser that can handle streaming input.
schema.output_parser.NoOpOutputParser
alias of StrOutputParser
schema.output_parser.OutputParserException(error)
Exception that output parsers should raise to signify a parsing error.
schema.output_parser.StrOutputParser
OutputParser that parses LLMResult into the top likely string.
schema.prompt.PromptValue
Base abstract class for inputs to any language model.
schema.prompt_template.BasePromptTemplate
Base class for all prompt templates, returning a prompt.
schema.retriever.BaseRetriever
Abstract base class for a Document retrieval system.
schema.runnable.base.Runnable()
A unit of work that can be invoked, batched, streamed, transformed and composed.
schema.runnable.base.RunnableBinding
A runnable that delegates calls to another runnable with a set of kwargs.
schema.runnable.base.RunnableBindingBase
A runnable that delegates calls to another runnable with a set of kwargs.
schema.runnable.base.RunnableEach
A runnable that delegates calls to another runnable with each element of the input sequence.
schema.runnable.base.RunnableEachBase
A runnable that delegates calls to another runnable with each element of the input sequence.
schema.runnable.base.RunnableGenerator(transform)
A runnable that runs a generator function.
schema.runnable.base.RunnableLambda(func[, ...])
RunnableLambda converts a python callable into a Runnable.
schema.runnable.base.RunnableMap
alias of RunnableParallel
schema.runnable.base.RunnableParallel
A runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.
schema.runnable.base.RunnableSequence
A sequence of runnables, where the output of each is the input of the next.
schema.runnable.base.RunnableSerializable


schema.runnable.base.RunnableSerializable
A Runnable that can be serialized to JSON.
schema.runnable.branch.RunnableBranch
A Runnable that selects which branch to run based on a condition.
schema.runnable.config.EmptyDict
Empty dict type.
schema.runnable.config.RunnableConfig
Configuration for a Runnable.
schema.runnable.configurable.DynamicRunnable
A Serializable Runnable that can be dynamically configured.
schema.runnable.configurable.RunnableConfigurableAlternatives
A Runnable that can be dynamically configured.
schema.runnable.configurable.RunnableConfigurableFields
A Runnable that can be dynamically configured.
schema.runnable.configurable.StrEnum(value)
A string enum.
schema.runnable.fallbacks.RunnableWithFallbacks
A Runnable that can fallback to other Runnables if it fails.
schema.runnable.history.RunnableWithMessageHistory
A runnable that manages chat message history for another runnable.
schema.runnable.passthrough.RunnableAssign
A runnable that assigns key-value pairs to Dict[str, Any] inputs.
schema.runnable.passthrough.RunnablePassthrough
A runnable to passthrough inputs unchanged or with additional keys.
schema.runnable.retry.RunnableRetry
Retry a Runnable if it fails.
schema.runnable.router.RouterInput
A Router input.
schema.runnable.router.RouterRunnable
A runnable that routes to a set of runnables based on Input['key'].
schema.runnable.utils.AddableDict
Dictionary that can be added to another dictionary.
schema.runnable.utils.ConfigurableField(id)
A field that can be configured by the user.
schema.runnable.utils.ConfigurableFieldMultiOption(id, ...)
A field that can be configured by the user with multiple default values.
schema.runnable.utils.ConfigurableFieldSingleOption(id, ...)
A field that can be configured by the user with a default value.


A field that can be configured by the user with a default value.
schema.runnable.utils.ConfigurableFieldSpec(id, ...)
A field that can be configured by the user.
schema.runnable.utils.GetLambdaSource()
Get the source code of a lambda function.
schema.runnable.utils.IsFunctionArgDict()
Check if the first argument of a function is a dict.
schema.runnable.utils.IsLocalDict(name, keys)
Check if a name is a local dict.
schema.runnable.utils.SupportsAdd(*args, ...)
Protocol for objects that support addition.
schema.storage.BaseStore()
Abstract interface for a key-value store.
schema.vectorstore.VectorStore()
Interface for vector store.
schema.vectorstore.VectorStoreRetriever
Base Retriever class for VectorStore.
Functions¶
schema.callbacks.manager.ahandle_event(...)
Generic event handler for AsyncCallbackManager.
schema.callbacks.manager.atrace_as_chain_group(...)
Get an async callback manager for a chain group in a context manager.
schema.callbacks.manager.collect_runs()
Collect all run traces in context.
schema.callbacks.manager.env_var_is_set(env_var)
Check if an environment variable is set.
schema.callbacks.manager.handle_event(...)
Generic event handler for CallbackManager.
schema.callbacks.manager.register_configure_hook(...)
schema.callbacks.manager.trace_as_chain_group(...)
Get a callback manager for a chain group in a context manager.
schema.callbacks.manager.tracing_enabled([...])
Get the Deprecated LangChainTracer in a context manager.
schema.callbacks.manager.tracing_v2_enabled([...])
Instruct LangChain to log all runs in context to LangSmith.
schema.callbacks.tracers.evaluation.wait_for_all_evaluators()
Wait for all tracers to finish.
schema.callbacks.tracers.langchain.get_client()
Get the client.
schema.callbacks.tracers.langchain.log_error_once(...)


Get the client.
schema.callbacks.tracers.langchain.log_error_once(...)
Log an error once.
schema.callbacks.tracers.langchain.wait_for_all_tracers()
Wait for all tracers to finish.
schema.callbacks.tracers.langchain_v1.get_headers()
Get the headers for the LangChain API.
schema.callbacks.tracers.schemas.RunTypeEnum()
RunTypeEnum.
schema.callbacks.tracers.stdout.elapsed(run)
Get the elapsed time of a run.
schema.callbacks.tracers.stdout.try_json_stringify(...)
Try to stringify an object to JSON.
schema.messages.get_buffer_string(messages)
Convert sequence of Messages to strings and concatenate them into one string.
schema.messages.merge_content(first_content, ...)
schema.messages.messages_from_dict(messages)
Convert a sequence of messages from dicts to Message objects.
schema.messages.messages_to_dict(messages)
Convert a sequence of Messages to a list of dictionaries.
schema.prompt_template.format_document(doc, ...)
Format a document into a string based on a prompt template.
schema.runnable.base.coerce_to_runnable(thing)
Coerce a runnable-like object into a Runnable.
schema.runnable.config.acall_func_with_variable_args(...)
Call function that may optionally accept a run_manager and/or config.
schema.runnable.config.call_func_with_variable_args(...)
Call function that may optionally accept a run_manager and/or config.
schema.runnable.config.ensure_config([config])
Ensure that a config is a dict with all keys present.
schema.runnable.config.get_async_callback_manager_for_config(config)
Get an async callback manager for a config.
schema.runnable.config.get_callback_manager_for_config(config)
Get a callback manager for a config.
schema.runnable.config.get_config_list(...)
Get a list of configs from a single config or a list of configs.
schema.runnable.config.get_executor_for_config(config)
Get an executor for a config.


schema.runnable.config.get_executor_for_config(config)
Get an executor for a config.
schema.runnable.config.merge_configs(*configs)
Merge multiple configs into one.
schema.runnable.config.patch_config(config, *)
Patch a config with new values.
schema.runnable.configurable.make_options_spec(...)
Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.
schema.runnable.passthrough.aidentity(x)
An async identity function
schema.runnable.passthrough.identity(x)
An identity function
schema.runnable.utils.aadd(addables)
Asynchronously add a sequence of addable objects together.
schema.runnable.utils.accepts_config(callable)
Check if a callable accepts a config argument.
schema.runnable.utils.accepts_run_manager(...)
Check if a callable accepts a run_manager argument.
schema.runnable.utils.add(addables)
Add a sequence of addable objects together.
schema.runnable.utils.gated_coro(semaphore, coro)
Run a coroutine with a semaphore.
schema.runnable.utils.gather_with_concurrency(n, ...)
Gather coroutines with a limit on the number of concurrent coroutines.
schema.runnable.utils.get_function_first_arg_dict_keys(func)
Get the keys of the first argument of a function if it is a dict.
schema.runnable.utils.get_lambda_source(func)
Get the source code of a lambda function.
schema.runnable.utils.get_unique_config_specs(specs)
Get the unique config specs from a sequence of config specs.
schema.runnable.utils.indent_lines_after_first(...)
Indent all lines of text after the first line.
langchain.schema.runnable¶
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.


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¶
schema.runnable.base.Runnable()
A unit of work that can be invoked, batched, streamed, transformed and composed.
schema.runnable.base.RunnableBinding
A runnable that delegates calls to another runnable with a set of kwargs.
schema.runnable.base.RunnableBindingBase
A runnable that delegates calls to another runnable with a set of kwargs.
schema.runnable.base.RunnableEach
A runnable that delegates calls to another runnable with each element of the input sequence.
schema.runnable.base.RunnableEachBase
A runnable that delegates calls to another runnable with each element of the input sequence.
schema.runnable.base.RunnableGenerator(transform)
A runnable that runs a generator function.
schema.runnable.base.RunnableLambda(func[, ...])
RunnableLambda converts a python callable into a Runnable.
schema.runnable.base.RunnableMap
alias of RunnableParallel
schema.runnable.base.RunnableParallel
A runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.
schema.runnable.base.RunnableSequence
A sequence of runnables, where the output of each is the input of the next.
schema.runnable.base.RunnableSerializable
A Runnable that can be serialized to JSON.
schema.runnable.branch.RunnableBranch
A Runnable that selects which branch to run based on a condition.
schema.runnable.config.EmptyDict
Empty dict type.
schema.runnable.config.RunnableConfig


schema.runnable.config.EmptyDict
Empty dict type.
schema.runnable.config.RunnableConfig
Configuration for a Runnable.
schema.runnable.configurable.DynamicRunnable
A Serializable Runnable that can be dynamically configured.
schema.runnable.configurable.RunnableConfigurableAlternatives
A Runnable that can be dynamically configured.
schema.runnable.configurable.RunnableConfigurableFields
A Runnable that can be dynamically configured.
schema.runnable.configurable.StrEnum(value)
A string enum.
schema.runnable.fallbacks.RunnableWithFallbacks
A Runnable that can fallback to other Runnables if it fails.
schema.runnable.history.RunnableWithMessageHistory
A runnable that manages chat message history for another runnable.
schema.runnable.passthrough.RunnableAssign
A runnable that assigns key-value pairs to Dict[str, Any] inputs.
schema.runnable.passthrough.RunnablePassthrough
A runnable to passthrough inputs unchanged or with additional keys.
schema.runnable.retry.RunnableRetry
Retry a Runnable if it fails.
schema.runnable.router.RouterInput
A Router input.
schema.runnable.router.RouterRunnable
A runnable that routes to a set of runnables based on Input['key'].
schema.runnable.utils.AddableDict
Dictionary that can be added to another dictionary.
schema.runnable.utils.ConfigurableField(id)
A field that can be configured by the user.
schema.runnable.utils.ConfigurableFieldMultiOption(id, ...)
A field that can be configured by the user with multiple default values.
schema.runnable.utils.ConfigurableFieldSingleOption(id, ...)
A field that can be configured by the user with a default value.
schema.runnable.utils.ConfigurableFieldSpec(id, ...)
A field that can be configured by the user.
schema.runnable.utils.GetLambdaSource()
Get the source code of a lambda function.


schema.runnable.utils.GetLambdaSource()
Get the source code of a lambda function.
schema.runnable.utils.IsFunctionArgDict()
Check if the first argument of a function is a dict.
schema.runnable.utils.IsLocalDict(name, keys)
Check if a name is a local dict.
schema.runnable.utils.SupportsAdd(*args, ...)
Protocol for objects that support addition.
Functions¶
schema.runnable.base.coerce_to_runnable(thing)
Coerce a runnable-like object into a Runnable.
schema.runnable.config.acall_func_with_variable_args(...)
Call function that may optionally accept a run_manager and/or config.
schema.runnable.config.call_func_with_variable_args(...)
Call function that may optionally accept a run_manager and/or config.
schema.runnable.config.ensure_config([config])
Ensure that a config is a dict with all keys present.
schema.runnable.config.get_async_callback_manager_for_config(config)
Get an async callback manager for a config.
schema.runnable.config.get_callback_manager_for_config(config)
Get a callback manager for a config.
schema.runnable.config.get_config_list(...)
Get a list of configs from a single config or a list of configs.
schema.runnable.config.get_executor_for_config(config)
Get an executor for a config.
schema.runnable.config.merge_configs(*configs)
Merge multiple configs into one.
schema.runnable.config.patch_config(config, *)
Patch a config with new values.
schema.runnable.configurable.make_options_spec(...)
Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.
schema.runnable.passthrough.aidentity(x)
An async identity function
schema.runnable.passthrough.identity(x)
An identity function
schema.runnable.utils.aadd(addables)
Asynchronously add a sequence of addable objects together.


Asynchronously add a sequence of addable objects together.
schema.runnable.utils.accepts_config(callable)
Check if a callable accepts a config argument.
schema.runnable.utils.accepts_run_manager(...)
Check if a callable accepts a run_manager argument.
schema.runnable.utils.add(addables)
Add a sequence of addable objects together.
schema.runnable.utils.gated_coro(semaphore, coro)
Run a coroutine with a semaphore.
schema.runnable.utils.gather_with_concurrency(n, ...)
Gather coroutines with a limit on the number of concurrent coroutines.
schema.runnable.utils.get_function_first_arg_dict_keys(func)
Get the keys of the first argument of a function if it is a dict.
schema.runnable.utils.get_lambda_source(func)
Get the source code of a lambda function.
schema.runnable.utils.get_unique_config_specs(specs)
Get the unique config specs from a sequence of config specs.
schema.runnable.utils.indent_lines_after_first(...)
Indent all lines of text after the first line.
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.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(


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 by EvaluatorType or config, or you can pass in custom_evaluators
Classes¶
smith.evaluation.config.EvalConfig
Configuration for a given run evaluator.
smith.evaluation.config.RunEvalConfig
Configuration for a run evaluation.
smith.evaluation.config.SingleKeyEvalConfig
Create a new model by parsing and validating input data from keyword arguments.
smith.evaluation.progress.ProgressBarCallback(total)
A simple progress bar for the console.
smith.evaluation.runner_utils.InputFormatError
Raised when the input format is invalid.
smith.evaluation.runner_utils.TestResult
A dictionary of the results of a single test run.
smith.evaluation.string_run_evaluator.ChainStringRunMapper
Extract items to evaluate from the run object from a chain.
smith.evaluation.string_run_evaluator.LLMStringRunMapper
Extract items to evaluate from the run object.
smith.evaluation.string_run_evaluator.StringExampleMapper
Map an example, or row in the dataset, to the inputs of an evaluation.
smith.evaluation.string_run_evaluator.StringRunEvaluatorChain
Evaluate Run and optional examples.
smith.evaluation.string_run_evaluator.StringRunMapper
Extract items to evaluate from the run object.
smith.evaluation.string_run_evaluator.ToolStringRunMapper
Map an input to the tool.
Functions¶
smith.evaluation.name_generation.random_name([...])
Generate a random name.
smith.evaluation.runner_utils.arun_on_dataset(...)
Run the Chain or language model on a dataset and store traces to the specified project name.
smith.evaluation.runner_utils.run_on_dataset(...)
Run the Chain or language model on a dataset and store traces to the specified project name.
langchain.storage¶


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¶
storage.encoder_backed.EncoderBackedStore(...)
Wraps a store with key and value encoders/decoders.
storage.exceptions.InvalidKeyException
Raised when a key is invalid; e.g., uses incorrect characters.
storage.file_system.LocalFileStore(root_path)
BaseStore interface that works on the local file system.
storage.in_memory.InMemoryStore()
In-memory implementation of the BaseStore using a dictionary.
storage.redis.RedisStore(*[, client, ...])
BaseStore implementation using Redis as the underlying store.
storage.upstash_redis.UpstashRedisStore(*[, ...])
BaseStore implementation using Upstash Redis as the underlying store.
langchain.text_splitter¶
Text Splitters are classes for splitting text.
Class hierarchy:
BaseDocumentTransformer --> TextSplitter --> <name>TextSplitter  # Example: CharacterTextSplitter
                                             RecursiveCharacterTextSplitter -->  <name>TextSplitter
Note: MarkdownHeaderTextSplitter and **HTMLHeaderTextSplitter do not derive from TextSplitter.
Main helpers:
Document, Tokenizer, Language, LineType, HeaderType
Classes¶
text_splitter.CharacterTextSplitter([...])
Splitting text that looks at characters.
text_splitter.ElementType
Element type as typed dict.
text_splitter.HTMLHeaderTextSplitter(...[, ...])
Splitting HTML files based on specified headers.
text_splitter.HeaderType
Header type as typed dict.
text_splitter.Language(value[, names, ...])
Enum of the programming languages.
text_splitter.LatexTextSplitter(**kwargs)


Enum of the programming languages.
text_splitter.LatexTextSplitter(**kwargs)
Attempts to split the text along Latex-formatted layout elements.
text_splitter.LineType
Line type as typed dict.
text_splitter.MarkdownHeaderTextSplitter(...)
Splitting markdown files based on specified headers.
text_splitter.MarkdownTextSplitter(**kwargs)
Attempts to split the text along Markdown-formatted headings.
text_splitter.NLTKTextSplitter([separator, ...])
Splitting text using NLTK package.
text_splitter.PythonCodeTextSplitter(**kwargs)
Attempts to split the text along Python syntax.
text_splitter.RecursiveCharacterTextSplitter([...])
Splitting text by recursively look at characters.
text_splitter.SentenceTransformersTokenTextSplitter([...])
Splitting text to tokens using sentence model tokenizer.
text_splitter.SpacyTextSplitter([separator, ...])
Splitting text using Spacy package.
text_splitter.TextSplitter(chunk_size, ...)
Interface for splitting text into chunks.
text_splitter.TokenTextSplitter([...])
Splitting text to tokens using model tokenizer.
text_splitter.Tokenizer(chunk_overlap, ...)
Tokenizer data class.
Functions¶
text_splitter.split_text_on_tokens(*, text, ...)
Split incoming text and return chunks using tokenizer.
langchain.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:
ToolMetaclass --> BaseTool --> <name>Tool  # Examples: AIPluginTool, BaseGraphQLTool
                               <name>      # Examples: BraveSearch, HumanInputRun
Main helpers:
CallbackManagerForToolRun, AsyncCallbackManagerForToolRun
Classes¶


Main helpers:
CallbackManagerForToolRun, AsyncCallbackManagerForToolRun
Classes¶
tools.ainetwork.app.AINAppOps
Tool for app operations.
tools.ainetwork.app.AppOperationType(value)
Type of app operation as enumerator.
tools.ainetwork.app.AppSchema
Schema for app operations.
tools.ainetwork.base.AINBaseTool
Base class for the AINetwork tools.
tools.ainetwork.base.OperationType(value[, ...])
Type of operation as enumerator.
tools.ainetwork.owner.AINOwnerOps
Tool for owner operations.
tools.ainetwork.owner.RuleSchema
Schema for owner operations.
tools.ainetwork.rule.AINRuleOps
Tool for owner operations.
tools.ainetwork.rule.RuleSchema
Schema for owner operations.
tools.ainetwork.transfer.AINTransfer
Tool for transfer operations.
tools.ainetwork.transfer.TransferSchema
Schema for transfer operations.
tools.ainetwork.value.AINValueOps
Tool for value operations.
tools.ainetwork.value.ValueSchema
Schema for value operations.
tools.amadeus.base.AmadeusBaseTool
Base Tool for Amadeus.
tools.amadeus.closest_airport.AmadeusClosestAirport
Tool for finding the closest airport to a particular location.
tools.amadeus.closest_airport.ClosestAirportSchema
Schema for the AmadeusClosestAirport tool.
tools.amadeus.flight_search.AmadeusFlightSearch
Tool for searching for a single flight between two airports.
tools.amadeus.flight_search.FlightSearchSchema
Schema for the AmadeusFlightSearch tool.
tools.arxiv.tool.ArxivInput
Create a new model by parsing and validating input data from keyword arguments.
tools.arxiv.tool.ArxivQueryRun
Tool that searches the Arxiv API.


tools.arxiv.tool.ArxivQueryRun
Tool that searches the Arxiv API.
tools.azure_cognitive_services.form_recognizer.AzureCogsFormRecognizerTool
Tool that queries the Azure Cognitive Services Form Recognizer API.
tools.azure_cognitive_services.image_analysis.AzureCogsImageAnalysisTool
Tool that queries the Azure Cognitive Services Image Analysis API.
tools.azure_cognitive_services.speech2text.AzureCogsSpeech2TextTool
Tool that queries the Azure Cognitive Services Speech2Text API.
tools.azure_cognitive_services.text2speech.AzureCogsText2SpeechTool
Tool that queries the Azure Cognitive Services Text2Speech API.
tools.base.BaseTool
Interface LangChain tools must implement.
tools.base.SchemaAnnotationError
Raised when 'args_schema' is missing or has an incorrect type annotation.
tools.base.StructuredTool
Tool that can operate on any number of inputs.
tools.base.Tool
Tool that takes in function or coroutine directly.
tools.base.ToolException
An optional exception that tool throws when execution error occurs.
tools.bearly.tool.BearlyInterpreterTool(api_key)
Tool for evaluating python code in a sandbox environment.
tools.bearly.tool.BearlyInterpreterToolArguments
Arguments for the BearlyInterpreterTool.
tools.bearly.tool.FileInfo
Information about a file to be uploaded.
tools.bing_search.tool.BingSearchResults
Tool that queries the Bing Search API and gets back json.
tools.bing_search.tool.BingSearchRun
Tool that queries the Bing search API.
tools.brave_search.tool.BraveSearch
Tool that queries the BraveSearch.
tools.clickup.tool.ClickupAction
Tool that queries the  Clickup API.
tools.dataforseo_api_search.tool.DataForSeoAPISearchResults
Tool that queries the DataForSeo Google Search API and get back json.
tools.dataforseo_api_search.tool.DataForSeoAPISearchRun


tools.dataforseo_api_search.tool.DataForSeoAPISearchRun
Tool that queries the DataForSeo Google search API.
tools.ddg_search.tool.DDGInput
Create a new model by parsing and validating input data from keyword arguments.
tools.ddg_search.tool.DuckDuckGoSearchResults
Tool that queries the DuckDuckGo search API and gets back json.
tools.ddg_search.tool.DuckDuckGoSearchRun
Tool that queries the DuckDuckGo search API.
tools.e2b_data_analysis.tool.E2BDataAnalysisTool
Tool for running python code in a sandboxed environment for data analysis.
tools.e2b_data_analysis.tool.E2BDataAnalysisToolArguments
Arguments for the E2BDataAnalysisTool.
tools.e2b_data_analysis.tool.UploadedFile
Description of the uploaded path with its remote path.
tools.e2b_data_analysis.unparse.Unparser(tree)
Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.
tools.edenai.audio_speech_to_text.EdenAiSpeechToTextTool
Tool that queries the Eden AI Speech To Text API.
tools.edenai.audio_text_to_speech.EdenAiTextToSpeechTool
Tool that queries the Eden AI Text to speech API.
tools.edenai.edenai_base_tool.EdenaiTool
the base tool for all the EdenAI Tools .
tools.edenai.image_explicitcontent.EdenAiExplicitImageTool
Tool that queries the Eden AI Explicit image detection.
tools.edenai.image_objectdetection.EdenAiObjectDetectionTool
Tool that queries the Eden AI Object detection API.
tools.edenai.ocr_identityparser.EdenAiParsingIDTool
Tool that queries the Eden AI  Identity parsing API.
tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool


tools.edenai.ocr_invoiceparser.EdenAiParsingInvoiceTool
Tool that queries the Eden AI Invoice parsing API.
tools.edenai.text_moderation.EdenAiTextModerationTool
Tool that queries the Eden AI Explicit text detection.
tools.eleven_labs.models.ElevenLabsModel(value)
Models available for Eleven Labs Text2Speech.
tools.eleven_labs.text2speech.ElevenLabsModel(value)
Models available for Eleven Labs Text2Speech.
tools.eleven_labs.text2speech.ElevenLabsText2SpeechTool
Tool that queries the Eleven Labs Text2Speech API.
tools.file_management.copy.CopyFileTool
Tool that copies a file.
tools.file_management.copy.FileCopyInput
Input for CopyFileTool.
tools.file_management.delete.DeleteFileTool
Tool that deletes a file.
tools.file_management.delete.FileDeleteInput
Input for DeleteFileTool.
tools.file_management.file_search.FileSearchInput
Input for FileSearchTool.
tools.file_management.file_search.FileSearchTool
Tool that searches for files in a subdirectory that match a regex pattern.
tools.file_management.list_dir.DirectoryListingInput
Input for ListDirectoryTool.
tools.file_management.list_dir.ListDirectoryTool
Tool that lists files and directories in a specified folder.
tools.file_management.move.FileMoveInput
Input for MoveFileTool.
tools.file_management.move.MoveFileTool
Tool that moves a file.
tools.file_management.read.ReadFileInput
Input for ReadFileTool.
tools.file_management.read.ReadFileTool
Tool that reads a file.
tools.file_management.utils.BaseFileToolMixin
Mixin for file system tools.
tools.file_management.utils.FileValidationError
Error for paths outside the root directory.
tools.file_management.write.WriteFileInput
Input for WriteFileTool.
tools.file_management.write.WriteFileTool
Tool that writes a file to disk.


tools.file_management.write.WriteFileTool
Tool that writes a file to disk.
tools.github.tool.GitHubAction
Tool for interacting with the GitHub API.
tools.gitlab.tool.GitLabAction
Tool for interacting with the GitLab API.
tools.gmail.base.GmailBaseTool
Base class for Gmail tools.
tools.gmail.create_draft.CreateDraftSchema
Input for CreateDraftTool.
tools.gmail.create_draft.GmailCreateDraft
Tool that creates a draft email for Gmail.
tools.gmail.get_message.GmailGetMessage
Tool that gets a message by ID from Gmail.
tools.gmail.get_message.SearchArgsSchema
Input for GetMessageTool.
tools.gmail.get_thread.GetThreadSchema
Input for GetMessageTool.
tools.gmail.get_thread.GmailGetThread
Tool that gets a thread by ID from Gmail.
tools.gmail.search.GmailSearch
Tool that searches for messages or threads in Gmail.
tools.gmail.search.Resource(value[, names, ...])
Enumerator of Resources to search.
tools.gmail.search.SearchArgsSchema
Input for SearchGmailTool.
tools.gmail.send_message.GmailSendMessage
Tool that sends a message to Gmail.
tools.gmail.send_message.SendMessageSchema
Input for SendMessageTool.
tools.golden_query.tool.GoldenQueryRun
Tool that adds the capability to query using the Golden API and get back JSON.
tools.google_cloud.texttospeech.GoogleCloudTextToSpeechTool
Tool that queries the Google Cloud Text to Speech API.
tools.google_places.tool.GooglePlacesSchema
Input for GooglePlacesTool.
tools.google_places.tool.GooglePlacesTool
Tool that queries the Google places API.
tools.google_scholar.tool.GoogleScholarQueryRun
Tool that queries the Google search API.
tools.google_search.tool.GoogleSearchResults
Tool that queries the Google Search API and gets back json.
tools.google_search.tool.GoogleSearchRun
Tool that queries the Google search API.


tools.google_search.tool.GoogleSearchRun
Tool that queries the Google search API.
tools.google_serper.tool.GoogleSerperResults
Tool that queries the Serper.dev Google Search API and get back json.
tools.google_serper.tool.GoogleSerperRun
Tool that queries the Serper.dev Google search API.
tools.graphql.tool.BaseGraphQLTool
Base tool for querying a GraphQL API.
tools.human.tool.HumanInputRun
Tool that asks user for input.
tools.ifttt.IFTTTWebhook
IFTTT Webhook.
tools.jira.tool.JiraAction
Tool that queries the Atlassian Jira API.
tools.json.tool.JsonGetValueTool
Tool for getting a value in a JSON spec.
tools.json.tool.JsonListKeysTool
Tool for listing keys in a JSON spec.
tools.json.tool.JsonSpec
Base class for JSON spec.
tools.memorize.tool.Memorize
Create a new model by parsing and validating input data from keyword arguments.
tools.memorize.tool.TrainableLLM(*args, **kwargs)
tools.metaphor_search.tool.MetaphorSearchResults
Tool that queries the Metaphor Search API and gets back json.
tools.multion.close_session.CloseSessionSchema
Input for UpdateSessionTool.
tools.multion.close_session.MultionCloseSession
Tool that closes an existing Multion Browser Window with provided fields.
tools.multion.create_session.CreateSessionSchema
Input for CreateSessionTool.
tools.multion.create_session.MultionCreateSession
Tool that creates a new Multion Browser Window with provided fields.
tools.multion.update_session.MultionUpdateSession
Tool that updates an existing Multion Browser Window with provided fields.
tools.multion.update_session.UpdateSessionSchema
Input for UpdateSessionTool.
tools.nuclia.tool.NUASchema
Input for Nuclia Understanding API.


tools.nuclia.tool.NUASchema
Input for Nuclia Understanding API.
tools.nuclia.tool.NucliaUnderstandingAPI
Tool to process files with the Nuclia Understanding API.
tools.office365.base.O365BaseTool
Base class for the Office 365 tools.
tools.office365.create_draft_message.CreateDraftMessageSchema
Input for SendMessageTool.
tools.office365.create_draft_message.O365CreateDraftMessage
Tool for creating a draft email in Office 365.
tools.office365.events_search.O365SearchEvents
Class for searching calendar events in Office 365
tools.office365.events_search.SearchEventsInput
Input for SearchEmails Tool.
tools.office365.messages_search.O365SearchEmails
Class for searching email messages in Office 365
tools.office365.messages_search.SearchEmailsInput
Input for SearchEmails Tool.
tools.office365.send_event.O365SendEvent
Tool for sending calendar events in Office 365.
tools.office365.send_event.SendEventSchema
Input for CreateEvent Tool.
tools.office365.send_message.O365SendMessage
Tool for sending an email in Office 365.
tools.office365.send_message.SendMessageSchema
Input for SendMessageTool.
tools.openapi.utils.api_models.APIOperation
A model for a single API operation.
tools.openapi.utils.api_models.APIProperty
A model for a property in the query, path, header, or cookie params.
tools.openapi.utils.api_models.APIPropertyBase
Base model for an API property.
tools.openapi.utils.api_models.APIPropertyLocation(value)
The location of the property.
tools.openapi.utils.api_models.APIRequestBody
A model for a request body.
tools.openapi.utils.api_models.APIRequestBodyProperty
A model for a request body property.
tools.openweathermap.tool.OpenWeatherMapQueryRun
Tool that queries the OpenWeatherMap API.
tools.playwright.base.BaseBrowserTool
Base class for browser tools.


tools.playwright.base.BaseBrowserTool
Base class for browser tools.
tools.playwright.click.ClickTool
Tool for clicking on an element with the given CSS selector.
tools.playwright.click.ClickToolInput
Input for ClickTool.
tools.playwright.current_page.CurrentWebPageTool
Tool for getting the URL of the current webpage.
tools.playwright.extract_hyperlinks.ExtractHyperlinksTool
Extract all hyperlinks on the page.
tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput
Input for ExtractHyperlinksTool.
tools.playwright.extract_text.ExtractTextTool
Tool for extracting all the text on the current webpage.
tools.playwright.get_elements.GetElementsTool
Tool for getting elements in the current web page matching a CSS selector.
tools.playwright.get_elements.GetElementsToolInput
Input for GetElementsTool.
tools.playwright.navigate.NavigateTool
Tool for navigating a browser to a URL.
tools.playwright.navigate.NavigateToolInput
Input for NavigateToolInput.
tools.playwright.navigate_back.NavigateBackTool
Navigate back to the previous page in the browser history.
tools.plugin.AIPlugin
AI Plugin Definition.
tools.plugin.AIPluginTool
Tool for getting the OpenAPI spec for an AI Plugin.
tools.plugin.AIPluginToolSchema
Schema for AIPluginTool.
tools.plugin.ApiConfig
API Configuration.
tools.powerbi.tool.InfoPowerBITool
Tool for getting metadata about a PowerBI Dataset.
tools.powerbi.tool.ListPowerBITool
Tool for getting tables names.
tools.powerbi.tool.QueryPowerBITool
Tool for querying a Power BI Dataset.
tools.pubmed.tool.PubmedQueryRun
Tool that searches the PubMed API.
tools.requests.tool.BaseRequestsTool
Base class for requests tools.
tools.requests.tool.RequestsDeleteTool
Tool for making a DELETE request to an API endpoint.
tools.requests.tool.RequestsGetTool


Tool for making a DELETE request to an API endpoint.
tools.requests.tool.RequestsGetTool
Tool for making a GET request to an API endpoint.
tools.requests.tool.RequestsPatchTool
Tool for making a PATCH request to an API endpoint.
tools.requests.tool.RequestsPostTool
Tool for making a POST request to an API endpoint.
tools.requests.tool.RequestsPutTool
Tool for making a PUT request to an API endpoint.
tools.retriever.RetrieverInput
Create a new model by parsing and validating input data from keyword arguments.
tools.scenexplain.tool.SceneXplainInput
Input for SceneXplain.
tools.scenexplain.tool.SceneXplainTool
Tool that explains images.
tools.searchapi.tool.SearchAPIResults
Tool that queries the SearchApi.io search API and returns JSON.
tools.searchapi.tool.SearchAPIRun
Tool that queries the SearchApi.io search API.
tools.searx_search.tool.SearxSearchResults
Tool that queries a Searx instance and gets back json.
tools.searx_search.tool.SearxSearchRun
Tool that queries a Searx instance.
tools.shell.tool.ShellInput
Commands for the Bash Shell tool.
tools.shell.tool.ShellTool
Tool to run shell commands.
tools.sleep.tool.SleepInput
Input for CopyFileTool.
tools.sleep.tool.SleepTool
Tool that adds the capability to sleep.
tools.spark_sql.tool.BaseSparkSQLTool
Base tool for interacting with Spark SQL.
tools.spark_sql.tool.InfoSparkSQLTool
Tool for getting metadata about a Spark SQL.
tools.spark_sql.tool.ListSparkSQLTool
Tool for getting tables names.
tools.spark_sql.tool.QueryCheckerTool
Use an LLM to check if a query is correct.
tools.spark_sql.tool.QuerySparkSQLTool
Tool for querying a Spark SQL.
tools.sql_database.tool.BaseSQLDatabaseTool


Tool for querying a Spark SQL.
tools.sql_database.tool.BaseSQLDatabaseTool
Base tool for interacting with a SQL database.
tools.sql_database.tool.InfoSQLDatabaseTool
Tool for getting metadata about a SQL database.
tools.sql_database.tool.ListSQLDatabaseTool
Tool for getting tables names.
tools.sql_database.tool.QuerySQLCheckerTool
Use an LLM to check if a query is correct.
tools.sql_database.tool.QuerySQLDataBaseTool
Tool for querying a SQL database.
tools.steamship_image_generation.tool.ModelName(value)
Supported Image Models for generation.
tools.steamship_image_generation.tool.SteamshipImageGenerationTool
Tool used to generate images from a text-prompt.
tools.tavily_search.tool.TavilyAnswer
Tool that queries the Tavily Search API and gets back an answer.
tools.tavily_search.tool.TavilyInput
Create a new model by parsing and validating input data from keyword arguments.
tools.tavily_search.tool.TavilySearchResults
Tool that queries the Tavily Search API and gets back json.
tools.vectorstore.tool.BaseVectorStoreTool
Base class for tools that use a VectorStore.
tools.vectorstore.tool.VectorStoreQATool
Tool for the VectorDBQA chain.
tools.vectorstore.tool.VectorStoreQAWithSourcesTool
Tool for the VectorDBQAWithSources chain.
tools.wikipedia.tool.WikipediaQueryRun
Tool that searches the Wikipedia API.
tools.wolfram_alpha.tool.WolframAlphaQueryRun
Tool that queries using the Wolfram Alpha SDK.
tools.yahoo_finance_news.YahooFinanceNewsTool
Tool that searches financial news on Yahoo Finance.
tools.youtube.search.YouTubeSearchTool
Tool that queries YouTube.
tools.zapier.tool.ZapierNLAListActions
Returns a list of all exposed (enabled) actions associated with


Returns a list of all exposed (enabled) actions associated with
tools.zapier.tool.ZapierNLARunAction
Executes an action that is identified by action_id, must be exposed
Functions¶
tools.ainetwork.utils.authenticate([network])
Authenticate using the AIN Blockchain
tools.amadeus.utils.authenticate()
Authenticate using the Amadeus API
tools.azure_cognitive_services.utils.detect_file_src_type(...)
Detect if the file is local or remote.
tools.azure_cognitive_services.utils.download_audio_from_url(...)
Download audio from url to local.
tools.base.create_schema_from_function(...)
Create a pydantic schema from a function's signature.
tools.base.tool(*args[, return_direct, ...])
Make tools out of functions, can be used with or without arguments.
tools.bearly.tool.file_to_base64(path)
Convert a file to base64.
tools.bearly.tool.head_file(path, n)
Get the first n lines of a file.
tools.bearly.tool.strip_markdown_code(md_string)
Strip markdown code from a string.
tools.ddg_search.tool.DuckDuckGoSearchTool(...)
Deprecated.
tools.e2b_data_analysis.tool.add_last_line_print(code)
Add print statement to the last line if it's missing.
tools.e2b_data_analysis.unparse.interleave(...)
Call f on each item in seq, calling inter() in between.
tools.e2b_data_analysis.unparse.roundtrip(...)
tools.file_management.utils.get_validated_relative_path(...)
Resolve a relative path, raising an error if not within the root directory.
tools.file_management.utils.is_relative_to(...)
Check if path is relative to root.
tools.gmail.utils.build_resource_service([...])
Build a Gmail service.
tools.gmail.utils.clean_email_body(body)
Clean email body.
tools.gmail.utils.get_gmail_credentials([...])


Clean email body.
tools.gmail.utils.get_gmail_credentials([...])
Get credentials.
tools.gmail.utils.import_google()
Import google libraries.
tools.gmail.utils.import_googleapiclient_resource_builder()
Import googleapiclient.discovery.build function.
tools.gmail.utils.import_installed_app_flow()
Import InstalledAppFlow class.
tools.interaction.tool.StdInInquireTool(...)
Tool for asking the user for input.
tools.office365.utils.authenticate()
Authenticate using the Microsoft Grah API
tools.office365.utils.clean_body(body)
Clean body of a message or event.
tools.playwright.base.lazy_import_playwright_browsers()
Lazy import playwright browsers.
tools.playwright.utils.aget_current_page(browser)
Asynchronously get the current page of the browser.
tools.playwright.utils.create_async_playwright_browser([...])
Create an async playwright browser.
tools.playwright.utils.create_sync_playwright_browser([...])
Create a playwright browser.
tools.playwright.utils.get_current_page(browser)
Get the current page of the browser.
tools.playwright.utils.run_async(coro)
Run an async coroutine.
tools.plugin.marshal_spec(txt)
Convert the yaml or json serialized spec to a dict.
tools.render.format_tool_to_openai_function(tool)
Format tool into the OpenAI function API.
tools.render.format_tool_to_openai_tool(tool)
Format tool into the OpenAI function API.
tools.render.render_text_description(tools)
Render the tool name and description in plain text.
tools.render.render_text_description_and_args(tools)
Render the tool name, description, and args in plain text.
tools.retriever.create_retriever_tool(...)
Create a tool to do retrieval of documents.
tools.steamship_image_generation.utils.make_image_public(...)
Upload a block to a signed URL and return the public URL.
langchain.tools.render¶


Upload a block to a signed URL and return the public URL.
langchain.tools.render¶
Different methods for rendering Tools to be passed to LLMs.
Depending on the LLM you are using and the prompting strategy you are using,
you may want Tools to be rendered in a different way.
This module contains various ways to render tools.
Functions¶
tools.render.format_tool_to_openai_function(tool)
Format tool into the OpenAI function API.
tools.render.format_tool_to_openai_tool(tool)
Format tool into the OpenAI function API.
tools.render.render_text_description(tools)
Render the tool name and description in plain text.
tools.render.render_text_description_and_args(tools)
Render the tool name, description, and args in plain text.
langchain.utilities¶
Utilities are the integrations with third-part systems and packages.
Other LangChain classes use Utilities to interact with third-part systems
and packages.
Classes¶
utilities.alpha_vantage.AlphaVantageAPIWrapper
Wrapper for AlphaVantage API for Currency Exchange Rate.
utilities.apify.ApifyWrapper
Wrapper around Apify.
utilities.arcee.ArceeDocument
Arcee document.
utilities.arcee.ArceeDocumentAdapter()
Adapter for Arcee documents
utilities.arcee.ArceeDocumentSource
Source of an Arcee document.
utilities.arcee.ArceeRoute(value[, names, ...])
Routes available for the Arcee API as enumerator.
utilities.arcee.ArceeWrapper(arcee_api_key, ...)
Wrapper for Arcee API.
utilities.arcee.DALMFilter
Filters available for a DALM retrieval and generation.
utilities.arcee.DALMFilterType(value[, ...])
Filter types available for a DALM retrieval as enumerator.
utilities.arxiv.ArxivAPIWrapper
Wrapper around ArxivAPI.
utilities.awslambda.LambdaWrapper


Wrapper around ArxivAPI.
utilities.awslambda.LambdaWrapper
Wrapper for AWS Lambda SDK.
utilities.bibtex.BibtexparserWrapper
Wrapper around bibtexparser.
utilities.bing_search.BingSearchAPIWrapper
Wrapper for Bing Search API.
utilities.brave_search.BraveSearchWrapper
Wrapper around the Brave search engine.
utilities.clickup.CUList(folder_id, name[, ...])
Component class for a list.
utilities.clickup.ClickupAPIWrapper
Wrapper for Clickup API.
utilities.clickup.Component()
Base class for all components.
utilities.clickup.Member(id, username, ...)
Component class for a member.
utilities.clickup.Space(id, name, private, ...)
Component class for a space.
utilities.clickup.Task(id, name, ...)
Class for a task.
utilities.clickup.Team(id, name, members)
Component class for a team.
utilities.dalle_image_generator.DallEAPIWrapper
Wrapper for OpenAI's DALL-E Image Generator.
utilities.dataforseo_api_search.DataForSeoAPIWrapper
Wrapper around the DataForSeo API.
utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper
Wrapper for DuckDuckGo Search API.
utilities.github.GitHubAPIWrapper
Wrapper for GitHub API.
utilities.gitlab.GitLabAPIWrapper
Wrapper for GitLab API.
utilities.golden_query.GoldenQueryAPIWrapper
Wrapper for Golden.
utilities.google_places_api.GooglePlacesAPIWrapper
Wrapper around Google Places API.
utilities.google_scholar.GoogleScholarAPIWrapper
Wrapper for Google Scholar API
utilities.google_search.GoogleSearchAPIWrapper
Wrapper for Google Search API.
utilities.google_serper.GoogleSerperAPIWrapper
Wrapper around the Serper.dev Google Search API.
utilities.graphql.GraphQLAPIWrapper


Wrapper around the Serper.dev Google Search API.
utilities.graphql.GraphQLAPIWrapper
Wrapper around GraphQL API.
utilities.jira.JiraAPIWrapper
Wrapper for Jira API.
utilities.max_compute.MaxComputeAPIWrapper(client)
Interface for querying Alibaba Cloud MaxCompute tables.
utilities.metaphor_search.MetaphorSearchAPIWrapper
Wrapper for Metaphor Search API.
utilities.openapi.HTTPVerb(value[, names, ...])
Enumerator of the HTTP verbs.
utilities.openapi.OpenAPISpec()
OpenAPI Model that removes mis-formatted parts of the spec.
utilities.openweathermap.OpenWeatherMapAPIWrapper
Wrapper for OpenWeatherMap API using PyOWM.
utilities.portkey.Portkey()
Portkey configuration.
utilities.powerbi.PowerBIDataset
Create PowerBI engine from dataset ID and credential or token.
utilities.pubmed.PubMedAPIWrapper
Wrapper around PubMed API.
utilities.python.PythonREPL
Simulates a standalone Python REPL.
utilities.redis.TokenEscaper([escape_chars_re])
Escape punctuation within an input string.
utilities.requests.Requests
Wrapper around requests to handle auth and async.
utilities.requests.RequestsWrapper
alias of TextRequestsWrapper
utilities.requests.TextRequestsWrapper
Lightweight wrapper around requests library.
utilities.scenexplain.SceneXplainAPIWrapper
Wrapper for SceneXplain API.
utilities.searchapi.SearchApiAPIWrapper
Wrapper around SearchApi API.
utilities.searx_search.SearxResults(data)
Dict like wrapper around search api results.
utilities.searx_search.SearxSearchWrapper
Wrapper for Searx API.
utilities.serpapi.HiddenPrints()
Context manager to hide prints.
utilities.serpapi.SerpAPIWrapper
Wrapper around SerpAPI.
utilities.spark_sql.SparkSQL([...])
SparkSQL is a utility class for interacting with Spark SQL.


SparkSQL is a utility class for interacting with Spark SQL.
utilities.sql_database.SQLDatabase(engine[, ...])
SQLAlchemy wrapper around a database.
utilities.tavily_search.TavilySearchAPIWrapper
Wrapper for Tavily Search API.
utilities.tensorflow_datasets.TensorflowDatasets
Access to the TensorFlow Datasets.
utilities.twilio.TwilioAPIWrapper
Messaging Client using Twilio.
utilities.wikipedia.WikipediaAPIWrapper
Wrapper around WikipediaAPI.
utilities.wolfram_alpha.WolframAlphaAPIWrapper
Wrapper for Wolfram Alpha.
utilities.zapier.ZapierNLAWrapper
Wrapper for Zapier NLA.
Functions¶
utilities.anthropic.get_num_tokens_anthropic(text)
Get the number of tokens in a string of text.
utilities.anthropic.get_token_ids_anthropic(text)
Get the token ids for a string of text.
utilities.clickup.extract_dict_elements_from_component_fields(...)
Extract elements from a dictionary.
utilities.clickup.fetch_data(url, access_token)
Fetch data from a URL.
utilities.clickup.fetch_first_id(data, key)
Fetch the first id from a dictionary.
utilities.clickup.fetch_folder_id(space_id, ...)
Fetch the folder id.
utilities.clickup.fetch_list_id(space_id, ...)
Fetch the list id.
utilities.clickup.fetch_space_id(team_id, ...)
Fetch the space id.
utilities.clickup.fetch_team_id(access_token)
Fetch the team id.
utilities.clickup.load_query(query[, ...])
Attempts to parse a JSON string and return the parsed object.
utilities.clickup.parse_dict_through_component(...)
Parse a dictionary by creating a component and then turning it back into a dictionary.
utilities.opaqueprompts.desanitize(...)
Restore the original sensitive data from the sanitized text.
utilities.opaqueprompts.sanitize(input)


utilities.opaqueprompts.sanitize(input)
Sanitize input string or dict of strings by replacing sensitive data with placeholders.
utilities.powerbi.fix_table_name(table)
Add single quotes around table names that contain spaces.
utilities.powerbi.json_to_md(json_contents)
Converts a JSON object to a markdown table.
utilities.redis.check_redis_module_exist(...)
Check if the correct Redis modules are installed.
utilities.redis.get_client(redis_url, **kwargs)
Get a redis client from the connection url given.
utilities.sql_database.truncate_word(...[, ...])
Truncate a string to a certain number of words, based on the max string length.
utilities.vertexai.get_client_info([module])
Returns a custom user agent header.
utilities.vertexai.init_vertexai([project, ...])
Init vertexai.
utilities.vertexai.raise_vertex_import_error([...])
Raise ImportError related to Vertex SDK being not available.
langchain.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
utils.openai_functions.FunctionDescription
Representation of a callable function to the OpenAI API.
utils.openai_functions.ToolDescription
Representation of a callable function to the OpenAI API.
Functions¶
utils.aiter.py_anext(iterator[, default])


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.get_from_dict_or_env(data, key, ...)
Get a value from a dictionary or an environment variable.
utils.env.get_from_env(key, env_key[, default])
Get a value from a dictionary or an environment variable.
utils.html.extract_sub_links(raw_html, url, *)
Extract all links from a raw html string and convert into absolute paths.
utils.html.find_all_links(raw_html, *[, pattern])
Extract all links from a raw html string.
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.json_schema.dereference_refs(schema_obj, *)
Try to substitute $refs in JSON Schema.
utils.loading.try_load_from_hub(path, ...)
Load configuration from hub.
utils.math.cosine_similarity(X, Y)
Row-wise cosine similarity between two equal-width matrices.
utils.math.cosine_similarity_top_k(X, Y[, ...])
Row-wise cosine similarity with optional top-k and score threshold filtering.
utils.openai.is_openai_v1()
utils.openai_functions.convert_pydantic_to_openai_function(...)


utils.openai_functions.convert_pydantic_to_openai_function(...)
Converts a Pydantic model to a function description for the OpenAI API.
utils.openai_functions.convert_pydantic_to_openai_tool(...)
Converts a Pydantic model to a function description for the OpenAI API.
utils.pydantic.get_pydantic_major_version()
Get the major version of Pydantic.
utils.strings.comma_list(items)
Convert a list to a comma-separated string.
utils.strings.stringify_dict(data)
Stringify a dictionary.
utils.strings.stringify_value(val)
Stringify a value.
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.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¶
vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch(...)
Alibaba Cloud OpenSearch vector store.
vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearchSettings(...)
Alibaba Cloud Opensearch` client configuration.
vectorstores.analyticdb.AnalyticDB(...[, ...])
AnalyticDB (distributed PostgreSQL) vector store.
vectorstores.annoy.Annoy(embedding_function, ...)
Annoy vector store.
vectorstores.astradb.AstraDB(*, embedding, ...)
Wrapper around DataStax Astra DB for vector-store workloads.
vectorstores.atlas.AtlasDB(name[, ...])
Atlas vector store.
vectorstores.awadb.AwaDB([table_name, ...])
AwaDB vector store.
vectorstores.azure_cosmos_db.AzureCosmosDBVectorSearch(...)
Azure Cosmos DB for MongoDB vCore vector store.
vectorstores.azure_cosmos_db.CosmosDBSimilarityType(value)
Cosmos DB Similarity Type as enumerator.
vectorstores.azuresearch.AzureSearch(...[, ...])
Azure Cognitive Search vector store.
vectorstores.azuresearch.AzureSearchVectorStoreRetriever
Retriever that uses Azure Cognitive Search.
vectorstores.bageldb.Bagel([cluster_name, ...])
BagelDB.ai vector store.
vectorstores.baiducloud_vector_search.BESVectorStore(...)
Baidu Elasticsearch vector store.
vectorstores.cassandra.Cassandra(embedding, ...)
Wrapper around Apache Cassandra(R) for vector-store workloads.
vectorstores.chroma.Chroma([...])
ChromaDB vector store.


vectorstores.chroma.Chroma([...])
ChromaDB vector store.
vectorstores.clarifai.Clarifai([user_id, ...])
Clarifai AI vector store.
vectorstores.clickhouse.Clickhouse(embedding)
ClickHouse VectorSearch vector store.
vectorstores.clickhouse.ClickhouseSettings
ClickHouse client configuration.
vectorstores.dashvector.DashVector(...)
DashVector vector store.
vectorstores.deeplake.DeepLake([...])
Activeloop Deep Lake vector store.
vectorstores.dingo.Dingo(embedding, text_key, *)
Dingo vector store.
vectorstores.docarray.base.DocArrayIndex(...)
Base class for DocArray based vector stores.
vectorstores.docarray.hnsw.DocArrayHnswSearch(...)
HnswLib storage using DocArray package.
vectorstores.docarray.in_memory.DocArrayInMemorySearch(...)
In-memory DocArray storage for exact search.
vectorstores.elastic_vector_search.ElasticKnnSearch(...)
[Deprecated]  [DEPRECATED] Elasticsearch with k-nearest neighbor search (k-NN) vector store.
vectorstores.elastic_vector_search.ElasticVectorSearch(...)
ElasticVectorSearch uses the brute force method of searching on vectors.
vectorstores.elasticsearch.ApproxRetrievalStrategy([...])
Approximate retrieval strategy using the HNSW algorithm.
vectorstores.elasticsearch.BaseRetrievalStrategy()
Base class for Elasticsearch retrieval strategies.
vectorstores.elasticsearch.ElasticsearchStore(...)
Elasticsearch vector store.
vectorstores.elasticsearch.ExactRetrievalStrategy()
Exact retrieval strategy using the script_score query.
vectorstores.elasticsearch.SparseRetrievalStrategy([...])
Sparse retrieval strategy using the text_expansion processor.
vectorstores.epsilla.Epsilla(client, embeddings)
Wrapper around Epsilla vector database.


Wrapper around Epsilla vector database.
vectorstores.faiss.FAISS(embedding_function, ...)
Meta Faiss vector store.
vectorstores.hippo.Hippo(embedding_function)
Hippo vector store.
vectorstores.hologres.Hologres(...[, ndims, ...])
Hologres API vector store.
vectorstores.hologres.HologresWrapper(...)
Hologres API wrapper.
vectorstores.lancedb.LanceDB(connection, ...)
LanceDB vector store.
vectorstores.llm_rails.LLMRails([...])
Implementation of Vector Store using LLMRails.
vectorstores.llm_rails.LLMRailsRetriever
Retriever for LLMRails.
vectorstores.marqo.Marqo(client, index_name)
Marqo vector store.
vectorstores.matching_engine.MatchingEngine(...)
Google Vertex AI Matching Engine vector store.
vectorstores.meilisearch.Meilisearch(embedding)
Meilisearch vector store.
vectorstores.milvus.Milvus(embedding_function)
Milvus vector store.
vectorstores.momento_vector_index.MomentoVectorIndex(...)
Momento Vector Index (MVI) vector store.
vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch(...)
MongoDB Atlas Vector Search vector store.
vectorstores.myscale.MyScale(embedding[, config])
MyScale vector store.
vectorstores.myscale.MyScaleSettings
MyScale client configuration.
vectorstores.myscale.MyScaleWithoutJSON(...)
MyScale vector store without metadata column
vectorstores.neo4j_vector.Neo4jVector(...[, ...])
Neo4j vector index.
vectorstores.neo4j_vector.SearchType(value)
Enumerator of the Distance strategies.
vectorstores.nucliadb.NucliaDB(...[, ...])


vectorstores.nucliadb.NucliaDB(...[, ...])
NucliaDB vector store.
vectorstores.opensearch_vector_search.OpenSearchVectorSearch(...)
Amazon OpenSearch Vector Engine vector store.
vectorstores.pgembedding.BaseModel(**kwargs)
Base model for all SQL stores.
vectorstores.pgembedding.CollectionStore(...)
Collection store.
vectorstores.pgembedding.EmbeddingStore(**kwargs)
Embedding store.
vectorstores.pgembedding.PGEmbedding(...[, ...])
Postgres with the pg_embedding extension as a vector store.
vectorstores.pgembedding.QueryResult()
Result from a query.
vectorstores.pgvecto_rs.PGVecto_rs(...[, ...])
vectorstores.pgvector.BaseModel(**kwargs)
Base model for the SQL stores.
vectorstores.pgvector.DistanceStrategy(value)
Enumerator of the Distance strategies.
vectorstores.pgvector.PGVector(...[, ...])
Postgres/PGVector vector store.
vectorstores.pinecone.Pinecone(index, ...[, ...])
Pinecone vector store.
vectorstores.qdrant.Qdrant(client, ...[, ...])
Qdrant vector store.
vectorstores.qdrant.QdrantException
Qdrant related exceptions.
vectorstores.redis.base.Redis(redis_url, ...)
Redis vector database.
vectorstores.redis.base.RedisVectorStoreRetriever
Retriever for Redis VectorStore.
vectorstores.redis.filters.RedisFilter()
Collection of RedisFilterFields.
vectorstores.redis.filters.RedisFilterExpression([...])
A logical expression of RedisFilterFields.
vectorstores.redis.filters.RedisFilterField(field)
Base class for RedisFilterFields.
vectorstores.redis.filters.RedisFilterOperator(value)
RedisFilterOperator enumerator is used to create RedisFilterExpressions.
vectorstores.redis.filters.RedisNum(field)


vectorstores.redis.filters.RedisNum(field)
A RedisFilterField representing a numeric field in a Redis index.
vectorstores.redis.filters.RedisTag(field)
A RedisFilterField representing a tag in a Redis index.
vectorstores.redis.filters.RedisText(field)
A RedisFilterField representing a text field in a Redis index.
vectorstores.redis.schema.FlatVectorField
Schema for flat vector fields in Redis.
vectorstores.redis.schema.HNSWVectorField
Schema for HNSW vector fields in Redis.
vectorstores.redis.schema.NumericFieldSchema
Schema for numeric fields in Redis.
vectorstores.redis.schema.RedisDistanceMetric(value)
Distance metrics for Redis vector fields.
vectorstores.redis.schema.RedisField
Base class for Redis fields.
vectorstores.redis.schema.RedisModel
Schema for Redis index.
vectorstores.redis.schema.RedisVectorField
Base class for Redis vector fields.
vectorstores.redis.schema.TagFieldSchema
Schema for tag fields in Redis.
vectorstores.redis.schema.TextFieldSchema
Schema for text fields in Redis.
vectorstores.rocksetdb.Rockset(client, ...)
Rockset vector store.
vectorstores.scann.ScaNN(embedding, index, ...)
ScaNN vector store.
vectorstores.semadb.SemaDB(collection_name, ...)
SemaDB vector store.
vectorstores.singlestoredb.SingleStoreDB(...)
SingleStore DB vector store.
vectorstores.sklearn.BaseSerializer(persist_path)
Base class for serializing data.
vectorstores.sklearn.BsonSerializer(persist_path)
Serializes data in binary json using the bson python package.
vectorstores.sklearn.JsonSerializer(persist_path)
Serializes data in json using the json package from python standard library.
vectorstores.sklearn.ParquetSerializer(...)
Serializes data in Apache Parquet format using the pyarrow package.
vectorstores.sklearn.SKLearnVectorStore(...)


vectorstores.sklearn.SKLearnVectorStore(...)
Simple in-memory vector store based on the scikit-learn library NearestNeighbors implementation.
vectorstores.sklearn.SKLearnVectorStoreException
Exception raised by SKLearnVectorStore.
vectorstores.sqlitevss.SQLiteVSS(table, ...)
Wrapper around SQLite with vss extension as a vector database.
vectorstores.starrocks.StarRocks(embedding)
StarRocks vector store.
vectorstores.starrocks.StarRocksSettings
StarRocks client configuration.
vectorstores.supabase.SupabaseVectorStore(...)
Supabase Postgres vector store.
vectorstores.tair.Tair(embedding_function, ...)
Tair vector store.
vectorstores.tencentvectordb.ConnectionParams(...)
Tencent vector DB Connection params.
vectorstores.tencentvectordb.IndexParams(...)
Tencent vector DB Index params.
vectorstores.tencentvectordb.TencentVectorDB(...)
Initialize wrapper around the tencent vector database.
vectorstores.tigris.Tigris(client, ...)
Tigris vector store.
vectorstores.tiledb.TileDB(embedding, ...[, ...])
Wrapper around TileDB vector database.
vectorstores.timescalevector.TimescaleVector(...)
VectorStore implementation using the timescale vector client to store vectors in Postgres.
vectorstores.typesense.Typesense(...[, ...])
Typesense vector store.
vectorstores.usearch.USearch(embedding, ...)
USearch vector store.
vectorstores.utils.DistanceStrategy(value[, ...])
Enumerator of the Distance strategies for calculating distances between vectors.
vectorstores.vald.Vald(embedding[, host, ...])
Wrapper around Vald vector database.
vectorstores.vearch.Vearch(embedding_function)
Initialize vearch vector store flag 1 for cluster,0 for standalone


Initialize vearch vector store flag 1 for cluster,0 for standalone
vectorstores.vectara.Vectara([...])
Vectara API vector store.
vectorstores.vectara.VectaraRetriever
Retriever class for Vectara.
vectorstores.vespa.VespaStore(app[, ...])
Vespa vector store.
vectorstores.weaviate.Weaviate(client, ...)
Weaviate vector store.
vectorstores.xata.XataVectorStore(api_key, ...)
Xata vector store.
vectorstores.zep.CollectionConfig(name, ...)
Configuration for a Zep Collection.
vectorstores.zep.ZepVectorStore(...[, ...])
Zep vector store.
vectorstores.zilliz.Zilliz(embedding_function)
Zilliz vector store.
Functions¶
vectorstores.alibabacloud_opensearch.create_metadata(fields)
Create metadata from fields.
vectorstores.annoy.dependable_annoy_import()
Import annoy if available, otherwise raise error.
vectorstores.clickhouse.has_mul_sub_str(s, *args)
Check if a string contains multiple substrings.
vectorstores.faiss.dependable_faiss_import([...])
Import faiss if available, otherwise raise error.
vectorstores.myscale.has_mul_sub_str(s, *args)
Check if a string contains multiple substrings.
vectorstores.neo4j_vector.check_if_not_null(...)
Check if the values are not None or empty string
vectorstores.neo4j_vector.sort_by_index_name(...)
Sort first element to match the index_name if exists
vectorstores.qdrant.sync_call_fallback(method)
Decorator to call the synchronous method of the class if the async method is not implemented.
vectorstores.redis.base.check_index_exists(...)
Check if Redis index exists.
vectorstores.redis.filters.check_operator_misuse(func)


Check if Redis index exists.
vectorstores.redis.filters.check_operator_misuse(func)
Decorator to check for misuse of equality operators.
vectorstores.redis.schema.read_schema(...)
Reads in the index schema from a dict or yaml file.
vectorstores.scann.dependable_scann_import()
Import scann if available, otherwise raise error.
vectorstores.scann.normalize(x)
Normalize vectors to unit length.
vectorstores.starrocks.debug_output(s)
Print a debug message if DEBUG is True.
vectorstores.starrocks.get_named_result(...)
Get a named result from a query.
vectorstores.starrocks.has_mul_sub_str(s, *args)
Check if a string has multiple substrings.
vectorstores.tiledb.dependable_tiledb_import()
Import tiledb-vector-search if available, otherwise raise error.
vectorstores.tiledb.get_documents_array_uri(uri)
vectorstores.tiledb.get_documents_array_uri_from_group(group)
vectorstores.tiledb.get_vector_index_uri(uri)
vectorstores.tiledb.get_vector_index_uri_from_group(group)
vectorstores.usearch.dependable_usearch_import()
Import usearch if available, otherwise raise error.
vectorstores.utils.filter_complex_metadata(...)
Filter out metadata types that are not supported for a vector store.
vectorstores.utils.maximal_marginal_relevance(...)
Calculate maximal marginal relevance.


langchain_experimental API Reference¶
langchain_experimental.agents¶
Functions¶
agents.agent_toolkits.csv.base.create_csv_agent(...)
Create csv agent by loading to a dataframe and using pandas agent.
agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent(llm, df)
Construct a pandas agent from an LLM and dataframe.
agents.agent_toolkits.python.base.create_python_agent(...)
Construct a python agent from an LLM and tool.
agents.agent_toolkits.spark.base.create_spark_dataframe_agent(llm, df)
Construct a Spark agent from an LLM and dataframe.
agents.agent_toolkits.xorbits.base.create_xorbits_agent(...)
Construct a xorbits agent from an LLM and dataframe.
langchain_experimental.autonomous_agents¶
Classes¶
autonomous_agents.autogpt.agent.AutoGPT(...)
Agent class for interacting with Auto-GPT.
autonomous_agents.autogpt.memory.AutoGPTMemory
Memory for AutoGPT.
autonomous_agents.autogpt.output_parser.AutoGPTAction(...)
Action returned by AutoGPTOutputParser.
autonomous_agents.autogpt.output_parser.AutoGPTOutputParser
Output parser for AutoGPT.
autonomous_agents.autogpt.output_parser.BaseAutoGPTOutputParser
Base Output parser for AutoGPT.
autonomous_agents.autogpt.prompt.AutoGPTPrompt
Prompt for AutoGPT.
autonomous_agents.autogpt.prompt_generator.PromptGenerator()
A class for generating custom prompt strings.
autonomous_agents.baby_agi.baby_agi.BabyAGI
Controller model for the BabyAGI agent.
autonomous_agents.baby_agi.task_creation.TaskCreationChain
Chain generating tasks.
autonomous_agents.baby_agi.task_execution.TaskExecutionChain
Chain to execute tasks.
autonomous_agents.baby_agi.task_prioritization.TaskPrioritizationChain