Base class for browser tools.
tools.playwright.click.ClickTool
Create a new model by parsing and validating input data from keyword arguments.
tools.playwright.click.ClickToolInput
Input for ClickTool.
tools.playwright.current_page.CurrentWebPageTool
Create a new model by parsing and validating input data from keyword arguments.
tools.playwright.extract_hyperlinks.ExtractHyperlinksTool
Extract all hyperlinks on the page.
tools.playwright.extract_hyperlinks.ExtractHyperlinksToolInput
Input for ExtractHyperlinksTool.
tools.playwright.extract_text.ExtractTextTool
Create a new model by parsing and validating input data from keyword arguments.
tools.playwright.get_elements.GetElementsTool
Create a new model by parsing and validating input data from keyword arguments.
tools.playwright.get_elements.GetElementsToolInput
Input for GetElementsTool.
tools.playwright.navigate.NavigateTool
Create a new model by parsing and validating input data from keyword arguments.
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
Create a new model by parsing and validating input data from keyword arguments.
tools.plugin.AIPluginToolSchema
AIPLuginToolSchema.
tools.plugin.ApiConfig
Create a new model by parsing and validating input data from keyword arguments.
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 adds the capability to search using the PubMed API.
tools.python.tool.PythonAstREPLTool
A tool for running python code in a REPL.


A tool for running python code in a REPL.
tools.python.tool.PythonREPLTool
A tool for running python code in a REPL.
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 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.scenexplain.tool.SceneXplainInput
Input for SceneXplain.
tools.scenexplain.tool.SceneXplainTool
Tool that adds the capability to explain images.
tools.searx_search.tool.SearxSearchResults
Tool that has the capability to query a Searx instance and get back json.
tools.searx_search.tool.SearxSearchRun
Tool that adds the capability to query 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
Create a new model by parsing and validating input data from keyword arguments.
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 adds the capability to search using the Wikipedia API.
tools.wolfram_alpha.tool.WolframAlphaQueryRun
Tool that adds the capability to query using the Wolfram Alpha SDK.
tools.youtube.search.YouTubeSearchTool
Create a new model by parsing and validating input data from keyword arguments.
tools.zapier.tool.ZapierNLAListActions
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.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(...)


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.convert_to_openai.format_tool_to_openai_function(tool)
Format tool into the OpenAI function API.
tools.ddg_search.tool.DuckDuckGoSearchTool(...)
Deprecated.
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([...])
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.create_async_playwright_browser([...])
Create a 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)
param coro
The coroutine to run. Coroutine[Any, Any, T]
tools.plugin.marshal_spec(txt)


tools.plugin.marshal_spec(txt)
Convert the yaml or json serialized spec to a dict.
tools.python.tool.sanitize_input(query)
Sanitize input to the python REPL.
tools.steamship_image_generation.utils.make_image_public(...)
Upload a block to a signed URL and return the public URL.
langchain.utilities: Utilities¶
General utilities.
Classes¶
utilities.apify.ApifyWrapper
Wrapper around Apify.
utilities.arxiv.ArxivAPIWrapper
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
Create a new model by parsing and validating input data from keyword arguments.
utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper
Wrapper for DuckDuckGo Search API.
utilities.google_places_api.GooglePlacesAPIWrapper
Wrapper around Google Places 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 GraphQL API.
utilities.jira.JiraAPIWrapper
Wrapper for Jira API.
utilities.metaphor_search.MetaphorSearchAPIWrapper
Wrapper for Metaphor Search API.
utilities.openapi.HTTPVerb(value[, names, ...])
HTTP verbs.
utilities.openapi.OpenAPISpec
OpenAPI Model that removes misformatted parts of the spec.
utilities.openweathermap.OpenWeatherMapAPIWrapper
Wrapper for OpenWeatherMap API using PyOWM.
utilities.powerbi.PowerBIDataset
Create PowerBI engine from dataset ID and credential or token.
utilities.pupmed.PubMedAPIWrapper


utilities.pupmed.PubMedAPIWrapper
Wrapper around PubMed API.
utilities.python.PythonREPL
Simulates a standalone Python REPL.
utilities.scenexplain.SceneXplainAPIWrapper
Wrapper for SceneXplain API.
utilities.searx_search.SearxResults(data)
Dict like wrapper around search api results.
utilities.searx_search.SearxSearchWrapper
Wrapper for Searx API.
utilities.serpapi.SerpAPIWrapper
Wrapper around SerpAPI.
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.loading.try_load_from_hub(path, ...)
Load configuration from hub.
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.vertexai.init_vertexai([project, ...])
Init vertexai.
utilities.vertexai.raise_vertex_import_error()
Raise ImportError related to Vertex SDK being not available.
langchain.utils: Utils¶
Generic utility functions.
Functions¶
utils.comma_list(items)
utils.get_from_dict_or_env(data, key, env_key)
Get a value from a dictionary or an environment variable.
utils.get_from_env(key, env_key[, default])
Get a value from a dictionary or an environment variable.
utils.guard_import(module_name, *[, ...])
Dynamically imports a module and raises a helpful exception if the module is not installed.
utils.mock_now(dt_value)


utils.mock_now(dt_value)
Context manager for mocking out datetime.now() in unit tests. Example: with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):     assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11).
utils.raise_for_status_with_text(response)
Raise an error with the response text.
utils.stringify_dict(data)
Stringify a dictionary.
utils.stringify_value(val)
Stringify a value.
utils.xor_args(*arg_groups)
Validate specified keyword args are mutually exclusive.
langchain.vectorstores: Vectorstores¶
Wrappers on top of vector stores.
Classes¶
vectorstores.alibabacloud_opensearch.AlibabaCloudOpenSearch(...)
Alibaba Cloud OpenSearch Vector Store
vectorstores.analyticdb.AnalyticDB(...[, ...])
VectorStore implementation using AnalyticDB.
vectorstores.annoy.Annoy(embedding_function, ...)
Wrapper around Annoy vector database.
vectorstores.atlas.AtlasDB(name[, ...])
Wrapper around Atlas: Nomic's neural database and rhizomatic instrument.
vectorstores.awadb.AwaDB([table_name, ...])
Interface implemented by AwaDB vector stores.
vectorstores.azuresearch.AzureSearch(...[, ...])
Initialize with necessary components.
vectorstores.azuresearch.AzureSearchVectorStoreRetriever
Create a new model by parsing and validating input data from keyword arguments.
vectorstores.base.VectorStore()
Interface for vector stores.
vectorstores.base.VectorStoreRetriever
Create a new model by parsing and validating input data from keyword arguments.
vectorstores.cassandra.Cassandra(embedding, ...)
Wrapper around Cassandra embeddings platform.
vectorstores.chroma.Chroma([...])
Wrapper around ChromaDB embeddings platform.


vectorstores.chroma.Chroma([...])
Wrapper around ChromaDB embeddings platform.
vectorstores.clarifai.Clarifai([user_id, ...])
Wrapper around Clarifai AI platform's vector store.
vectorstores.clickhouse.Clickhouse(embedding)
Wrapper around ClickHouse vector database
vectorstores.clickhouse.ClickhouseSettings
ClickHouse Client Configuration
vectorstores.deeplake.DeepLake([...])
Wrapper around Deep Lake, a data lake for deep learning applications.
vectorstores.docarray.base.DocArrayIndex(...)
Initialize a vector store from DocArray's DocIndex.
vectorstores.docarray.hnsw.DocArrayHnswSearch(...)
Wrapper around HnswLib storage.
vectorstores.docarray.in_memory.DocArrayInMemorySearch(...)
Wrapper around in-memory storage for exact search.
vectorstores.elastic_vector_search.ElasticKnnSearch(...)
A class for performing k-Nearest Neighbors (k-NN) search on an Elasticsearch index.
vectorstores.elastic_vector_search.ElasticVectorSearch(...)
Wrapper around Elasticsearch as a vector database.
vectorstores.faiss.FAISS(embedding_function, ...)
Wrapper around FAISS vector database.
vectorstores.hologres.Hologres(...[, ndims, ...])
VectorStore implementation using Hologres.
vectorstores.lancedb.LanceDB(connection, ...)
Wrapper around LanceDB vector database.
vectorstores.matching_engine.MatchingEngine(...)
Vertex Matching Engine implementation of the vector store.
vectorstores.milvus.Milvus(embedding_function)
Wrapper around the Milvus vector database.
vectorstores.mongodb_atlas.MongoDBAtlasVectorSearch(...)
Wrapper around MongoDB Atlas Vector Search.
vectorstores.myscale.MyScale(embedding[, config])
Wrapper around MyScale vector database
vectorstores.myscale.MyScaleSettings
MyScale Client Configuration


Wrapper around MyScale vector database
vectorstores.myscale.MyScaleSettings
MyScale Client Configuration
vectorstores.opensearch_vector_search.OpenSearchVectorSearch(...)
Wrapper around OpenSearch as a vector database.
vectorstores.pinecone.Pinecone(index, ...[, ...])
Wrapper around Pinecone vector database.
vectorstores.qdrant.Qdrant(client, ...[, ...])
Wrapper around Qdrant vector database.
vectorstores.redis.Redis(redis_url, ...)
Wrapper around Redis vector database.
vectorstores.redis.RedisVectorStoreRetriever
Create a new model by parsing and validating input data from keyword arguments.
vectorstores.rocksetdb.Rockset(client, ...)
Wrapper arpund Rockset vector database.
vectorstores.singlestoredb.DistanceStrategy(value)
Enumerator of the Distance strategies for SingleStoreDB.
vectorstores.singlestoredb.SingleStoreDB(...)
This class serves as a Pythonic interface to the SingleStore DB database.
vectorstores.singlestoredb.SingleStoreDBRetriever
Retriever for SingleStoreDB vector stores.
vectorstores.sklearn.BaseSerializer(persist_path)
Abstract base class for saving and loading 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(...)
A simple in-memory vector store based on the scikit-learn library NearestNeighbors implementation.
vectorstores.sklearn.SKLearnVectorStoreException
Exception raised by SKLearnVectorStore.
vectorstores.starrocks.StarRocks(embedding)
Wrapper around StarRocks vector database


Wrapper around StarRocks vector database
vectorstores.starrocks.StarRocksSettings
StarRocks Client Configuration
vectorstores.supabase.SupabaseVectorStore(...)
VectorStore for a Supabase postgres database.
vectorstores.tair.Tair(embedding_function, ...)
Wrapper around Tair Vector store.
vectorstores.tigris.Tigris(client, ...)
Initialize Tigris vector store
vectorstores.typesense.Typesense(...[, ...])
Wrapper around Typesense vector search.
vectorstores.vectara.Vectara([...])
Implementation of Vector Store using Vectara (https://vectara.com).
vectorstores.vectara.VectaraRetriever
Create a new model by parsing and validating input data from keyword arguments.
vectorstores.weaviate.Weaviate(client, ...)
Wrapper around Weaviate vector database.
vectorstores.zilliz.Zilliz(embedding_function)
Initialize wrapper around the milvus vector database.
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.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.


Check if a string has multiple substrings.
vectorstores.utils.maximal_marginal_relevance(...)
Calculate maximal marginal relevance.


langchain.retrievers.zep.ZepRetriever¶
class langchain.retrievers.zep.ZepRetriever(session_id: str, url: str, api_key: Optional[str] = None, top_k: Optional[int] = None)[source]¶
Bases: BaseRetriever
A Retriever implementation for the Zep long-term memory store. Search your
user’s long-term chat history with Zep.
Note: You will need to provide the user’s session_id to use this retriever.
More on Zep:
Zep provides long-term conversation storage for LLM apps. The server stores,
summarizes, embeds, indexes, and enriches conversational AI chat
histories, and exposes them via simple, low-latency APIs.
For server installation instructions, see:
https://docs.getzep.com/deployment/quickstart/
Methods
__init__(session_id, url[, api_key, top_k])
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.metal.MetalRetriever¶
class langchain.retrievers.metal.MetalRetriever(client: Any, params: Optional[dict] = None)[source]¶
Bases: BaseRetriever
Retriever that uses the Metal API.
Methods
__init__(client[, params])
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.pinecone_hybrid_search.create_index¶
langchain.retrievers.pinecone_hybrid_search.create_index(contexts: List[str], index: Any, embeddings: Embeddings, sparse_encoder: Any, ids: Optional[List[str]] = None, metadatas: Optional[List[dict]] = None) → None[source]¶
Create a Pinecone index from a list of contexts.
Modifies the index argument in-place.
Parameters
contexts – List of contexts to embed.
index – Pinecone index to use.
embeddings – Embeddings model to use.
sparse_encoder – Sparse encoder to use.
ids – List of ids to use for the documents.
metadatas – List of metadata to use for the documents.


langchain.retrievers.kendra.TextWithHighLights¶
class langchain.retrievers.kendra.TextWithHighLights(*, Text: str, Highlights: Optional[Any] = None, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param Highlights: Optional[Any] = None¶
param Text: str [Required]¶


langchain.retrievers.zilliz.ZillizRetriever¶
class langchain.retrievers.zilliz.ZillizRetriever(embedding_function: Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[Dict[str, Any]] = None, consistency_level: str = 'Session', search_params: Optional[dict] = None)[source]¶
Bases: BaseRetriever
Retriever that uses the Zilliz API.
Methods
__init__(embedding_function[, ...])
add_texts(texts[, metadatas])
Add text to the Zilliz store
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
add_texts(texts: List[str], metadatas: Optional[List[dict]] = None) → None[source]¶
Add text to the Zilliz store
Parameters
texts (List[str]) – The text
metadatas (List[dict]) – Metadata dicts, must line up with existing store
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.kendra.AdditionalResultAttributeValue¶
class langchain.retrievers.kendra.AdditionalResultAttributeValue(*, TextWithHighlightsValue: TextWithHighLights, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param TextWithHighlightsValue: langchain.retrievers.kendra.TextWithHighLights [Required]¶


langchain.retrievers.document_compressors.chain_filter.default_get_input¶
langchain.retrievers.document_compressors.chain_filter.default_get_input(query: str, doc: Document) → Dict[str, Any][source]¶
Return the compression chain input.


langchain.retrievers.multi_query.LineListOutputParser¶
class langchain.retrievers.multi_query.LineListOutputParser[source]¶
Bases: PydanticOutputParser
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param pydantic_object: Type[langchain.output_parsers.pydantic.T] [Required]¶
dict(**kwargs: Any) → Dict¶
Return dictionary representation of output parser.
get_format_instructions() → str¶
Instructions on how the LLM output should be formatted.
parse(text: str) → LineList[source]¶
Parse the output of an LLM call.
A method which takes in a string (assumed output of a language model )
and parses it into some structure.
Parameters
text – output of language model
Returns
structured output
parse_result(result: List[Generation]) → T¶
Parse LLM Result.
parse_with_prompt(completion: str, prompt: PromptValue) → Any¶
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion – output of language model
prompt – prompt value
Returns
structured output
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
property lc_attributes: Dict¶
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]¶
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]


eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]¶
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool¶
Return whether or not the class is serializable.
model Config¶
Bases: object
extra = 'ignore'¶


langchain.retrievers.kendra.combined_text¶
langchain.retrievers.kendra.combined_text(title: str, excerpt: str) → str[source]¶


langchain.retrievers.wikipedia.WikipediaRetriever¶
class langchain.retrievers.wikipedia.WikipediaRetriever(*, wiki_client: Any = None, top_k_results: int = 3, lang: str = 'en', load_all_available_meta: bool = False, doc_content_chars_max: int = 4000)[source]¶
Bases: BaseRetriever, WikipediaAPIWrapper
It is effectively a wrapper for WikipediaAPIWrapper.
It wraps load() to get_relevant_documents().
It uses all WikipediaAPIWrapper arguments without any change.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param doc_content_chars_max: int = 4000¶
param lang: str = 'en'¶
param load_all_available_meta: bool = False¶
param top_k_results: int = 3¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
load(query: str) → List[Document]¶
Run Wikipedia search and get the article text plus the meta information.
See
Returns: a list of documents.
run(query: str) → str¶
Run Wikipedia search and get page summaries.
validator validate_environment  »  all fields¶
Validate that the python package exists in environment.


validator validate_environment  »  all fields¶
Validate that the python package exists in environment.
model Config¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.retrievers.self_query.myscale.MyScaleTranslator¶
class langchain.retrievers.self_query.myscale.MyScaleTranslator(metadata_key: str = 'metadata')[source]¶
Bases: Visitor
Logic for converting internal query language elements to valid filters.
Methods
__init__([metadata_key])
visit_comparison(comparison)
Translate a Comparison.
visit_operation(operation)
Translate an Operation.
visit_structured_query(structured_query)
Translate a StructuredQuery.
Attributes
allowed_comparators
allowed_operators
Subset of allowed logical operators.
map_dict
visit_comparison(comparison: Comparison) → Dict[source]¶
Translate a Comparison.
visit_operation(operation: Operation) → Dict[source]¶
Translate an Operation.
visit_structured_query(structured_query: StructuredQuery) → Tuple[str, dict][source]¶
Translate a StructuredQuery.
allowed_comparators: Optional[Sequence[Comparator]] = [<Comparator.EQ: 'eq'>, <Comparator.GT: 'gt'>, <Comparator.GTE: 'gte'>, <Comparator.LT: 'lt'>, <Comparator.LTE: 'lte'>, <Comparator.CONTAIN: 'contain'>, <Comparator.LIKE: 'like'>]¶
allowed_operators: Optional[Sequence[Operator]] = [<Operator.AND: 'and'>, <Operator.OR: 'or'>, <Operator.NOT: 'not'>]¶
Subset of allowed logical operators.


Subset of allowed logical operators.
map_dict = {Operator.AND: <function DEFAULT_COMPOSER.<locals>.f>, Comparator.CONTAIN: <function FUNCTION_COMPOSER.<locals>.f>, Comparator.EQ: <function DEFAULT_COMPOSER.<locals>.f>, Comparator.GT: <function DEFAULT_COMPOSER.<locals>.f>, Comparator.GTE: <function DEFAULT_COMPOSER.<locals>.f>, Comparator.LIKE: <function DEFAULT_COMPOSER.<locals>.f>, Comparator.LT: <function DEFAULT_COMPOSER.<locals>.f>, Comparator.LTE: <function DEFAULT_COMPOSER.<locals>.f>, Operator.NOT: <function DEFAULT_COMPOSER.<locals>.f>, Operator.OR: <function DEFAULT_COMPOSER.<locals>.f>}¶


langchain.retrievers.document_compressors.chain_extract.default_get_input¶
langchain.retrievers.document_compressors.chain_extract.default_get_input(query: str, doc: Document) → Dict[str, Any][source]¶
Return the compression chain input.


langchain.retrievers.kendra.DocumentAttribute¶
class langchain.retrievers.kendra.DocumentAttribute(*, Key: str, Value: DocumentAttributeValue, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param Key: str [Required]¶
param Value: langchain.retrievers.kendra.DocumentAttributeValue [Required]¶


langchain.retrievers.pinecone_hybrid_search.hash_text¶
langchain.retrievers.pinecone_hybrid_search.hash_text(text: str) → str[source]¶
Hash a text using SHA256.
Parameters
text – Text to hash.
Returns
Hashed text.


langchain.retrievers.self_query.base.SelfQueryRetriever¶
class langchain.retrievers.self_query.base.SelfQueryRetriever(*, vectorstore: VectorStore, llm_chain: LLMChain, search_type: str = 'similarity', search_kwargs: dict = None, structured_query_translator: Visitor, verbose: bool = False, use_original_query: bool = False)[source]¶
Bases: BaseRetriever, BaseModel
Retriever that wraps around a vector store and uses an LLM to generate
the vector store queries.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param llm_chain: langchain.chains.llm.LLMChain [Required]¶
The LLMChain for generating the vector store queries.
param search_kwargs: dict [Optional]¶
Keyword arguments to pass in to the vector store search.
param search_type: str = 'similarity'¶
The search type to perform on the vector store.
param structured_query_translator: langchain.chains.query_constructor.ir.Visitor [Required]¶
Translator for turning internal query language into vectorstore search params.
param use_original_query: bool = False¶
param vectorstore: langchain.vectorstores.base.VectorStore [Required]¶
The underlying vector store from which documents will be retrieved.
param verbose: bool = False¶
Use original query instead of the revised new query from LLM
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod from_llm(llm: BaseLanguageModel, vectorstore: VectorStore, document_contents: str, metadata_field_info: List[AttributeInfo], structured_query_translator: Optional[Visitor] = None, chain_kwargs: Optional[Dict] = None, enable_limit: bool = False, use_original_query: bool = False, **kwargs: Any) → SelfQueryRetriever[source]¶
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
validator validate_translator  »  all fields[source]¶
Validate translator.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.llama_index.LlamaIndexRetriever¶
class langchain.retrievers.llama_index.LlamaIndexRetriever(*, index: Any = None, query_kwargs: Dict = None)[source]¶
Bases: BaseRetriever, BaseModel
Question-answering with sources over an LlamaIndex data structure.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param index: Any = None¶
param query_kwargs: Dict [Optional]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.contextual_compression.ContextualCompressionRetriever¶
class langchain.retrievers.contextual_compression.ContextualCompressionRetriever(*, base_compressor: BaseDocumentCompressor, base_retriever: BaseRetriever)[source]¶
Bases: BaseRetriever, BaseModel
Retriever that wraps a base retriever and compresses the results.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param base_compressor: langchain.retrievers.document_compressors.base.BaseDocumentCompressor [Required]¶
Compressor for compressing retrieved documents.
param base_retriever: langchain.schema.BaseRetriever [Required]¶
Base Retriever to use for getting relevant documents.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶


langchain.retrievers.llama_index.LlamaIndexGraphRetriever¶
class langchain.retrievers.llama_index.LlamaIndexGraphRetriever(*, graph: Any = None, query_configs: List[Dict] = None)[source]¶
Bases: BaseRetriever, BaseModel
Question-answering with sources over an LlamaIndex graph data structure.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param graph: Any = None¶
param query_configs: List[Dict] [Optional]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.document_compressors.cohere_rerank.CohereRerank¶
class langchain.retrievers.document_compressors.cohere_rerank.CohereRerank(*, client: Client, top_n: int = 3, model: str = 'rerank-english-v2.0')[source]¶
Bases: BaseDocumentCompressor
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param client: Client [Required]¶
param model: str = 'rerank-english-v2.0'¶
param top_n: int = 3¶
async acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress retrieved documents given the query context.
compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress retrieved documents given the query context.
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶


langchain.retrievers.kendra.clean_excerpt¶
langchain.retrievers.kendra.clean_excerpt(excerpt: str) → str[source]¶


langchain.retrievers.milvus.MilvusRetreiver¶
langchain.retrievers.milvus.MilvusRetreiver(*args: Any, **kwargs: Any) → MilvusRetriever[source]¶
Deprecated MilvusRetreiver. Please use MilvusRetriever (‘i’ before ‘e’) instead.
Parameters
*args –
**kwargs –
Returns
MilvusRetriever


langchain.retrievers.docarray.DocArrayRetriever¶
class langchain.retrievers.docarray.DocArrayRetriever(*, index: Any = None, embeddings: Embeddings, search_field: str, content_field: str, search_type: SearchType = SearchType.similarity, top_k: int = 1, filters: Optional[Any] = None)[source]¶
Bases: BaseRetriever, BaseModel
Retriever class for DocArray Document Indices.
Currently, supports 5 backends:
InMemoryExactNNIndex, HnswDocumentIndex, QdrantDocumentIndex,
ElasticDocIndex, and WeaviateDocumentIndex.
Parameters
index – One of the above-mentioned index instances
embeddings – Embedding model to represent text as vectors
search_field – Field to consider for searching in the documents.
Should be an embedding/vector/tensor.
content_field – Field that represents the main content in your document schema.
Will be used as a page_content. Everything else will go into metadata.
search_type – Type of search to perform (similarity / mmr)
filters – Filters applied for document retrieval.
top_k – Number of documents to return
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param content_field: str [Required]¶
param embeddings: langchain.embeddings.base.Embeddings [Required]¶
param filters: Optional[Any] = None¶
param index: Any = None¶
param search_field: str [Required]¶
param search_type: langchain.retrievers.docarray.SearchType = SearchType.similarity¶
param top_k: int = 1¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶


Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.document_compressors.chain_extract.NoOutputParser¶
class langchain.retrievers.document_compressors.chain_extract.NoOutputParser(*, no_output_str: str = 'NO_OUTPUT')[source]¶
Bases: BaseOutputParser[str]
Parse outputs that could return a null string of some sort.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param no_output_str: str = 'NO_OUTPUT'¶
dict(**kwargs: Any) → Dict¶
Return dictionary representation of output parser.
get_format_instructions() → str¶
Instructions on how the LLM output should be formatted.
parse(text: str) → str[source]¶
Parse the output of an LLM call.
A method which takes in a string (assumed output of a language model )
and parses it into some structure.
Parameters
text – output of language model
Returns
structured output
parse_result(result: List[Generation]) → T¶
Parse LLM Result.
parse_with_prompt(completion: str, prompt: PromptValue) → Any¶
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion – output of language model
prompt – prompt value
Returns
structured output
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
property lc_attributes: Dict¶
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]¶
Return the namespace of the langchain object.


property lc_namespace: List[str]¶
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]¶
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool¶
Return whether or not the class is serializable.
model Config¶
Bases: object
extra = 'ignore'¶


langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever¶
class langchain.retrievers.time_weighted_retriever.TimeWeightedVectorStoreRetriever(*, vectorstore: VectorStore, search_kwargs: dict = None, memory_stream: List[Document] = None, decay_rate: float = 0.01, k: int = 4, other_score_keys: List[str] = [], default_salience: Optional[float] = None)[source]¶
Bases: BaseRetriever, BaseModel
Retriever combining embedding similarity with recency.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param decay_rate: float = 0.01¶
The exponential decay factor used as (1.0-decay_rate)**(hrs_passed).
param default_salience: Optional[float] = None¶
The salience to assign memories not retrieved from the vector store.
None assigns no salience to documents not fetched from the vector store.
param k: int = 4¶
The maximum number of documents to retrieve in a given call.
param memory_stream: List[langchain.schema.Document] [Optional]¶
The memory_stream of documents to search through.
param other_score_keys: List[str] = []¶
Other keys in the metadata to factor into the score, e.g. ‘importance’.
param search_kwargs: dict [Optional]¶
Keyword arguments to pass to the vectorstore similarity search.
param vectorstore: langchain.vectorstores.base.VectorStore [Required]¶
The vectorstore to store documents and determine salience.
async aadd_documents(documents: List[Document], **kwargs: Any) → List[str][source]¶
Add documents to vectorstore.


Add documents to vectorstore.
add_documents(documents: List[Document], **kwargs: Any) → List[str][source]¶
Add documents to vectorstore.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_salient_docs(query: str) → Dict[int, Tuple[Document, float]][source]¶
Return documents that are salient to the query.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.kendra.AdditionalResultAttribute¶
class langchain.retrievers.kendra.AdditionalResultAttribute(*, Key: str, ValueType: Literal['TEXT_WITH_HIGHLIGHTS_VALUE'], Value: AdditionalResultAttributeValue, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param Key: str [Required]¶
param Value: langchain.retrievers.kendra.AdditionalResultAttributeValue [Required]¶
param ValueType: Literal['TEXT_WITH_HIGHLIGHTS_VALUE'] [Required]¶
get_value_text() → str[source]¶


langchain.retrievers.kendra.RetrieveResultItem¶
class langchain.retrievers.kendra.RetrieveResultItem(*, Content: Optional[str] = None, DocumentAttributes: Optional[List[DocumentAttribute]] = [], DocumentId: Optional[str] = None, DocumentTitle: Optional[str] = None, DocumentURI: Optional[str] = None, Id: Optional[str] = None, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param Content: Optional[str] = None¶
param DocumentAttributes: Optional[List[langchain.retrievers.kendra.DocumentAttribute]] = []¶
param DocumentId: Optional[str] = None¶
param DocumentTitle: Optional[str] = None¶
param DocumentURI: Optional[str] = None¶
param Id: Optional[str] = None¶
get_excerpt() → str[source]¶
to_doc() → Document[source]¶


langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever¶
class langchain.retrievers.chatgpt_plugin_retriever.ChatGPTPluginRetriever(*, url: str, bearer_token: str, top_k: int = 3, filter: Optional[dict] = None, aiosession: Optional[ClientSession] = None)[source]¶
Bases: BaseRetriever, BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
param bearer_token: str [Required]¶
param filter: Optional[dict] = None¶
param top_k: int = 3¶
param url: str [Required]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor¶
class langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor(*, llm_chain: ~langchain.chains.llm.LLMChain, get_input: ~typing.Callable[[str, ~langchain.schema.Document], dict] = <function default_get_input>)[source]¶
Bases: BaseDocumentCompressor
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input>¶
Callable for constructing the chain input from the query and a Document.
param llm_chain: langchain.chains.llm.LLMChain [Required]¶
LLM wrapper to use for compressing documents.
async acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress page content of raw documents asynchronously.
compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress page content of raw documents.
classmethod from_llm(llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, get_input: Optional[Callable[[str, Document], str]] = None, llm_chain_kwargs: Optional[dict] = None) → LLMChainExtractor[source]¶
Initialize from LLM.


langchain.retrievers.self_query.weaviate.WeaviateTranslator¶
class langchain.retrievers.self_query.weaviate.WeaviateTranslator[source]¶
Bases: Visitor
Logic for converting internal query language elements to valid filters.
Methods
__init__()
visit_comparison(comparison)
Translate a Comparison.
visit_operation(operation)
Translate an Operation.
visit_structured_query(structured_query)
Translate a StructuredQuery.
Attributes
allowed_comparators
allowed_operators
Subset of allowed logical operators.
visit_comparison(comparison: Comparison) → Dict[source]¶
Translate a Comparison.
visit_operation(operation: Operation) → Dict[source]¶
Translate an Operation.
visit_structured_query(structured_query: StructuredQuery) → Tuple[str, dict][source]¶
Translate a StructuredQuery.
allowed_comparators: Optional[Sequence[Comparator]] = [<Comparator.EQ: 'eq'>]¶
allowed_operators: Optional[Sequence[Operator]] = [<Operator.AND: 'and'>, <Operator.OR: 'or'>]¶
Subset of allowed logical operators.


langchain.retrievers.svm.create_index¶
langchain.retrievers.svm.create_index(contexts: List[str], embeddings: Embeddings) → ndarray[source]¶
Create an index of embeddings for a list of contexts.
:param contexts: List of contexts to embed.
:param embeddings: Embeddings model to use.
Returns
Index of embeddings.


langchain.retrievers.self_query.qdrant.QdrantTranslator¶
class langchain.retrievers.self_query.qdrant.QdrantTranslator(metadata_key: str)[source]¶
Bases: Visitor
Logic for converting internal query language elements to valid filters.
Methods
__init__(metadata_key)
visit_comparison(comparison)
Translate a Comparison.
visit_operation(operation)
Translate an Operation.
visit_structured_query(structured_query)
Translate a StructuredQuery.
Attributes
allowed_comparators
allowed_operators
visit_comparison(comparison: Comparison) → rest.FieldCondition[source]¶
Translate a Comparison.
visit_operation(operation: Operation) → rest.Filter[source]¶
Translate an Operation.
visit_structured_query(structured_query: StructuredQuery) → Tuple[str, dict][source]¶
Translate a StructuredQuery.
allowed_comparators: Optional[Sequence[Comparator]] = None¶
allowed_operators: Optional[Sequence[Operator]] = None¶


langchain.retrievers.document_compressors.base.BaseDocumentCompressor¶
class langchain.retrievers.document_compressors.base.BaseDocumentCompressor[source]¶
Bases: BaseModel, ABC
Base abstraction interface for document compression.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
abstract async acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress retrieved documents given the query context.
abstract compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress retrieved documents given the query context.


langchain.retrievers.document_compressors.chain_filter.LLMChainFilter¶
class langchain.retrievers.document_compressors.chain_filter.LLMChainFilter(*, llm_chain: ~langchain.chains.llm.LLMChain, get_input: ~typing.Callable[[str, ~langchain.schema.Document], dict] = <function default_get_input>)[source]¶
Bases: BaseDocumentCompressor
Filter that drops documents that aren’t relevant to the query.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input>¶
Callable for constructing the chain input from the query and a Document.
param llm_chain: langchain.chains.llm.LLMChain [Required]¶
LLM wrapper to use for filtering documents.
The chain prompt is expected to have a BooleanOutputParser.
async acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Filter down documents.
compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Filter down documents based on their relevance to the query.
classmethod from_llm(llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) → LLMChainFilter[source]¶


langchain.retrievers.document_compressors.base.DocumentCompressorPipeline¶
class langchain.retrievers.document_compressors.base.DocumentCompressorPipeline(*, transformers: List[Union[BaseDocumentTransformer, BaseDocumentCompressor]])[source]¶
Bases: BaseDocumentCompressor
Document compressor that uses a pipeline of transformers.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param transformers: List[Union[langchain.schema.BaseDocumentTransformer, langchain.retrievers.document_compressors.base.BaseDocumentCompressor]] [Required]¶
List of document filters that are chained together and run in sequence.
async acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Compress retrieved documents given the query context.
compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Transform a list of documents.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.multi_query.LineList¶
class langchain.retrievers.multi_query.LineList(*, lines: List[str])[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param lines: List[str] [Required]¶
Lines of text


langchain.retrievers.kendra.DocumentAttributeValue¶
class langchain.retrievers.kendra.DocumentAttributeValue(*, DateValue: Optional[str] = None, LongValue: Optional[int] = None, StringListValue: Optional[List[str]] = None, StringValue: Optional[str] = None, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param DateValue: Optional[str] = None¶
param LongValue: Optional[int] = None¶
param StringListValue: Optional[List[str]] = None¶
param StringValue: Optional[str] = None¶


langchain.retrievers.remote_retriever.RemoteLangChainRetriever¶
class langchain.retrievers.remote_retriever.RemoteLangChainRetriever(*, url: str, headers: Optional[dict] = None, input_key: str = 'message', response_key: str = 'response', page_content_key: str = 'page_content', metadata_key: str = 'metadata')[source]¶
Bases: BaseRetriever, BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param headers: Optional[dict] = None¶
param input_key: str = 'message'¶
param metadata_key: str = 'metadata'¶
param page_content_key: str = 'page_content'¶
param response_key: str = 'response'¶
param url: str [Required]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.databerry.DataberryRetriever¶
class langchain.retrievers.databerry.DataberryRetriever(datastore_url: str, top_k: Optional[int] = None, api_key: Optional[str] = None)[source]¶
Bases: BaseRetriever
Retriever that uses the Databerry API.
Methods
__init__(datastore_url[, top_k, api_key])
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
Attributes
datastore_url
top_k
api_key
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
api_key: Optional[str]¶
datastore_url: str¶
top_k: Optional[int]¶


langchain.retrievers.docarray.SearchType¶
class langchain.retrievers.docarray.SearchType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases: str, Enum
Enumerator of the types of search to perform.
Methods
__init__(*args, **kwds)
capitalize()
Return a capitalized version of the string.
casefold()
Return a version of the string suitable for caseless comparisons.
center(width[, fillchar])
Return a centered string of length width.
count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
encode([encoding, errors])
Encode the string using the codec registered for encoding.
endswith(suffix[, start[, end]])
Return True if S ends with the specified suffix, False otherwise.
expandtabs([tabsize])
Return a copy where all tab characters are expanded using spaces.
find(sub[, start[, end]])
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
format(*args, **kwargs)
Return a formatted version of S, using substitutions from args and kwargs.
format_map(mapping)
Return a formatted version of S, using substitutions from mapping.
index(sub[, start[, end]])
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
isalpha()
Return True if the string is an alphabetic string, False otherwise.
isascii()
Return True if all characters in the string are ASCII, False otherwise.
isdecimal()
Return True if the string is a decimal string, False otherwise.


isdecimal()
Return True if the string is a decimal string, False otherwise.
isdigit()
Return True if the string is a digit string, False otherwise.
isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
islower()
Return True if the string is a lowercase string, False otherwise.
isnumeric()
Return True if the string is a numeric string, False otherwise.
isprintable()
Return True if the string is printable, False otherwise.
isspace()
Return True if the string is a whitespace string, False otherwise.
istitle()
Return True if the string is a title-cased string, False otherwise.
isupper()
Return True if the string is an uppercase string, False otherwise.
join(iterable, /)
Concatenate any number of strings.
ljust(width[, fillchar])
Return a left-justified string of length width.
lower()
Return a copy of the string converted to lowercase.
lstrip([chars])
Return a copy of the string with leading whitespace removed.
maketrans
Return a translation table usable for str.translate().
partition(sep, /)
Partition the string into three parts using the given separator.
removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
replace(old, new[, count])
Return a copy with all occurrences of substring old replaced by new.
rfind(sub[, start[, end]])
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
rindex(sub[, start[, end]])
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].


rjust(width[, fillchar])
Return a right-justified string of length width.
rpartition(sep, /)
Partition the string into three parts using the given separator.
rsplit([sep, maxsplit])
Return a list of the substrings in the string, using sep as the separator string.
rstrip([chars])
Return a copy of the string with trailing whitespace removed.
split([sep, maxsplit])
Return a list of the substrings in the string, using sep as the separator string.
splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries.
startswith(prefix[, start[, end]])
Return True if S starts with the specified prefix, False otherwise.
strip([chars])
Return a copy of the string with leading and trailing whitespace removed.
swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
title()
Return a version of the string where each word is titlecased.
translate(table, /)
Replace each character in the string using the given translation table.
upper()
Return a copy of the string converted to uppercase.
zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
Attributes
similarity
mmr
capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
casefold()¶
Return a version of the string suitable for caseless comparisons.
center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
count(sub[, start[, end]]) → int¶
Return the number of non-overlapping occurrences of substring sub in


Return the number of non-overlapping occurrences of substring sub in
string S[start:end].  Optional arguments start and end are
interpreted as in slice notation.
encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
encodingThe encoding in which to encode the string.
errorsThe error handling scheme to use for encoding errors.
The default is ‘strict’ meaning that encoding errors raise a
UnicodeEncodeError.  Other possible values are ‘ignore’, ‘replace’ and
‘xmlcharrefreplace’ as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
endswith(suffix[, start[, end]]) → bool¶
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
find(sub[, start[, end]]) → int¶
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
format(*args, **kwargs) → str¶
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces (‘{’ and ‘}’).
format_map(mapping) → str¶
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces (‘{’ and ‘}’).
index(sub[, start[, end]]) → int¶
Return the lowest index in S where substring sub is found,


Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and
there is at least one character in the string.
isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there
is at least one character in the string.
isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F.
Empty string is ASCII too.
isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and
there is at least one character in the string.
isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there
is at least one character in the string.
isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
such as “def” or “class”.
islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and
there is at least one cased character in the string.
isnumeric()¶
Return True if the string is a numeric string, False otherwise.


isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at
least one character in the string.
isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in
repr() or if it is empty.
isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there
is at least one character in the string.
istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only
follow uncased characters and lowercase characters only cased ones.
isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and
there is at least one cased character in the string.
join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
lower()¶
Return a copy of the string converted to lowercase.
lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
static maketrans()¶
Return a translation table usable for str.translate().


static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string.  If the separator is found,
returns a 3-tuple containing the part before the separator, the separator
itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string
and two empty strings.
removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string.
removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string.
replace(old, new, count=- 1, /)¶
Return a copy with all occurrences of substring old replaced by new.
countMaximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
rfind(sub[, start[, end]]) → int¶


replaced.
rfind(sub[, start[, end]]) → int¶
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
rindex(sub[, start[, end]]) → int¶
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If
the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings
and the original string.
rsplit(sep=None, maxsplit=- 1)¶
Return a list of the substrings in the string, using sep as the separator string.
sepThe separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \n \r \t \f and spaces) and will discard
empty strings from the result.
maxsplitMaximum number of splits (starting from the left).
-1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.


rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
split(sep=None, maxsplit=- 1)¶
Return a list of the substrings in the string, using sep as the separator string.
sepThe separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \n \r \t \f and spaces) and will discard
empty strings from the result.
maxsplitMaximum number of splits (starting from the left).
-1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally
delimited.  With natural text that includes punctuation, consider using
the regular expression module.
splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and
true.
startswith(prefix[, start[, end]]) → bool¶
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining
cased characters have lower case.
translate(table, /)¶
Replace each character in the string using the given translation table.


translate(table, /)¶
Replace each character in the string using the given translation table.
tableTranslation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list.  If this operation raises LookupError, the character is
left untouched.  Characters mapped to None are deleted.
upper()¶
Return a copy of the string converted to uppercase.
zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
mmr = 'mmr'¶
similarity = 'similarity'¶


langchain.retrievers.kendra.AmazonKendraRetriever¶
class langchain.retrievers.kendra.AmazonKendraRetriever(index_id: str, region_name: Optional[str] = None, credentials_profile_name: Optional[str] = None, top_k: int = 3, attribute_filter: Optional[Dict] = None, client: Optional[Any] = None)[source]¶
Bases: BaseRetriever
Retriever class to query documents from Amazon Kendra Index.
Parameters
index_id – Kendra index id
region_name – The aws region e.g., us-west-2.
Fallsback to AWS_DEFAULT_REGION env variable
or region specified in ~/.aws/config.
credentials_profile_name – The name of the profile in the ~/.aws/credentials
or ~/.aws/config files, which has either access keys or role information
specified. If not specified, the default credential profile or, if on an
EC2 instance, credentials from IMDS will be used.
top_k – No of results to return
attribute_filter – Additional filtering of results based on metadata
See: https://docs.aws.amazon.com/kendra/latest/APIReference
client – boto3 client for Kendra
Example
retriever = AmazonKendraRetriever(
    index_id="c0806df7-e76b-4bce-9b5c-d5582f6b1a03"
)
Methods
__init__(index_id[, region_name, ...])
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶


Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever¶
class langchain.retrievers.azure_cognitive_search.AzureCognitiveSearchRetriever(*, service_name: str = '', index_name: str = '', api_key: str = '', api_version: str = '2020-06-30', aiosession: Optional[ClientSession] = None, content_key: str = 'content')[source]¶
Bases: BaseRetriever, BaseModel
Wrapper around Azure Cognitive Search.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
ClientSession, in case we want to reuse connection for better performance.
param api_key: str = ''¶
API Key. Both Admin and Query keys work, but for reading data it’s
recommended to use a Query key.
param api_version: str = '2020-06-30'¶
API version
param content_key: str = 'content'¶
Key in a retrieved result to set as the Document page_content.
param index_name: str = ''¶
Name of Index inside Azure Cognitive Search service
param service_name: str = ''¶
Name of Azure Cognitive Search service
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for


Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
validator validate_environment  »  all fields[source]¶
Validate that service name, index name and api key exists in environment.
model Config[source]¶
Bases: object
arbitrary_types_allowed = True¶
extra = 'forbid'¶


langchain.retrievers.self_query.pinecone.PineconeTranslator¶
class langchain.retrievers.self_query.pinecone.PineconeTranslator[source]¶
Bases: Visitor
Logic for converting internal query language elements to valid filters.
Methods
__init__()
visit_comparison(comparison)
Translate a Comparison.
visit_operation(operation)
Translate an Operation.
visit_structured_query(structured_query)
Translate a StructuredQuery.
Attributes
allowed_comparators
allowed_operators
Subset of allowed logical operators.
visit_comparison(comparison: Comparison) → Dict[source]¶
Translate a Comparison.
visit_operation(operation: Operation) → Dict[source]¶
Translate an Operation.
visit_structured_query(structured_query: StructuredQuery) → Tuple[str, dict][source]¶
Translate a StructuredQuery.
allowed_comparators: Optional[Sequence[Comparator]] = None¶
allowed_operators: Optional[Sequence[Operator]] = [<Operator.AND: 'and'>, <Operator.OR: 'or'>]¶
Subset of allowed logical operators.


langchain.retrievers.kendra.QueryResultItem¶
class langchain.retrievers.kendra.QueryResultItem(*, DocumentId: str, DocumentTitle: TextWithHighLights, DocumentURI: Optional[str] = None, FeedbackToken: Optional[str] = None, Format: Optional[str] = None, Id: Optional[str] = None, Type: Optional[str] = None, AdditionalAttributes: Optional[List[AdditionalResultAttribute]] = [], DocumentExcerpt: Optional[TextWithHighLights] = None, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param AdditionalAttributes: Optional[List[langchain.retrievers.kendra.AdditionalResultAttribute]] = []¶
param DocumentExcerpt: Optional[langchain.retrievers.kendra.TextWithHighLights] = None¶
param DocumentId: str [Required]¶
param DocumentTitle: langchain.retrievers.kendra.TextWithHighLights [Required]¶
param DocumentURI: Optional[str] = None¶
param FeedbackToken: Optional[str] = None¶
param Format: Optional[str] = None¶
param Id: Optional[str] = None¶
param Type: Optional[str] = None¶
get_attribute_value() → str[source]¶
get_excerpt() → str[source]¶
to_doc() → Document[source]¶


langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter¶
class langchain.retrievers.document_compressors.embeddings_filter.EmbeddingsFilter(*, embeddings: ~langchain.embeddings.base.Embeddings, similarity_fn: ~typing.Callable = <function cosine_similarity>, k: ~typing.Optional[int] = 20, similarity_threshold: ~typing.Optional[float] = None)[source]¶
Bases: BaseDocumentCompressor
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param embeddings: langchain.embeddings.base.Embeddings [Required]¶
Embeddings to use for embedding document contents and queries.
param k: Optional[int] = 20¶
The number of relevant documents to return. Can be set to None, in which case
similarity_threshold must be specified. Defaults to 20.
param similarity_fn: Callable = <function cosine_similarity>¶
Similarity function for comparing documents. Function expected to take as input
two matrices (List[List[float]]) and return a matrix of scores where higher values
indicate greater similarity.
param similarity_threshold: Optional[float] = None¶
Threshold for determining when two documents are similar enough
to be considered redundant. Defaults to None, must be specified if k is set
to None.
async acompress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Filter down documents.
compress_documents(documents: Sequence[Document], query: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → Sequence[Document][source]¶
Filter documents based on similarity of their embeddings to the query.
validator validate_params  »  all fields[source]¶
Validate similarity parameters.


validator validate_params  »  all fields[source]¶
Validate similarity parameters.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.knn.KNNRetriever¶
class langchain.retrievers.knn.KNNRetriever(*, embeddings: Embeddings, index: Any = None, texts: List[str], k: int = 4, relevancy_threshold: Optional[float] = None)[source]¶
Bases: BaseRetriever, BaseModel
KNN Retriever.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param embeddings: langchain.embeddings.base.Embeddings [Required]¶
param index: Any = None¶
param k: int = 4¶
param relevancy_threshold: Optional[float] = None¶
param texts: List[str] [Required]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod from_texts(texts: List[str], embeddings: Embeddings, **kwargs: Any) → KNNRetriever[source]¶
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.kendra.RetrieveResult¶
class langchain.retrievers.kendra.RetrieveResult(*, QueryId: str, ResultItems: List[RetrieveResultItem], **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param QueryId: str [Required]¶
param ResultItems: List[langchain.retrievers.kendra.RetrieveResultItem] [Required]¶
get_top_k_docs(top_n: int) → List[Document][source]¶


langchain.retrievers.knn.create_index¶
langchain.retrievers.knn.create_index(contexts: List[str], embeddings: Embeddings) → ndarray[source]¶
Create an index of embeddings for a list of contexts.
Parameters
contexts – List of contexts to embed.
embeddings – Embeddings model to use.
Returns
Index of embeddings.


langchain.retrievers.zilliz.ZillizRetreiver¶
langchain.retrievers.zilliz.ZillizRetreiver(*args: Any, **kwargs: Any) → ZillizRetriever[source]¶
Deprecated ZillizRetreiver. Please use ZillizRetriever (‘i’ before ‘e’) instead.
:param *args:
:param **kwargs:
Returns
ZillizRetriever


langchain.retrievers.multi_query.MultiQueryRetriever¶
class langchain.retrievers.multi_query.MultiQueryRetriever(retriever: BaseRetriever, llm_chain: LLMChain, verbose: bool = True, parser_key: str = 'lines')[source]¶
Bases: BaseRetriever
Given a user query, use an LLM to write a set of queries.
Retrieve docs for each query. Rake the unique union of all retrieved docs.
Initialize MultiQueryRetriever.
Parameters
retriever – retriever to query documents from
llm_chain – llm_chain for query generation
verbose – show the queries that we generated to the user
parser_key – attribute name for the parsed output
Returns
MultiQueryRetriever
Methods
__init__(retriever, llm_chain[, verbose, ...])
Initialize MultiQueryRetriever.
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
from_llm(retriever, llm[, prompt, parser_key])
Initialize from llm using default template.
generate_queries(question, run_manager)
Generate queries based upon user input.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
retrieve_documents(queries, run_manager)
Run all LLM generated queries.
unique_union(documents)
Get uniqe Documents.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod from_llm(retriever: BaseRetriever, llm: BaseLLM, prompt: PromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='You are an AI language model assistant. Your task is \n    to generate 3 different versions of the given user \n    question to retrieve relevant documents from a vector  database. \n    By generating multiple perspectives on the user question, \n    your goal is to help the user overcome some of the limitations \n    of distance-based similarity search. Provide these alternative \n    questions seperated by newlines. Original question: {question}', template_format='f-string', validate_template=True), parser_key: str = 'lines') → MultiQueryRetriever[source]¶
Initialize from llm using default template.
Parameters
retriever – retriever to query documents from
llm – llm for query generation using DEFAULT_QUERY_PROMPT
Returns
MultiQueryRetriever
generate_queries(question: str, run_manager: CallbackManagerForRetrieverRun) → List[str][source]¶
Generate queries based upon user input.
Parameters
question – user query
Returns
List of LLM generated queries that are similar to the user input
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
retrieve_documents(queries: List[str], run_manager: CallbackManagerForRetrieverRun) → List[Document][source]¶
Run all LLM generated queries.
Parameters
queries – query list
Returns
List of retrived Documents


Parameters
queries – query list
Returns
List of retrived Documents
unique_union(documents: List[Document]) → List[Document][source]¶
Get uniqe Documents.
Parameters
documents – List of retrived Documents
Returns
List of unique retrived Documents


langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever¶
class langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever(client: Any, index_name: str)[source]¶
Bases: BaseRetriever
Wrapper around Elasticsearch using BM25 as a retrieval method.
To connect to an Elasticsearch instance that requires login credentials,
including Elastic Cloud, use the Elasticsearch URL format
https://username:password@es_host:9243. For example, to connect to Elastic
Cloud, create the Elasticsearch URL with the required authentication details and
pass it to the ElasticVectorSearch constructor as the named parameter
elasticsearch_url.
You can obtain your Elastic Cloud URL and login credentials by logging in to the
Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and
navigating to the “Deployments” page.
To obtain your Elastic Cloud password for the default “elastic” user:
Log in to the Elastic Cloud console at https://cloud.elastic.co
Go to “Security” > “Users”
Locate the “elastic” user and click “Edit”
Click “Reset password”
Follow the prompts to reset the password
The format for Elastic Cloud URLs is
https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243.
Methods
__init__(client, index_name)
add_texts(texts[, refresh_indices])
Run more texts through the embeddings and add to the retriever.
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
create(elasticsearch_url, index_name[, k1, b])
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.


Retrieve documents relevant to a query.
add_texts(texts: Iterable[str], refresh_indices: bool = True) → List[str][source]¶
Run more texts through the embeddings and add to the retriever.
Parameters
texts – Iterable of strings to add to the retriever.
refresh_indices – bool to refresh ElasticSearch indices
Returns
List of ids from adding the texts into the retriever.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod create(elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75) → ElasticSearchBM25Retriever[source]¶
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.tfidf.TFIDFRetriever¶
class langchain.retrievers.tfidf.TFIDFRetriever(*, vectorizer: Any = None, docs: List[Document], tfidf_array: Any = None, k: int = 4)[source]¶
Bases: BaseRetriever, BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param docs: List[langchain.schema.Document] [Required]¶
param k: int = 4¶
param tfidf_array: Any = None¶
param vectorizer: Any = None¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod from_documents(documents: Iterable[Document], *, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any) → TFIDFRetriever[source]¶
classmethod from_texts(texts: Iterable[str], metadatas: Optional[Iterable[dict]] = None, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any) → TFIDFRetriever[source]¶
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.vespa_retriever.VespaRetriever¶
class langchain.retrievers.vespa_retriever.VespaRetriever(app: Vespa, body: Dict, content_field: str, metadata_fields: Optional[Sequence[str]] = None)[source]¶
Bases: BaseRetriever
Retriever that uses the Vespa.
Parameters
app – Vespa client.
body – query body.
content_field – result field with document contents.
metadata_fields – result fields to include in document metadata.
Methods
__init__(app, body, content_field[, ...])
param app
Vespa client.
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
from_params(url, content_field, *[, k, ...])
Instantiate retriever from params.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
get_relevant_documents_with_filter(query, *)
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod from_params(url: str, content_field: str, *, k: Optional[int] = None, metadata_fields: Union[Sequence[str], Literal['*']] = (), sources: Optional[Union[Sequence[str], Literal['*']]] = None, _filter: Optional[str] = None, yql: Optional[str] = None, **kwargs: Any) → VespaRetriever[source]¶
Instantiate retriever from params.
Parameters
url (str) – Vespa app URL.


Instantiate retriever from params.
Parameters
url (str) – Vespa app URL.
content_field (str) – Field in results to return as Document page_content.
k (Optional[int]) – Number of Documents to return. Defaults to None.
metadata_fields (Sequence[str] or "*") – Fields in results to include in
document metadata. Defaults to empty tuple ().
sources (Sequence[str] or "*" or None) – Sources to retrieve
from. Defaults to None.
_filter (Optional[str]) – Document filter condition expressed in YQL.
Defaults to None.
yql (Optional[str]) – Full YQL query to be used. Should not be specified
if _filter or sources are specified. Defaults to None.
kwargs (Any) – Keyword arguments added to query body.
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents_with_filter(query: str, *, _filter: Optional[str] = None) → List[Document][source]¶


langchain.retrievers.self_query.myscale.FUNCTION_COMPOSER¶
langchain.retrievers.self_query.myscale.FUNCTION_COMPOSER(op_name: str) → Callable[source]¶
Composer for functions.
:param op_name: Name of the function.
Returns
Callable that takes a list of arguments and returns a string.


langchain.retrievers.svm.SVMRetriever¶
class langchain.retrievers.svm.SVMRetriever(*, embeddings: Embeddings, index: Any = None, texts: List[str], k: int = 4, relevancy_threshold: Optional[float] = None)[source]¶
Bases: BaseRetriever, BaseModel
SVM Retriever.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param embeddings: langchain.embeddings.base.Embeddings [Required]¶
param index: Any = None¶
param k: int = 4¶
param relevancy_threshold: Optional[float] = None¶
param texts: List[str] [Required]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
classmethod from_texts(texts: List[str], embeddings: Embeddings, **kwargs: Any) → SVMRetriever[source]¶
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.retrievers.pubmed.PubMedRetriever¶
class langchain.retrievers.pubmed.PubMedRetriever(*, top_k_results: int = 3, load_max_docs: int = 25, doc_content_chars_max: int = 2000, load_all_available_meta: bool = False, email: str = 'your_email@example.com', base_url_esearch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?', base_url_efetch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?', max_retry: int = 5, sleep_time: float = 0.2, ARXIV_MAX_QUERY_LENGTH: int = 300)[source]¶
Bases: BaseRetriever, PubMedAPIWrapper
It is effectively a wrapper for PubMedAPIWrapper.
It wraps load() to get_relevant_documents().
It uses all PubMedAPIWrapper arguments without any change.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param doc_content_chars_max: int = 2000¶
param email: str = 'your_email@example.com'¶
param load_all_available_meta: bool = False¶
param load_max_docs: int = 25¶
param top_k_results: int = 3¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶


Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
load(query: str) → List[dict]¶
Search PubMed for documents matching the query.
Return a list of dictionaries containing the document metadata.
load_docs(query: str) → List[Document]¶
retrieve_article(uid: str, webenv: str) → dict¶
run(query: str) → str¶
Run PubMed search and get the article meta information.
See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
It uses only the most informative fields of article meta information.
model Config¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶