id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
59
127
6d5c37c1dbcb-80
Returns List of ids added to the vectorstore Return type List[str] as_retriever(**kwargs: Any) → langchain.vectorstores.redis.RedisVectorStoreRetriever[source]# static drop_index(index_name: str, delete_documents: bool, **kwargs: Any) → bool[source]# Drop a Redis search index. Parameters index_name (str) – Name of the index to drop. delete_documents (bool) – Whether to drop the associated documents. Returns Whether or not the drop was successful. Return type bool classmethod from_existing_index(embedding: langchain.embeddings.base.Embeddings, index_name: str, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', **kwargs: Any) → langchain.vectorstores.redis.Redis[source]# Connect to an existing Redis index. classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, index_name: Optional[str] = None, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', **kwargs: Any) → langchain.vectorstores.redis.Redis[source]# Create a Redis vectorstore from raw documents. This is a user-friendly interface that: Embeds documents. Creates a new index for the embeddings in Redis. Adds the documents to the newly created Redis index. This is intended to be a quick way to get started. .. rubric:: Example
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-81
This is intended to be a quick way to get started. .. rubric:: Example classmethod from_texts_return_keys(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, index_name: Optional[str] = None, content_key: str = 'content', metadata_key: str = 'metadata', vector_key: str = 'content_vector', distance_metric: Literal['COSINE', 'IP', 'L2'] = 'COSINE', **kwargs: Any) → Tuple[langchain.vectorstores.redis.Redis, List[str]][source]# Create a Redis vectorstore from raw documents. This is a user-friendly interface that: Embeds documents. Creates a new index for the embeddings in Redis. Adds the documents to the newly created Redis index. This is intended to be a quick way to get started. .. rubric:: Example similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Returns the most similar indexed documents to the query text. Parameters query (str) – The query text for which to find similar documents. k (int) – The number of documents to return. Default is 4. Returns A list of documents that are most similar to the query text. Return type List[Document] similarity_search_limit_score(query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any) → List[langchain.schema.Document][source]# Returns the most similar indexed documents to the query text within the score_threshold range. Parameters query (str) – The query text for which to find similar documents. k (int) – The number of documents to return. Default is 4.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-82
k (int) – The number of documents to return. Default is 4. score_threshold (float) – The minimum matching score required for a document 0.2. (to be considered a match. Defaults to) – similarity (Because the similarity calculation algorithm is based on cosine) – :param : :param the smaller the angle: :param the higher the similarity.: Returns A list of documents that are most similar to the query text, including the match score for each document. Return type List[Document] Note If there are no documents that satisfy the score_threshold value, an empty list is returned. similarity_search_with_score(query: str, k: int = 4) → List[Tuple[langchain.schema.Document, float]][source]# Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query and score for each class langchain.vectorstores.SKLearnVectorStore(embedding: langchain.embeddings.base.Embeddings, *, persist_path: Optional[str] = None, serializer: Literal['json', 'bson', 'parquet'] = 'json', metric: str = 'cosine', **kwargs: Any)[source]# A simple in-memory vector store based on the scikit-learn library NearestNeighbors implementation. add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-83
kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, persist_path: Optional[str] = None, **kwargs: Any) → langchain.vectorstores.sklearn.SKLearnVectorStore[source]# Return VectorStore initialized from texts and embeddings. max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param query: Text to look up documents similar to. :param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. :param embedding: Embedding to look up documents similar to. :param k: Number of Documents to return. Defaults to 4.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-84
:param k: Number of Documents to return. Defaults to 4. :param fetch_k: Number of Documents to fetch to pass to MMR algorithm. :param lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. persist() → None[source]# similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query. similarity_search_with_score(query: str, *, k: int = 4, **kwargs: Any) → List[Tuple[langchain.schema.Document, float]][source]# class langchain.vectorstores.SingleStoreDB(embedding: langchain.embeddings.base.Embeddings, *, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]# This class serves as a Pythonic interface to the SingleStore DB database. The prerequisite for using this class is the installation of the singlestoredb Python package. The SingleStoreDB vectorstore can be created by providing an embedding function and the relevant parameters for the database connection, connection pool, and optionally, the names of the table and the fields to use. add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, **kwargs: Any) → List[str][source]# Add more texts to the vectorstore. Parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-85
Add more texts to the vectorstore. Parameters texts (Iterable[str]) – Iterable of strings/text to add to the vectorstore. metadatas (Optional[List[dict]], optional) – Optional list of metadatas. Defaults to None. embeddings (Optional[List[List[float]]], optional) – Optional pre-generated embeddings. Defaults to None. Returns empty list Return type List[str] as_retriever(**kwargs: Any) → langchain.vectorstores.singlestoredb.SingleStoreDBRetriever[source]# connection_kwargs# Create connection pool. classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, table_name: str = 'embeddings', content_field: str = 'content', metadata_field: str = 'metadata', vector_field: str = 'vector', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any) → langchain.vectorstores.singlestoredb.SingleStoreDB[source]# Create a SingleStoreDB vectorstore from raw documents. This is a user-friendly interface that: Embeds documents. Creates a new table for the embeddings in SingleStoreDB. Adds the documents to the newly created table. This is intended to be a quick way to get started. .. rubric:: Example similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Returns the most similar indexed documents to the query text. Uses cosine similarity. Parameters query (str) – The query text for which to find similar documents. k (int) – The number of documents to return. Default is 4. Returns
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-86
k (int) – The number of documents to return. Default is 4. Returns A list of documents that are most similar to the query text. Return type List[Document] similarity_search_with_score(query: str, k: int = 4) → List[Tuple[langchain.schema.Document, float]][source]# Return docs most similar to query. Uses cosine similarity. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query and score for each vector_field# Pass the rest of the kwargs to the connection. class langchain.vectorstores.SupabaseVectorStore(client: supabase.client.Client, embedding: Embeddings, table_name: str, query_name: Union[str, None] = None)[source]# VectorStore for a Supabase postgres database. Assumes you have the pgvector extension installed and a match_documents (or similar) function. For more details: https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabase You can implement your own match_documents function in order to limit the search space to a subset of documents based on your own authorization or business logic. Note that the Supabase Python client does not yet support async operations. If you’d like to use max_marginal_relevance_search, please review the instructions below on modifying the match_documents function to return matched embeddings. add_texts(texts: Iterable[str], metadatas: Optional[List[dict[Any, Any]]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-87
Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. add_vectors(vectors: List[List[float]], documents: List[langchain.schema.Document]) → List[str][source]# classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, client: Optional[supabase.client.Client] = None, table_name: Optional[str] = 'documents', query_name: Union[str, None] = 'match_documents', **kwargs: Any) → SupabaseVectorStore[source]# Return VectorStore initialized from texts and embeddings. max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. fetch_k – Number of Documents to fetch to pass to MMR algorithm. lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. max_marginal_relevance_search requires that query_name returns matched embeddings alongside the match documents. The following function demonstrates how to do this: ```sql CREATE FUNCTION match_documents_embeddings(query_embedding vector(1536),
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-88
```sql CREATE FUNCTION match_documents_embeddings(query_embedding vector(1536), match_count int) RETURNS TABLE(id bigint, content text, metadata jsonb, embedding vector(1536), similarity float) LANGUAGE plpgsql AS $$ # variable_conflict use_column BEGINRETURN query SELECT id, content, metadata, embedding, 1 -(docstore.embedding <=> query_embedding) AS similarity FROMdocstore ORDER BYdocstore.embedding <=> query_embedding LIMIT match_count; END; $$; ``` max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. k – Number of Documents to return. Defaults to 4. fetch_k – Number of Documents to fetch to pass to MMR algorithm. lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. query_name: str# similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query. similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to embedding vector. Parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-89
Return docs most similar to embedding vector. Parameters embedding – Embedding to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query vector. similarity_search_by_vector_returning_embeddings(query: List[float], k: int) → List[Tuple[langchain.schema.Document, float, numpy.ndarray[numpy.float32, Any]]][source]# similarity_search_by_vector_with_relevance_scores(query: List[float], k: int) → List[Tuple[langchain.schema.Document, float]][source]# similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[langchain.schema.Document, float]][source]# Return docs and relevance scores in the range [0, 1]. 0 is dissimilar, 1 is most similar. Parameters query – input text k – Number of Documents to return. Defaults to 4. **kwargs – kwargs to be passed to similarity search. Should include: score_threshold: Optional, a floating point value between 0 to 1 to filter the resulting set of retrieved docs Returns List of Tuples of (doc, similarity_score) table_name: str# class langchain.vectorstores.Tair(embedding_function: langchain.embeddings.base.Embeddings, url: str, index_name: str, content_key: str = 'content', metadata_key: str = 'metadata', search_params: Optional[dict] = None, **kwargs: Any)[source]# add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]# Add texts data to an existing index.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-90
Add texts data to an existing index. create_index_if_not_exist(dim: int, distance_type: str, index_type: str, data_type: str, **kwargs: Any) → bool[source]# static drop_index(index_name: str = 'langchain', **kwargs: Any) → bool[source]# Drop an existing index. Parameters index_name (str) – Name of the index to drop. Returns True if the index is dropped successfully. Return type bool classmethod from_documents(documents: List[langchain.schema.Document], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = 'langchain', content_key: str = 'content', metadata_key: str = 'metadata', **kwargs: Any) → langchain.vectorstores.tair.Tair[source]# Return VectorStore initialized from documents and embeddings. classmethod from_existing_index(embedding: langchain.embeddings.base.Embeddings, index_name: str = 'langchain', content_key: str = 'content', metadata_key: str = 'metadata', **kwargs: Any) → langchain.vectorstores.tair.Tair[source]# Connect to an existing Tair index. classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = 'langchain', content_key: str = 'content', metadata_key: str = 'metadata', **kwargs: Any) → langchain.vectorstores.tair.Tair[source]# Return VectorStore initialized from texts and embeddings. similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Returns the most similar indexed documents to the query text. Parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-91
Returns the most similar indexed documents to the query text. Parameters query (str) – The query text for which to find similar documents. k (int) – The number of documents to return. Default is 4. Returns A list of documents that are most similar to the query text. Return type List[Document] class langchain.vectorstores.Tigris(client: TigrisClient, embeddings: Embeddings, index_name: str)[source]# add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. ids – Optional list of ids for documents. Ids will be autogenerated if not provided. kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, client: Optional[TigrisClient] = None, index_name: Optional[str] = None, **kwargs: Any) → Tigris[source]# Return VectorStore initialized from texts and embeddings. property search_index: TigrisVectorStore# similarity_search(query: str, k: int = 4, filter: Optional[TigrisFilter] = None, **kwargs: Any) → List[Document][source]# Return docs most similar to query.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-92
Return docs most similar to query. similarity_search_with_score(query: str, k: int = 4, filter: Optional[TigrisFilter] = None) → List[Tuple[Document, float]][source]# Run similarity search with Chroma with distance. Parameters query (str) – Query text to search for. k (int) – Number of results to return. Defaults to 4. filter (Optional[TigrisFilter]) – Filter by metadata. Defaults to None. Returns List of documents most similar to the querytext with distance in float. Return type List[Tuple[Document, float]] class langchain.vectorstores.Typesense(typesense_client: Client, embedding: Embeddings, *, typesense_collection_name: Optional[str] = None, text_key: str = 'text')[source]# Wrapper around Typesense vector search. To use, you should have the typesense python package installed. Example from langchain.embedding.openai import OpenAIEmbeddings from langchain.vectorstores import Typesense import typesense node = { "host": "localhost", # For Typesense Cloud use xxx.a1.typesense.net "port": "8108", # For Typesense Cloud use 443 "protocol": "http" # For Typesense Cloud use https } typesense_client = typesense.Client( { "nodes": [node], "api_key": "<API_KEY>", "connection_timeout_seconds": 2 } ) typesense_collection_name = "langchain-memory" embedding = OpenAIEmbeddings() vectorstore = Typesense( typesense_client, typesense_collection_name, embedding.embed_query, "text", )
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-93
typesense_collection_name, embedding.embed_query, "text", ) add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embedding and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. ids – Optional list of ids to associate with the texts. Returns List of ids from adding the texts into the vectorstore. classmethod from_client_params(embedding: langchain.embeddings.base.Embeddings, *, host: str = 'localhost', port: Union[str, int] = '8108', protocol: str = 'http', typesense_api_key: Optional[str] = None, connection_timeout_seconds: int = 2, **kwargs: Any) → langchain.vectorstores.typesense.Typesense[source]# Initialize Typesense directly from client parameters. Example from langchain.embedding.openai import OpenAIEmbeddings from langchain.vectorstores import Typesense # Pass in typesense_api_key as kwarg or set env var "TYPESENSE_API_KEY". vectorstore = Typesense( OpenAIEmbeddings(), host="localhost", port="8108", protocol="http", typesense_collection_name="langchain-memory", )
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-94
protocol="http", typesense_collection_name="langchain-memory", ) classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, typesense_client: Optional[Client] = None, typesense_client_params: Optional[dict] = None, typesense_collection_name: Optional[str] = None, text_key: str = 'text', **kwargs: Any) → Typesense[source]# Construct Typesense wrapper from raw text. similarity_search(query: str, k: int = 4, filter: Optional[str] = '', **kwargs: Any) → List[langchain.schema.Document][source]# Return typesense documents most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. filter – typesense filter_by expression to filter documents on Returns List of Documents most similar to the query and score for each similarity_search_with_score(query: str, k: int = 4, filter: Optional[str] = '') → List[Tuple[langchain.schema.Document, float]][source]# Return typesense documents most similar to query, along with scores. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. filter – typesense filter_by expression to filter documents on Returns List of Documents most similar to the query and score for each class langchain.vectorstores.Vectara(vectara_customer_id: Optional[str] = None, vectara_corpus_id: Optional[str] = None, vectara_api_key: Optional[str] = None)[source]# Implementation of Vector Store using Vectara (https://vectara.com). .. rubric:: Example
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-95
.. rubric:: Example from langchain.vectorstores import Vectara vectorstore = Vectara( vectara_customer_id=vectara_customer_id, vectara_corpus_id=vectara_corpus_id, vectara_api_key=vectara_api_key ) add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. Returns List of ids from adding the texts into the vectorstore. as_retriever(**kwargs: Any) → langchain.vectorstores.vectara.VectaraRetriever[source]# classmethod from_texts(texts: List[str], embedding: Optional[langchain.embeddings.base.Embeddings] = None, metadatas: Optional[List[dict]] = None, **kwargs: Any) → langchain.vectorstores.vectara.Vectara[source]# Construct Vectara wrapper from raw documents. This is intended to be a quick way to get started. .. rubric:: Example from langchain import Vectara vectara = Vectara.from_texts( texts, vectara_customer_id=customer_id, vectara_corpus_id=corpus_id, vectara_api_key=api_key, ) similarity_search(query: str, k: int = 5, lambda_val: float = 0.025, filter: Optional[str] = None, n_sentence_context: int = 0, **kwargs: Any) → List[langchain.schema.Document][source]# Return Vectara documents most similar to query, along with scores. Parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-96
Return Vectara documents most similar to query, along with scores. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 5. filter – Dictionary of argument(s) to filter on metadata. For example a filter can be “doc.rating > 3.0 and part.lang = ‘deu’”} see https://docs.vectara.com/docs/search-apis/sql/filter-overview for more details. n_sentence_context – number of sentences before/after the matching segment to add Returns List of Documents most similar to the query similarity_search_with_score(query: str, k: int = 5, lambda_val: float = 0.025, filter: Optional[str] = None, n_sentence_context: int = 0, **kwargs: Any) → List[Tuple[langchain.schema.Document, float]][source]# Return Vectara documents most similar to query, along with scores. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 5. lambda_val – lexical match parameter for hybrid search. filter – Dictionary of argument(s) to filter on metadata. For example a filter can be “doc.rating > 3.0 and part.lang = ‘deu’”} see https://docs.vectara.com/docs/search-apis/sql/filter-overview for more details. n_sentence_context – number of sentences before/after the matching segment to add Returns List of Documents most similar to the query and score for each. class langchain.vectorstores.VectorStore[source]# Interface for vector stores. async aadd_documents(documents: List[langchain.schema.Document], **kwargs: Any) → List[str][source]# Run more documents through the embeddings and add to the vectorstore. Parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-97
Run more documents through the embeddings and add to the vectorstore. Parameters (List[Document] (documents) – Documents to add to the vectorstore. Returns List of IDs of the added texts. Return type List[str] async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embeddings and add to the vectorstore. add_documents(documents: List[langchain.schema.Document], **kwargs: Any) → List[str][source]# Run more documents through the embeddings and add to the vectorstore. Parameters (List[Document] (documents) – Documents to add to the vectorstore. Returns List of IDs of the added texts. Return type List[str] abstract add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]# Run more texts through the embeddings and add to the vectorstore. Parameters texts – Iterable of strings to add to the vectorstore. metadatas – Optional list of metadatas associated with the texts. kwargs – vectorstore specific parameters Returns List of ids from adding the texts into the vectorstore. async classmethod afrom_documents(documents: List[langchain.schema.Document], embedding: langchain.embeddings.base.Embeddings, **kwargs: Any) → langchain.vectorstores.base.VST[source]# Return VectorStore initialized from documents and embeddings. async classmethod afrom_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → langchain.vectorstores.base.VST[source]# Return VectorStore initialized from texts and embeddings.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-98
Return VectorStore initialized from texts and embeddings. async amax_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. async amax_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. as_retriever(**kwargs: Any) → langchain.vectorstores.base.VectorStoreRetriever[source]# async asearch(query: str, search_type: str, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query using specified search type. async asimilarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query. async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to embedding vector. async asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[langchain.schema.Document, float]][source]# Return docs most similar to query. classmethod from_documents(documents: List[langchain.schema.Document], embedding: langchain.embeddings.base.Embeddings, **kwargs: Any) → langchain.vectorstores.base.VST[source]# Return VectorStore initialized from documents and embeddings.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-99
Return VectorStore initialized from documents and embeddings. abstract classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → langchain.vectorstores.base.VST[source]# Return VectorStore initialized from texts and embeddings. max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. fetch_k – Number of Documents to fetch to pass to MMR algorithm. lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. k – Number of Documents to return. Defaults to 4. fetch_k – Number of Documents to fetch to pass to MMR algorithm. lambda_mult – Number between 0 and 1 that determines the degree
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-100
lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. search(query: str, search_type: str, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query using specified search type. abstract similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query. similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to embedding vector. Parameters embedding – Embedding to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query vector. similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[langchain.schema.Document, float]][source]# Return docs and relevance scores in the range [0, 1]. 0 is dissimilar, 1 is most similar. Parameters query – input text k – Number of Documents to return. Defaults to 4. **kwargs – kwargs to be passed to similarity search. Should include: score_threshold: Optional, a floating point value between 0 to 1 to filter the resulting set of retrieved docs Returns List of Tuples of (doc, similarity_score)
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-101
Returns List of Tuples of (doc, similarity_score) class langchain.vectorstores.Weaviate(client: typing.Any, index_name: str, text_key: str, embedding: typing.Optional[langchain.embeddings.base.Embeddings] = None, attributes: typing.Optional[typing.List[str]] = None, relevance_score_fn: typing.Optional[typing.Callable[[float], float]] = <function _default_score_normalizer>, by_text: bool = True)[source]# Wrapper around Weaviate vector database. To use, you should have the weaviate-client python package installed. Example import weaviate from langchain.vectorstores import Weaviate client = weaviate.Client(url=os.environ["WEAVIATE_URL"], ...) weaviate = Weaviate(client, index_name, text_key) add_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) → List[str][source]# Upload texts with metadata (properties) to Weaviate. classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) → langchain.vectorstores.weaviate.Weaviate[source]# Construct Weaviate wrapper from raw documents. This is a user-friendly interface that: Embeds documents. Creates a new index for the embeddings in the Weaviate instance. Adds the documents to the newly created Weaviate index. This is intended to be a quick way to get started. Example from langchain.vectorstores.weaviate import Weaviate from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() weaviate = Weaviate.from_texts( texts, embeddings,
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-102
weaviate = Weaviate.from_texts( texts, embeddings, weaviate_url="http://localhost:8080" ) max_marginal_relevance_search(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. fetch_k – Number of Documents to fetch to pass to MMR algorithm. lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Parameters embedding – Embedding to look up documents similar to. k – Number of Documents to return. Defaults to 4. fetch_k – Number of Documents to fetch to pass to MMR algorithm. lambda_mult – Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-103
Defaults to 0.5. Returns List of Documents selected by maximal marginal relevance. similarity_search(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query. similarity_search_by_text(query: str, k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Return docs most similar to query. Parameters query – Text to look up documents similar to. k – Number of Documents to return. Defaults to 4. Returns List of Documents most similar to the query. similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[langchain.schema.Document][source]# Look up similar documents by embedding vector in Weaviate. similarity_search_with_score(query: str, k: int = 4, **kwargs: Any) → List[Tuple[langchain.schema.Document, float]][source]# Return list of documents most similar to the query text and cosine distance in float for each. Lower score represents more similarity. class langchain.vectorstores.Zilliz(embedding_function: langchain.embeddings.base.Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[dict[str, Any]] = None, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: Optional[bool] = False)[source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
6d5c37c1dbcb-104
classmethod from_texts(texts: List[str], embedding: langchain.embeddings.base.Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'LangChainCollection', connection_args: dict[str, Any] = {}, consistency_level: str = 'Session', index_params: Optional[dict] = None, search_params: Optional[dict] = None, drop_old: bool = False, **kwargs: Any) → langchain.vectorstores.zilliz.Zilliz[source]# Create a Zilliz collection, indexes it with HNSW, and insert data. Parameters texts (List[str]) – Text data. embedding (Embeddings) – Embedding function. metadatas (Optional[List[dict]]) – Metadata for each text if it exists. Defaults to None. collection_name (str, optional) – Collection name to use. Defaults to “LangChainCollection”. connection_args (dict[str, Any], optional) – Connection args to use. Defaults to DEFAULT_MILVUS_CONNECTION. consistency_level (str, optional) – Which consistency level to use. Defaults to “Session”. index_params (Optional[dict], optional) – Which index_params to use. Defaults to None. search_params (Optional[dict], optional) – Which search params to use. Defaults to None. drop_old (Optional[bool], optional) – Whether to drop the collection with that name if it exists. Defaults to False. Returns Zilliz Vector Store Return type Zilliz previous Document Loaders next Retrievers By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/vectorstores.html
d7df30d8f90e-0
.rst .pdf Document Compressors Document Compressors# pydantic model langchain.retrievers.document_compressors.CohereRerank[source]# field client: Client [Required]# field model: str = 'rerank-english-v2.0'# field top_n: int = 3# async acompress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Compress retrieved documents given the query context. compress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Compress retrieved documents given the query context. pydantic model langchain.retrievers.document_compressors.DocumentCompressorPipeline[source]# Document compressor that uses a pipeline of transformers. field 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[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Compress retrieved documents given the query context. compress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Transform a list of documents. pydantic model langchain.retrievers.document_compressors.EmbeddingsFilter[source]# field embeddings: langchain.embeddings.base.Embeddings [Required]# Embeddings to use for embedding document contents and queries. field 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.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/document_compressors.html
d7df30d8f90e-1
similarity_threshold must be specified. Defaults to 20. field 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. field 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[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Filter down documents. compress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Filter documents based on similarity of their embeddings to the query. pydantic model langchain.retrievers.document_compressors.LLMChainExtractor[source]# field get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input># Callable for constructing the chain input from the query and a Document. field llm_chain: langchain.chains.llm.LLMChain [Required]# LLM wrapper to use for compressing documents. async acompress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Compress page content of raw documents asynchronously. compress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Compress page content of raw documents.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/document_compressors.html
d7df30d8f90e-2
Compress page content of raw documents. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, prompt: Optional[langchain.prompts.prompt.PromptTemplate] = None, get_input: Optional[Callable[[str, langchain.schema.Document], str]] = None, llm_chain_kwargs: Optional[dict] = None) → langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor[source]# Initialize from LLM. pydantic model langchain.retrievers.document_compressors.LLMChainFilter[source]# Filter that drops documents that aren’t relevant to the query. field get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input># Callable for constructing the chain input from the query and a Document. field 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[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Filter down documents. compress_documents(documents: Sequence[langchain.schema.Document], query: str) → Sequence[langchain.schema.Document][source]# Filter down documents based on their relevance to the query. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, prompt: Optional[langchain.prompts.base.BasePromptTemplate] = None, **kwargs: Any) → langchain.retrievers.document_compressors.chain_filter.LLMChainFilter[source]# previous Retrievers next Document Transformers By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/document_compressors.html
020b9497c959-0
.rst .pdf Python REPL Python REPL# For backwards compatibility. pydantic model langchain.python.PythonREPL[source]# Simulates a standalone Python REPL. field globals: Optional[Dict] [Optional] (alias '_globals')# field locals: Optional[Dict] [Optional] (alias '_locals')# run(command: str) → str[source]# Run command with own globals/locals and returns anything printed. By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/python.html
1bb39e8a4fc7-0
.rst .pdf Document Transformers Document Transformers# Transform documents pydantic model langchain.document_transformers.EmbeddingsRedundantFilter[source]# Filter that drops redundant documents by comparing their embeddings. field embeddings: langchain.embeddings.base.Embeddings [Required]# Embeddings to use for embedding document contents. field 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. field similarity_threshold: float = 0.95# Threshold for determining when two documents are similar enough to be considered redundant. async atransform_documents(documents: Sequence[langchain.schema.Document], **kwargs: Any) → Sequence[langchain.schema.Document][source]# Asynchronously transform a list of documents. transform_documents(documents: Sequence[langchain.schema.Document], **kwargs: Any) → Sequence[langchain.schema.Document][source]# Filter down documents. langchain.document_transformers.get_stateful_documents(documents: Sequence[langchain.schema.Document]) → Sequence[langchain.document_transformers._DocumentWithState][source]# previous Document Compressors next Memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/document_transformers.html
0bf147887ee3-0
.rst .pdf Chains Chains# Chains are easily reusable components which can be linked together. pydantic model langchain.chains.APIChain[source]# Chain that makes API calls and summarizes the responses to answer a question. Validators raise_deprecation » all fields set_verbose » verbose validate_api_answer_prompt » all fields validate_api_request_prompt » all fields field api_answer_chain: LLMChain [Required]# field api_docs: str [Required]# field api_request_chain: LLMChain [Required]# field requests_wrapper: TextRequestsWrapper [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-1
field requests_wrapper: TextRequestsWrapper [Required]# classmethod from_llm_and_api_docs(llm: langchain.base_language.BaseLanguageModel, api_docs: str, headers: Optional[dict] = None, api_url_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['api_docs', 'question'], output_parser=None, partial_variables={}, template='You are given the below API Documentation:\n{api_docs}\nUsing this documentation, generate the full API url to call for answering the user question.\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\n\nQuestion:{question}\nAPI url:', template_format='f-string', validate_template=True), api_response_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['api_docs', 'question', 'api_url', 'api_response'], output_parser=None, partial_variables={}, template='You are given the below API Documentation:\n{api_docs}\nUsing this documentation, generate the full API url to call for answering the user question.\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\n\nQuestion:{question}\nAPI url: {api_url}\n\nHere is the response from the API:\n\n{api_response}\n\nSummarize this response to answer the original question.\n\nSummary:', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.api.base.APIChain[source]# Load chain from just an LLM and the api docs. pydantic model langchain.chains.AnalyzeDocumentChain[source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-2
pydantic model langchain.chains.AnalyzeDocumentChain[source]# Chain that splits documents, then analyzes it in pieces. Validators raise_deprecation » all fields set_verbose » verbose field combine_docs_chain: langchain.chains.combine_documents.base.BaseCombineDocumentsChain [Required]# field text_splitter: langchain.text_splitter.TextSplitter [Optional]# pydantic model langchain.chains.ChatVectorDBChain[source]# Chain for chatting with a vector database. Validators raise_deprecation » all fields set_verbose » verbose field search_kwargs: dict [Optional]# field top_k_docs_for_context: int = 4# field vectorstore: VectorStore [Required]# classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, vectorstore: langchain.vectorstores.base.VectorStore, condense_question_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['chat_history', 'question'], output_parser=None, partial_variables={}, template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\n\nChat History:\n{chat_history}\nFollow Up Input: {question}\nStandalone question:', template_format='f-string', validate_template=True), chain_type: str = 'stuff', combine_docs_chain_kwargs: Optional[Dict] = None, callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain[source]# Load chain from LLM. pydantic model langchain.chains.ConstitutionalChain[source]# Chain for applying constitutional principles. Example from langchain.llms import OpenAI
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-3
Chain for applying constitutional principles. Example from langchain.llms import OpenAI from langchain.chains import LLMChain, ConstitutionalChain from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple llm = OpenAI() qa_prompt = PromptTemplate( template="Q: {question} A:", input_variables=["question"], ) qa_chain = LLMChain(llm=llm, prompt=qa_prompt) constitutional_chain = ConstitutionalChain.from_llm( llm=llm, chain=qa_chain, constitutional_principles=[ ConstitutionalPrinciple( critique_request="Tell if this answer is good.", revision_request="Give a better answer.", ) ], ) constitutional_chain.run(question="What is the meaning of life?") Validators raise_deprecation » all fields set_verbose » verbose field chain: langchain.chains.llm.LLMChain [Required]# field constitutional_principles: List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple] [Required]# field critique_chain: langchain.chains.llm.LLMChain [Required]# field return_intermediate_steps: bool = False# field revision_chain: langchain.chains.llm.LLMChain [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-4
classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, chain: langchain.chains.llm.LLMChain, critique_prompt: langchain.prompts.base.BasePromptTemplate = FewShotPromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request'], output_parser=None, partial_variables={}, examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-5
model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-6
'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.", 'critique': "The provided sentence appears to
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-7
is not in the style of Master Yoda.", 'critique': "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", 'revision': 'No revisions needed.'}], example_selector=None, example_prompt=PromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request', 'critique'], output_parser=None, partial_variables={}, template='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}', template_format='f-string', validate_template=True), suffix='Human: {input_prompt}\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique:', example_separator='\n === \n', prefix="Below is a conversation between a human and an AI model. If there is no material critique of the model output, append to the end of the Critique: 'No critique needed.' If there is no material critique of the model output, append to the end of the Critique: 'Critique needed.'", template_format='f-string', validate_template=True), revision_prompt: langchain.prompts.base.BasePromptTemplate = FewShotPromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request', 'critique', 'revision_request'], output_parser=None, partial_variables={}, examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-8
precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision_request': 'Please rewrite the model
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-9
are too young to give consent. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also,
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-10
solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision_request': 'Please rewrite the model response. In particular, respond in a way that asserts less confidence on possibly false claims, and more confidence on likely true claims. Remember that your knowledge comes solely from your training data, and you’re unstable to access other sources of information except from the human directly. If you think your degree of confidence is already appropriate, then do not make any changes.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.",
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-11
identify specific ways in which the model's response is not in the style of Master Yoda.", 'critique': "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", 'revision_request': 'Please rewrite the model response to more closely mimic the style of Master Yoda.', 'revision': 'No revisions needed.'}], example_selector=None, example_prompt=PromptTemplate(input_variables=['input_prompt', 'output_from_model', 'critique_request', 'critique'], output_parser=None, partial_variables={}, template='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}', template_format='f-string', validate_template=True), suffix='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}\n\nIf the critique does not identify anything worth changing, ignore the Revision Request and do not make any revisions. Instead, return "No revisions needed".\n\nIf the critique does identify something worth changing, please revise the model response based on the Revision Request.\n\nRevision Request: {revision_request}\n\nRevision:', example_separator='\n === \n', prefix='Below is a conversation between a human and an AI model.', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.constitutional_ai.base.ConstitutionalChain[source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-12
Create a chain from an LLM. classmethod get_principles(names: Optional[List[str]] = None) → List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple][source]# property input_keys: List[str]# Defines the input keys. property output_keys: List[str]# Defines the output keys. pydantic model langchain.chains.ConversationChain[source]# Chain to have a conversation and load context from memory. Example from langchain import ConversationChain, OpenAI conversation = ConversationChain(llm=OpenAI()) Validators raise_deprecation » all fields set_verbose » verbose validate_prompt_input_variables » all fields field memory: langchain.schema.BaseMemory [Optional]# Default memory store. field prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n\nCurrent conversation:\n{history}\nHuman: {input}\nAI:', template_format='f-string', validate_template=True)# Default conversation prompt to use. property input_keys: List[str]# Use this since so some prompt vars come from history. pydantic model langchain.chains.ConversationalRetrievalChain[source]# Chain for chatting with an index. Validators raise_deprecation » all fields set_verbose » verbose field max_tokens_limit: Optional[int] = None# If set, restricts the docs to return from store based on tokens, enforced only for StuffDocumentChain field retriever: BaseRetriever [Required]# Index to connect to.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-13
field retriever: BaseRetriever [Required]# Index to connect to. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, retriever: langchain.schema.BaseRetriever, condense_question_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['chat_history', 'question'], output_parser=None, partial_variables={}, template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\n\nChat History:\n{chat_history}\nFollow Up Input: {question}\nStandalone question:', template_format='f-string', validate_template=True), chain_type: str = 'stuff', verbose: bool = False, condense_question_llm: Optional[langchain.base_language.BaseLanguageModel] = None, combine_docs_chain_kwargs: Optional[Dict] = None, callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain[source]# Load chain from LLM. pydantic model langchain.chains.FlareChain[source]# Validators raise_deprecation » all fields set_verbose » verbose field max_iter: int = 10# field min_prob: float = 0.2# field min_token_gap: int = 5# field num_pad_tokens: int = 2# field output_parser: FinishedOutputParser [Optional]# field question_generator_chain: QuestionGeneratorChain [Required]# field response_chain: _ResponseChain [Optional]# field retriever: BaseRetriever [Required]# field start_with_retrieval: bool = True#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-14
field start_with_retrieval: bool = True# classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, max_generation_len: int = 32, **kwargs: Any) → langchain.chains.flare.base.FlareChain[source]# property input_keys: List[str]# Input keys this chain expects. property output_keys: List[str]# Output keys this chain expects. pydantic model langchain.chains.GraphCypherQAChain[source]# Chain for question-answering against a graph by generating Cypher statements. Validators raise_deprecation » all fields set_verbose » verbose field cypher_generation_chain: LLMChain [Required]# field graph: Neo4jGraph [Required]# field qa_chain: LLMChain [Required]# field return_direct: bool = False# Whether or not to return the result of querying the graph directly. field return_intermediate_steps: bool = False# Whether or not to return the intermediate steps along with the final answer. field top_k: int = 10# Number of results to return from the query
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-15
field top_k: int = 10# Number of results to return from the query classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, *, qa_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template="You are an assistant that helps to form nice and human understandable answers.\nThe information part contains the provided information that you must use to construct an answer.\nThe provided information is authorative, you must never doubt it or try to use your internal knowledge to correct it.\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\nIf the provided information is empty, say that you don't know the answer.\nInformation:\n{context}\n\nQuestion: {question}\nHelpful Answer:", template_format='f-string', validate_template=True), cypher_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['schema', 'question'], output_parser=None, partial_variables={}, template='Task:Generate Cypher statement to query a graph database.\nInstructions:\nUse only the provided relationship types and properties in the schema.\nDo not use any other relationship types or properties that are not provided.\nSchema:\n{schema}\nNote: Do not include any explanations or apologies in your responses.\nDo not respond to any questions that might ask anything else than for you to construct a Cypher statement.\nDo not include any text except the generated Cypher statement.\n\nThe question is:\n{question}', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.graph_qa.cypher.GraphCypherQAChain[source]# Initialize from LLM. pydantic model langchain.chains.GraphQAChain[source]# Chain for question-answering against a graph. Validators
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-16
Chain for question-answering against a graph. Validators raise_deprecation » all fields set_verbose » verbose field entity_extraction_chain: LLMChain [Required]# field graph: NetworkxEntityGraph [Required]# field qa_chain: LLMChain [Required]# classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, qa_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template="Use the following knowledge triplets to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", template_format='f-string', validate_template=True), entity_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['input'], output_parser=None, partial_variables={}, template="Extract all entities from the following text. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return.\n\nEXAMPLE\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Sam.\nOutput: Langchain, Sam\nEND OF EXAMPLE\n\nBegin!\n\n{input}\nOutput:", template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.graph_qa.base.GraphQAChain[source]# Initialize from LLM.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-17
Initialize from LLM. pydantic model langchain.chains.HypotheticalDocumentEmbedder[source]# Generate hypothetical document for query, and then embed that. Based on https://arxiv.org/abs/2212.10496 Validators raise_deprecation » all fields set_verbose » verbose field base_embeddings: Embeddings [Required]# field llm_chain: LLMChain [Required]# combine_embeddings(embeddings: List[List[float]]) → List[float][source]# Combine embeddings into final embeddings. embed_documents(texts: List[str]) → List[List[float]][source]# Call the base embeddings. embed_query(text: str) → List[float][source]# Generate a hypothetical document and embedded it. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, base_embeddings: langchain.embeddings.base.Embeddings, prompt_key: str, **kwargs: Any) → langchain.chains.hyde.base.HypotheticalDocumentEmbedder[source]# Load and use LLMChain for a specific prompt key. property input_keys: List[str]# Input keys for Hyde’s LLM chain. property output_keys: List[str]# Output keys for Hyde’s LLM chain. pydantic model langchain.chains.LLMBashChain[source]# Chain that interprets a prompt and executes bash code to perform bash operations. Example from langchain import LLMBashChain, OpenAI llm_bash = LLMBashChain.from_llm(OpenAI()) Validators raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose validate_prompt » all fields field llm: Optional[BaseLanguageModel] = None# [Deprecated] LLM wrapper to use. field llm_chain: LLMChain [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-18
field llm_chain: LLMChain [Required]# field prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=BashOutputParser(), partial_variables={}, template='If someone asks you to perform a task, your job is to come up with a series of bash commands that will perform the task. There is no need to put "#!/bin/bash" in your answer. Make sure to reason step by step, using this format:\n\nQuestion: "copy the files in the directory named \'target\' into a new directory at the same level as target called \'myNewDirectory\'"\n\nI need to take the following actions:\n- List all files in the directory\n- Create a new directory\n- Copy the files from the first directory into the second directory\n```bash\nls\nmkdir myNewDirectory\ncp -r target/* myNewDirectory\n```\n\nThat is the format. Begin!\n\nQuestion: {question}', template_format='f-string', validate_template=True)# [Deprecated]
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-19
[Deprecated] classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=BashOutputParser(), partial_variables={}, template='If someone asks you to perform a task, your job is to come up with a series of bash commands that will perform the task. There is no need to put "#!/bin/bash" in your answer. Make sure to reason step by step, using this format:\n\nQuestion: "copy the files in the directory named \'target\' into a new directory at the same level as target called \'myNewDirectory\'"\n\nI need to take the following actions:\n- List all files in the directory\n- Create a new directory\n- Copy the files from the first directory into the second directory\n```bash\nls\nmkdir myNewDirectory\ncp -r target/* myNewDirectory\n```\n\nThat is the format. Begin!\n\nQuestion: {question}', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.llm_bash.base.LLMBashChain[source]# pydantic model langchain.chains.LLMChain[source]# Chain to run queries against LLMs. Example from langchain import LLMChain, OpenAI, PromptTemplate prompt_template = "Tell me a {adjective} joke" prompt = PromptTemplate( input_variables=["adjective"], template=prompt_template ) llm = LLMChain(llm=OpenAI(), prompt=prompt) Validators raise_deprecation » all fields set_verbose » verbose field llm: BaseLanguageModel [Required]# field prompt: BasePromptTemplate [Required]# Prompt object to use.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-20
field prompt: BasePromptTemplate [Required]# Prompt object to use. async aapply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None) → List[Dict[str, str]][source]# Utilize the LLM generate method for speed gains. async aapply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None) → Sequence[Union[str, List[str], Dict[str, str]]][source]# Call apply and then parse the results. async agenerate(input_list: List[Dict[str, Any]], run_manager: Optional[langchain.callbacks.manager.AsyncCallbackManagerForChainRun] = None) → langchain.schema.LLMResult[source]# Generate LLM result from inputs. apply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None) → List[Dict[str, str]][source]# Utilize the LLM generate method for speed gains. apply_and_parse(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None) → Sequence[Union[str, List[str], Dict[str, str]]][source]# Call apply and then parse the results. async apredict(callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → str[source]# Format prompt with kwargs and pass to LLM. Parameters callbacks – Callbacks to pass to LLMChain
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-21
Parameters callbacks – Callbacks to pass to LLMChain **kwargs – Keys to pass to prompt template. Returns Completion from LLM. Example completion = llm.predict(adjective="funny") async apredict_and_parse(callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → Union[str, List[str], Dict[str, str]][source]# Call apredict and then parse the results. async aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[langchain.callbacks.manager.AsyncCallbackManagerForChainRun] = None) → Tuple[List[langchain.schema.PromptValue], Optional[List[str]]][source]# Prepare prompts from inputs. create_outputs(response: langchain.schema.LLMResult) → List[Dict[str, str]][source]# Create outputs from response. classmethod from_string(llm: langchain.base_language.BaseLanguageModel, template: str) → langchain.chains.llm.LLMChain[source]# Create LLMChain from LLM and template. generate(input_list: List[Dict[str, Any]], run_manager: Optional[langchain.callbacks.manager.CallbackManagerForChainRun] = None) → langchain.schema.LLMResult[source]# Generate LLM result from inputs. predict(callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → str[source]# Format prompt with kwargs and pass to LLM. Parameters callbacks – Callbacks to pass to LLMChain **kwargs – Keys to pass to prompt template. Returns Completion from LLM. Example completion = llm.predict(adjective="funny")
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-22
Completion from LLM. Example completion = llm.predict(adjective="funny") predict_and_parse(callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → Union[str, List[str], Dict[str, Any]][source]# Call predict and then parse the results. prep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[langchain.callbacks.manager.CallbackManagerForChainRun] = None) → Tuple[List[langchain.schema.PromptValue], Optional[List[str]]][source]# Prepare prompts from inputs. property lc_serializable: bool# Return whether or not the class is serializable. pydantic model langchain.chains.LLMCheckerChain[source]# Chain for question-answering with self-verification. Example from langchain import OpenAI, LLMCheckerChain llm = OpenAI(temperature=0.7) checker_chain = LLMCheckerChain.from_llm(llm) Validators raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose field check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='Here is a bullet point list of assertions:\n{assertions}\nFor each assertion, determine whether it is true or false. If it is false, explain why.\n\n', template_format='f-string', validate_template=True)# [Deprecated] field create_draft_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='{question}\n\n', template_format='f-string', validate_template=True)# [Deprecated]
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-23
[Deprecated] field list_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['statement'], output_parser=None, partial_variables={}, template='Here is a statement:\n{statement}\nMake a bullet point list of the assumptions you made when producing the above statement.\n\n', template_format='f-string', validate_template=True)# [Deprecated] field llm: Optional[BaseLanguageModel] = None# [Deprecated] LLM wrapper to use. field question_to_checked_assertions_chain: SequentialChain [Required]# field revised_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'question'], output_parser=None, partial_variables={}, template="{checked_assertions}\n\nQuestion: In light of the above assertions and checks, how would you answer the question '{question}'?\n\nAnswer:", template_format='f-string', validate_template=True)# [Deprecated] Prompt to use when questioning the documents.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-24
[Deprecated] Prompt to use when questioning the documents. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, create_draft_answer_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='{question}\n\n', template_format='f-string', validate_template=True), list_assertions_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['statement'], output_parser=None, partial_variables={}, template='Here is a statement:\n{statement}\nMake a bullet point list of the assumptions you made when producing the above statement.\n\n', template_format='f-string', validate_template=True), check_assertions_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='Here is a bullet point list of assertions:\n{assertions}\nFor each assertion, determine whether it is true or false. If it is false, explain why.\n\n', template_format='f-string', validate_template=True), revised_answer_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'question'], output_parser=None, partial_variables={}, template="{checked_assertions}\n\nQuestion: In light of the above assertions and checks, how would you answer the question '{question}'?\n\nAnswer:", template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.llm_checker.base.LLMCheckerChain[source]# pydantic model langchain.chains.LLMMathChain[source]# Chain that interprets a prompt and executes python code to do math. Example from langchain import LLMMathChain, OpenAI llm_math = LLMMathChain.from_llm(OpenAI()) Validators raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-25
raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose field llm: Optional[BaseLanguageModel] = None# [Deprecated] LLM wrapper to use. field llm_chain: LLMChain [Required]# field prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='Translate a math problem into a expression that can be executed using Python\'s numexpr library. Use the output of running this code to answer the question.\n\nQuestion: ${{Question with math problem.}}\n```text\n${{single line mathematical expression that solves the problem}}\n```\n...numexpr.evaluate(text)...\n```output\n${{Output of running the code}}\n```\nAnswer: ${{Answer}}\n\nBegin.\n\nQuestion: What is 37593 * 67?\n```text\n37593 * 67\n```\n...numexpr.evaluate("37593 * 67")...\n```output\n2518731\n```\nAnswer: 2518731\n\nQuestion: 37593^(1/5)\n```text\n37593**(1/5)\n```\n...numexpr.evaluate("37593**(1/5)")...\n```output\n8.222831614237718\n```\nAnswer: 8.222831614237718\n\nQuestion: {question}\n', template_format='f-string', validate_template=True)# [Deprecated] Prompt to use to translate to python if necessary.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-26
[Deprecated] Prompt to use to translate to python if necessary. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='Translate a math problem into a expression that can be executed using Python\'s numexpr library. Use the output of running this code to answer the question.\n\nQuestion: ${{Question with math problem.}}\n```text\n${{single line mathematical expression that solves the problem}}\n```\n...numexpr.evaluate(text)...\n```output\n${{Output of running the code}}\n```\nAnswer: ${{Answer}}\n\nBegin.\n\nQuestion: What is 37593 * 67?\n```text\n37593 * 67\n```\n...numexpr.evaluate("37593 * 67")...\n```output\n2518731\n```\nAnswer: 2518731\n\nQuestion: 37593^(1/5)\n```text\n37593**(1/5)\n```\n...numexpr.evaluate("37593**(1/5)")...\n```output\n8.222831614237718\n```\nAnswer: 8.222831614237718\n\nQuestion: {question}\n', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.llm_math.base.LLMMathChain[source]# pydantic model langchain.chains.LLMRequestsChain[source]# Chain that hits a URL and then uses an LLM to parse results. Validators raise_deprecation » all fields set_verbose » verbose validate_environment » all fields field llm_chain: LLMChain [Required]# field requests_wrapper: TextRequestsWrapper [Optional]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-27
field requests_wrapper: TextRequestsWrapper [Optional]# field text_length: int = 8000# pydantic model langchain.chains.LLMSummarizationCheckerChain[source]# Chain for question-answering with self-verification. Example from langchain import OpenAI, LLMSummarizationCheckerChain llm = OpenAI(temperature=0.0) checker_chain = LLMSummarizationCheckerChain.from_llm(llm) Validators raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose field are_all_true_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false.\n\nIf all of the assertions are true, return "True". If any of the assertions are false, return "False".\n\nHere are some examples:\n===\n\nChecked Assertions: """\n- The sky is red: False\n- Water is made of lava: False\n- The sun is a star: True\n"""\nResult: False\n\n===\n\nChecked Assertions: """\n- The sky is blue: True\n- Water is wet: True\n- The sun is a star: True\n"""\nResult: True\n\n===\n\nChecked Assertions: """\n- The sky is blue - True\n- Water is made of lava- False\n- The sun is a star - True\n"""\nResult: False\n\n===\n\nChecked Assertions:"""\n{checked_assertions}\n"""\nResult:', template_format='f-string', validate_template=True)# [Deprecated]
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-28
[Deprecated] field check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\n\nHere is a bullet point list of facts:\n"""\n{assertions}\n"""\n\nFor each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".\nIf the fact is false, explain why.\n\n', template_format='f-string', validate_template=True)# [Deprecated] field create_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['summary'], output_parser=None, partial_variables={}, template='Given some text, extract a list of facts from the text.\n\nFormat your output as a bulleted list.\n\nText:\n"""\n{summary}\n"""\n\nFacts:', template_format='f-string', validate_template=True)# [Deprecated] field llm: Optional[BaseLanguageModel] = None# [Deprecated] LLM wrapper to use. field max_checks: int = 2# Maximum number of times to check the assertions. Default to double-checking.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-29
Maximum number of times to check the assertions. Default to double-checking. field revised_summary_prompt: PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'summary'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\n\nChecked Assertions:\n"""\n{checked_assertions}\n"""\n\nOriginal Summary:\n"""\n{summary}\n"""\n\nUsing these checked assertions, rewrite the original summary to be completely true.\n\nThe output should have the same structure and formatting as the original summary.\n\nSummary:', template_format='f-string', validate_template=True)# [Deprecated] field sequential_chain: SequentialChain [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-30
classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, create_assertions_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['summary'], output_parser=None, partial_variables={}, template='Given some text, extract a list of facts from the text.\n\nFormat your output as a bulleted list.\n\nText:\n"""\n{summary}\n"""\n\nFacts:', template_format='f-string', validate_template=True), check_assertions_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['assertions'], output_parser=None, partial_variables={}, template='You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.\n\nHere is a bullet point list of facts:\n"""\n{assertions}\n"""\n\nFor each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".\nIf the fact is false, explain why.\n\n', template_format='f-string', validate_template=True), revised_summary_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['checked_assertions', 'summary'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false. If the answer is false, a suggestion is given for a correction.\n\nChecked Assertions:\n"""\n{checked_assertions}\n"""\n\nOriginal Summary:\n"""\n{summary}\n"""\n\nUsing these checked assertions, rewrite the original summary to be completely true.\n\nThe output should have the same structure and formatting as the original summary.\n\nSummary:', template_format='f-string', validate_template=True), are_all_true_prompt: langchain.prompts.prompt.PromptTemplate =
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-31
validate_template=True), are_all_true_prompt: langchain.prompts.prompt.PromptTemplate = PromptTemplate(input_variables=['checked_assertions'], output_parser=None, partial_variables={}, template='Below are some assertions that have been fact checked and are labeled as true or false.\n\nIf all of the assertions are true, return "True". If any of the assertions are false, return "False".\n\nHere are some examples:\n===\n\nChecked Assertions: """\n- The sky is red: False\n- Water is made of lava: False\n- The sun is a star: True\n"""\nResult: False\n\n===\n\nChecked Assertions: """\n- The sky is blue: True\n- Water is wet: True\n- The sun is a star: True\n"""\nResult: True\n\n===\n\nChecked Assertions: """\n- The sky is blue - True\n- Water is made of lava- False\n- The sun is a star - True\n"""\nResult: False\n\n===\n\nChecked Assertions:"""\n{checked_assertions}\n"""\nResult:', template_format='f-string', validate_template=True), verbose: bool = False, **kwargs: Any) → langchain.chains.llm_summarization_checker.base.LLMSummarizationCheckerChain[source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-32
pydantic model langchain.chains.MapReduceChain[source]# Map-reduce chain. Validators raise_deprecation » all fields set_verbose » verbose field combine_documents_chain: BaseCombineDocumentsChain [Required]# Chain to use to combine documents. field text_splitter: TextSplitter [Required]# Text splitter to use. classmethod from_params(llm: langchain.base_language.BaseLanguageModel, prompt: langchain.prompts.base.BasePromptTemplate, text_splitter: langchain.text_splitter.TextSplitter, callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, combine_chain_kwargs: Optional[Mapping[str, Any]] = None, reduce_chain_kwargs: Optional[Mapping[str, Any]] = None, **kwargs: Any) → langchain.chains.mapreduce.MapReduceChain[source]# Construct a map-reduce chain that uses the chain for map and reduce. pydantic model langchain.chains.NebulaGraphQAChain[source]# Chain for question-answering against a graph by generating nGQL statements. Validators raise_deprecation » all fields set_verbose » verbose field graph: NebulaGraph [Required]# field ngql_generation_chain: LLMChain [Required]# field qa_chain: LLMChain [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-33
classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, *, qa_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], output_parser=None, partial_variables={}, template="You are an assistant that helps to form nice and human understandable answers.\nThe information part contains the provided information that you must use to construct an answer.\nThe provided information is authorative, you must never doubt it or try to use your internal knowledge to correct it.\nMake the answer sound as a response to the question. Do not mention that you based the result on the given information.\nIf the provided information is empty, say that you don't know the answer.\nInformation:\n{context}\n\nQuestion: {question}\nHelpful Answer:", template_format='f-string', validate_template=True), ngql_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['schema', 'question'], output_parser=None, partial_variables={}, template="Task:Generate NebulaGraph Cypher statement to query a graph database.\n\nInstructions:\n\nFirst, generate cypher then convert it to NebulaGraph Cypher dialect(rather than standard):\n1. it requires explicit label specification when referring to node properties: v.`Foo`.name\n2. it uses double equals sign for comparison: `==` rather than `=`\nFor instance:\n```diff\n< MATCH (p:person)-[:directed]->(m:movie) WHERE m.name = 'The Godfather II'\n< RETURN p.name;\n---\n> MATCH (p:`person`)-[:directed]->(m:`movie`) WHERE m.`movie`.`name` == 'The Godfather II'\n> RETURN p.`person`.`name`;\n```\n\nUse only the provided relationship types and properties in the schema.\nDo not use any other relationship types or properties that are not
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-34
types and properties in the schema.\nDo not use any other relationship types or properties that are not provided.\nSchema:\n{schema}\nNote: Do not include any explanations or apologies in your responses.\nDo not respond to any questions that might ask anything else than for you to construct a Cypher statement.\nDo not include any text except the generated Cypher statement.\n\nThe question is:\n{question}", template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.graph_qa.nebulagraph.NebulaGraphQAChain[source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-35
Initialize from LLM. pydantic model langchain.chains.OpenAIModerationChain[source]# Pass input through a moderation endpoint. To use, you should have the openai python package installed, and the environment variable OPENAI_API_KEY set with your API key. Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example from langchain.chains import OpenAIModerationChain moderation = OpenAIModerationChain() Validators raise_deprecation » all fields set_verbose » verbose validate_environment » all fields field error: bool = False# Whether or not to error if bad content was found. field model_name: Optional[str] = None# Moderation model name to use. field openai_api_key: Optional[str] = None# field openai_organization: Optional[str] = None# pydantic model langchain.chains.OpenAPIEndpointChain[source]# Chain interacts with an OpenAPI endpoint using natural language. Validators raise_deprecation » all fields set_verbose » verbose field api_operation: APIOperation [Required]# field api_request_chain: LLMChain [Required]# field api_response_chain: Optional[LLMChain] = None# field param_mapping: _ParamMapping [Required]# field requests: Requests [Optional]# field return_intermediate_steps: bool = False# deserialize_json_input(serialized_args: str) → dict[source]# Use the serialized typescript dictionary. Resolve the path, query params dict, and optional requestBody dict.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-36
Resolve the path, query params dict, and optional requestBody dict. classmethod from_api_operation(operation: langchain.tools.openapi.utils.api_models.APIOperation, llm: langchain.base_language.BaseLanguageModel, requests: Optional[langchain.requests.Requests] = None, verbose: bool = False, return_intermediate_steps: bool = False, raw_response: bool = False, callbacks: Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]] = None, **kwargs: Any) → langchain.chains.api.openapi.chain.OpenAPIEndpointChain[source]# Create an OpenAPIEndpointChain from an operation and a spec. classmethod from_url_and_method(spec_url: str, path: str, method: str, llm: langchain.base_language.BaseLanguageModel, requests: Optional[langchain.requests.Requests] = None, return_intermediate_steps: bool = False, **kwargs: Any) → langchain.chains.api.openapi.chain.OpenAPIEndpointChain[source]# Create an OpenAPIEndpoint from a spec at the specified url. pydantic model langchain.chains.PALChain[source]# Implements Program-Aided Language Models. Validators raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose field get_answer_expr: str = 'print(solution())'# field llm: Optional[BaseLanguageModel] = None# [Deprecated] field llm_chain: LLMChain [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-37
field prompt: BasePromptTemplate = PromptTemplate(input_variables=['question'], output_parser=None, partial_variables={}, template='Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\n\n# solution in Python:\n\n\ndef solution():\n    """Olivia has $23. She bought five bagels for $3 each. How much money does she have left?"""\n    money_initial = 23\n    bagels = 5\n    bagel_cost = 3\n    money_spent = bagels * bagel_cost\n    money_left = money_initial - money_spent\n    result = money_left\n    return result\n\n\n\n\n\nQ: Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\n\n# solution in Python:\n\n\ndef solution():\n    """Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?"""\n    golf_balls_initial = 58\n    golf_balls_lost_tuesday = 23\n    golf_balls_lost_wednesday = 2\n    golf_balls_left = golf_balls_initial - golf_balls_lost_tuesday - golf_balls_lost_wednesday\n    result = golf_balls_left\n    return result\n\n\n\n\n\nQ: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?\n\n# solution in Python:\n\n\ndef solution():\n    """There were nine computers in the server room. Five more computers were installed
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-38
solution():\n    """There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?"""\n    computers_initial = 9\n    computers_per_day = 5\n    num_days = 4  # 4 days between monday and thursday\n    computers_added = computers_per_day * num_days\n    computers_total = computers_initial + computers_added\n    result = computers_total\n    return result\n\n\n\n\n\nQ: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\n\n# solution in Python:\n\n\ndef solution():\n    """Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?"""\n    toys_initial = 5\n    mom_toys = 2\n    dad_toys = 2\n    total_received = mom_toys + dad_toys\n    total_toys = toys_initial + total_received\n    result = total_toys\n    return result\n\n\n\n\n\nQ: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\n\n# solution in Python:\n\n\ndef solution():\n    """Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?"""\n    jason_lollipops_initial = 20\n    jason_lollipops_after = 12\n    denny_lollipops = jason_lollipops_initial -
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-39
= 12\n    denny_lollipops = jason_lollipops_initial - jason_lollipops_after\n    result = denny_lollipops\n    return result\n\n\n\n\n\nQ: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\n\n# solution in Python:\n\n\ndef solution():\n    """Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?"""\n    leah_chocolates = 32\n    sister_chocolates = 42\n    total_chocolates = leah_chocolates + sister_chocolates\n    chocolates_eaten = 35\n    chocolates_left = total_chocolates - chocolates_eaten\n    result = chocolates_left\n    return result\n\n\n\n\n\nQ: If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\n\n# solution in Python:\n\n\ndef solution():\n    """If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?"""\n    cars_initial = 3\n    cars_arrived = 2\n    total_cars = cars_initial + cars_arrived\n    result = total_cars\n    return result\n\n\n\n\n\nQ: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\n\n# solution in Python:\n\n\ndef solution():\n    """There are 15 trees in the grove. Grove workers will plant trees in the grove today. After
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-40
15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?"""\n    trees_initial = 15\n    trees_after = 21\n    trees_added = trees_after - trees_initial\n    result = trees_added\n    return result\n\n\n\n\n\nQ: {question}\n\n# solution in Python:\n\n\n', template_format='f-string', validate_template=True)#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-41
[Deprecated] field python_globals: Optional[Dict[str, Any]] = None# field python_locals: Optional[Dict[str, Any]] = None# field return_intermediate_steps: bool = False# field stop: str = '\n\n'# classmethod from_colored_object_prompt(llm: langchain.base_language.BaseLanguageModel, **kwargs: Any) → langchain.chains.pal.base.PALChain[source]# Load PAL from colored object prompt. classmethod from_math_prompt(llm: langchain.base_language.BaseLanguageModel, **kwargs: Any) → langchain.chains.pal.base.PALChain[source]# Load PAL from math prompt. pydantic model langchain.chains.QAGenerationChain[source]# Validators raise_deprecation » all fields set_verbose » verbose field input_key: str = 'text'# field k: Optional[int] = None# field llm_chain: LLMChain [Required]# field output_key: str = 'questions'# field text_splitter: TextSplitter = <langchain.text_splitter.RecursiveCharacterTextSplitter object># classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, prompt: Optional[langchain.prompts.base.BasePromptTemplate] = None, **kwargs: Any) → langchain.chains.qa_generation.base.QAGenerationChain[source]# property input_keys: List[str]# Input keys this chain expects. property output_keys: List[str]# Output keys this chain expects. pydantic model langchain.chains.QAWithSourcesChain[source]# Question answering with sources over documents. Validators raise_deprecation » all fields set_verbose » verbose validate_naming » all fields pydantic model langchain.chains.RetrievalQA[source]# Chain for question-answering against an index. Example
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-42
Chain for question-answering against an index. Example from langchain.llms import OpenAI from langchain.chains import RetrievalQA from langchain.faiss import FAISS from langchain.vectorstores.base import VectorStoreRetriever retriever = VectorStoreRetriever(vectorstore=FAISS(...)) retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever) Validators raise_deprecation » all fields set_verbose » verbose field retriever: BaseRetriever [Required]# pydantic model langchain.chains.RetrievalQAWithSourcesChain[source]# Question-answering with sources over an index. Validators raise_deprecation » all fields set_verbose » verbose validate_naming » all fields field max_tokens_limit: int = 3375# Restrict the docs to return from store based on tokens, enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true field reduce_k_below_max_tokens: bool = False# Reduce the number of results to return from store based on tokens limit field retriever: langchain.schema.BaseRetriever [Required]# Index to connect to. pydantic model langchain.chains.SQLDatabaseChain[source]# Chain for interacting with SQL Database. Example from langchain import SQLDatabaseChain, OpenAI, SQLDatabase db = SQLDatabase(...) db_chain = SQLDatabaseChain.from_llm(OpenAI(), db) Validators raise_deprecation » all fields raise_deprecation » all fields set_verbose » verbose field database: SQLDatabase [Required]# SQL Database to connect to. field llm: Optional[BaseLanguageModel] = None# [Deprecated] LLM wrapper to use.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-43
[Deprecated] LLM wrapper to use. field llm_chain: LLMChain [Required]# field prompt: Optional[BasePromptTemplate] = None# [Deprecated] Prompt to use to translate natural language to SQL. field query_checker_prompt: Optional[BasePromptTemplate] = None# The prompt template that should be used by the query checker field return_direct: bool = False# Whether or not to return the result of querying the SQL table directly. field return_intermediate_steps: bool = False# Whether or not to return the intermediate steps along with the final answer. field top_k: int = 5# Number of results to return from the query field use_query_checker: bool = False# Whether or not the query checker tool should be used to attempt to fix the initial SQL from the LLM. classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, db: langchain.sql_database.SQLDatabase, prompt: Optional[langchain.prompts.base.BasePromptTemplate] = None, **kwargs: Any) → langchain.chains.sql_database.base.SQLDatabaseChain[source]# pydantic model langchain.chains.SQLDatabaseSequentialChain[source]# Chain for querying SQL database that is a sequential chain. The chain is as follows: 1. Based on the query, determine which tables to use. 2. Based on those tables, call the normal SQL database chain. This is useful in cases where the number of tables in the database is large. Validators raise_deprecation » all fields set_verbose » verbose field decider_chain: LLMChain [Required]# field return_intermediate_steps: bool = False# field sql_chain: SQLDatabaseChain [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-44
classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, database: langchain.sql_database.SQLDatabase, query_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['input', 'table_info', 'dialect', 'top_k'], output_parser=None, partial_variables={}, template='Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database.\n\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\n\nPay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n\nUse the following format:\n\nQuestion: Question here\nSQLQuery: SQL Query to run\nSQLResult: Result of the SQLQuery\nAnswer: Final answer here\n\nOnly use the following tables:\n{table_info}\n\nQuestion: {input}', template_format='f-string', validate_template=True), decider_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['query', 'table_names'], output_parser=CommaSeparatedListOutputParser(), partial_variables={}, template='Given the below input question and list of potential tables, output a comma separated list of the table names that may be necessary to answer this question.\n\nQuestion: {query}\n\nTable Names: {table_names}\n\nRelevant Table Names:', template_format='f-string', validate_template=True), **kwargs: Any) →
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-45
Table Names:', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.sql_database.base.SQLDatabaseSequentialChain[source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-46
Load the necessary chains. pydantic model langchain.chains.SequentialChain[source]# Chain where the outputs of one chain feed directly into next. Validators raise_deprecation » all fields set_verbose » verbose validate_chains » all fields field chains: List[langchain.chains.base.Chain] [Required]# field input_variables: List[str] [Required]# field return_all: bool = False# pydantic model langchain.chains.SimpleSequentialChain[source]# Simple chain where the outputs of one step feed directly into next. Validators raise_deprecation » all fields set_verbose » verbose validate_chains » all fields field chains: List[langchain.chains.base.Chain] [Required]# field strip_outputs: bool = False# pydantic model langchain.chains.TransformChain[source]# Chain transform chain output. Example from langchain import TransformChain transform_chain = TransformChain(input_variables=["text"], output_variables["entities"], transform=func()) Validators raise_deprecation » all fields set_verbose » verbose field input_variables: List[str] [Required]# field output_variables: List[str] [Required]# field transform: Callable[[Dict[str, str]], Dict[str, str]] [Required]# pydantic model langchain.chains.VectorDBQA[source]# Chain for question-answering against a vector database. Validators raise_deprecation » all fields set_verbose » verbose validate_search_type » all fields field k: int = 4# Number of documents to query for. field search_kwargs: Dict[str, Any] [Optional]# Extra search args. field search_type: str = 'similarity'# Search type to use over vectorstore. similarity or mmr. field vectorstore: VectorStore [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-47
field vectorstore: VectorStore [Required]# Vector Database to connect to. pydantic model langchain.chains.VectorDBQAWithSourcesChain[source]# Question-answering with sources over a vector database. Validators raise_deprecation » all fields set_verbose » verbose validate_naming » all fields field k: int = 4# Number of results to return from store field max_tokens_limit: int = 3375# Restrict the docs to return from store based on tokens, enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true field reduce_k_below_max_tokens: bool = False# Reduce the number of results to return from store based on tokens limit field search_kwargs: Dict[str, Any] [Optional]# Extra search args. field vectorstore: langchain.vectorstores.base.VectorStore [Required]# Vector Database to connect to. langchain.chains.create_extraction_chain(schema: dict, llm: langchain.base_language.BaseLanguageModel) → langchain.chains.base.Chain[source]# langchain.chains.create_extraction_chain_pydantic(pydantic_schema: Any, llm: langchain.base_language.BaseLanguageModel) → langchain.chains.base.Chain[source]# langchain.chains.create_tagging_chain(schema: dict, llm: langchain.base_language.BaseLanguageModel) → langchain.chains.base.Chain[source]# langchain.chains.create_tagging_chain_pydantic(pydantic_schema: Any, llm: langchain.base_language.BaseLanguageModel) → langchain.chains.base.Chain[source]# langchain.chains.load_chain(path: Union[str, pathlib.Path], **kwargs: Any) → langchain.chains.base.Chain[source]# Unified method for loading a chain from LangChainHub or local fs. previous Tagging next Agents
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
0bf147887ee3-48
previous Tagging next Agents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/chains.html
7db38aa60b44-0
.rst .pdf Retrievers Retrievers# pydantic model langchain.retrievers.ArxivRetriever[source]# It is effectively a wrapper for ArxivAPIWrapper. It wraps load() to get_relevant_documents(). It uses all ArxivAPIWrapper arguments without any change. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents class langchain.retrievers.AwsKendraIndexRetriever(kclient: Any, kendraindex: str, k: int = 3, languagecode: str = 'en')[source]# Wrapper around AWS Kendra. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Run search on Kendra index and get top k documents docs = get_relevant_documents(‘This is my query’) k: int# Number of documents to query for. kclient: Any# boto3 client for Kendra. kendraindex: str# Kendra index id languagecode: str# Languagecode used for querying. pydantic model langchain.retrievers.AzureCognitiveSearchRetriever[source]# Wrapper around Azure Cognitive Search.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-1
Wrapper around Azure Cognitive Search. field aiosession: Optional[aiohttp.client.ClientSession] = None# ClientSession, in case we want to reuse connection for better performance. field api_key: str = ''# API Key. Both Admin and Query keys work, but for reading data it’s recommended to use a Query key. field api_version: str = '2020-06-30'# API version field content_key: str = 'content'# Key in a retrieved result to set as the Document page_content. field index_name: str = ''# Name of Index inside Azure Cognitive Search service field service_name: str = ''# Name of Azure Cognitive Search service async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.ChatGPTPluginRetriever[source]# field aiosession: Optional[aiohttp.client.ClientSession] = None# field bearer_token: str [Required]# field filter: Optional[dict] = None# field top_k: int = 3# field url: str [Required]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-2
Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.ContextualCompressionRetriever[source]# Retriever that wraps a base retriever and compresses the results. field base_compressor: langchain.retrievers.document_compressors.base.BaseDocumentCompressor [Required]# Compressor for compressing retrieved documents. field base_retriever: langchain.schema.BaseRetriever [Required]# Base Retriever to use for getting relevant documents. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns Sequence of relevant documents class langchain.retrievers.DataberryRetriever(datastore_url: str, top_k: Optional[int] = None, api_key: Optional[str] = None)[source]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents api_key: Optional[str]# datastore_url: str# get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents top_k: Optional[int]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-3
Returns List of relevant documents top_k: Optional[int]# class langchain.retrievers.ElasticSearchBM25Retriever(client: Any, index_name: str)[source]# 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. add_texts(texts: Iterable[str], refresh_indices: bool = True) → List[str][source]# Run more texts through the embeddings and add to the retriver. 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) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-4
Parameters query – string to find relevant documents for Returns List of relevant documents classmethod create(elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75) → langchain.retrievers.elastic_search_bm25.ElasticSearchBM25Retriever[source]# get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.KNNRetriever[source]# field embeddings: langchain.embeddings.base.Embeddings [Required]# field index: Any = None# field k: int = 4# field relevancy_threshold: Optional[float] = None# field texts: List[str] [Required]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents classmethod from_texts(texts: List[str], embeddings: langchain.embeddings.base.Embeddings, **kwargs: Any) → langchain.retrievers.knn.KNNRetriever[source]# get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents class langchain.retrievers.MergerRetriever(retrievers: List[langchain.schema.BaseRetriever])[source]# This class merges the results of multiple retrievers. Parameters retrievers – A list of retrievers to merge.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-5
Parameters retrievers – A list of retrievers to merge. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Asynchronously get the relevant documents for a given query. Parameters query – The query to search for. Returns A list of relevant documents. async amerge_documents(query: str) → List[langchain.schema.Document][source]# Asynchronously merge the results of the retrievers. Parameters query – The query to search for. Returns A list of merged documents. get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get the relevant documents for a given query. Parameters query – The query to search for. Returns A list of relevant documents. merge_documents(query: str) → List[langchain.schema.Document][source]# Merge the results of the retrievers. Parameters query – The query to search for. Returns A list of merged documents. class langchain.retrievers.MetalRetriever(client: Any, params: Optional[dict] = None)[source]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.PineconeHybridSearchRetriever[source]# field alpha: float = 0.5# field embeddings: langchain.embeddings.base.Embeddings [Required]# field index: Any = None#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-6
field index: Any = None# field sparse_encoder: Any = None# field top_k: int = 4# add_texts(texts: List[str], ids: Optional[List[str]] = None, metadatas: Optional[List[dict]] = None) → None[source]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.PubMedRetriever[source]# It is effectively a wrapper for PubMedAPIWrapper. It wraps load() to get_relevant_documents(). It uses all PubMedAPIWrapper arguments without any change. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.RemoteLangChainRetriever[source]# field headers: Optional[dict] = None# field input_key: str = 'message'# field metadata_key: str = 'metadata'# field page_content_key: str = 'page_content'# field response_key: str = 'response'# field url: str [Required]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-7
field response_key: str = 'response'# field url: str [Required]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.SVMRetriever[source]# field embeddings: langchain.embeddings.base.Embeddings [Required]# field index: Any = None# field k: int = 4# field relevancy_threshold: Optional[float] = None# field texts: List[str] [Required]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents classmethod from_texts(texts: List[str], embeddings: langchain.embeddings.base.Embeddings, **kwargs: Any) → langchain.retrievers.svm.SVMRetriever[source]# get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.SelfQueryRetriever[source]# Retriever that wraps around a vector store and uses an LLM to generate the vector store queries. field llm_chain: langchain.chains.llm.LLMChain [Required]# The LLMChain for generating the vector store queries.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-8
The LLMChain for generating the vector store queries. field search_kwargs: dict [Optional]# Keyword arguments to pass in to the vector store search. field search_type: str = 'similarity'# The search type to perform on the vector store. field structured_query_translator: langchain.chains.query_constructor.ir.Visitor [Required]# Translator for turning internal query language into vectorstore search params. field vectorstore: langchain.vectorstores.base.VectorStore [Required]# The underlying vector store from which documents will be retrieved. field verbose: bool = False# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents classmethod from_llm(llm: langchain.base_language.BaseLanguageModel, vectorstore: langchain.vectorstores.base.VectorStore, document_contents: str, metadata_field_info: List[langchain.chains.query_constructor.schema.AttributeInfo], structured_query_translator: Optional[langchain.chains.query_constructor.ir.Visitor] = None, chain_kwargs: Optional[Dict] = None, enable_limit: bool = False, **kwargs: Any) → langchain.retrievers.self_query.base.SelfQueryRetriever[source]# get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.TFIDFRetriever[source]# field docs: List[langchain.schema.Document] [Required]# field k: int = 4# field tfidf_array: Any = None# field vectorizer: Any = None#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-9
field tfidf_array: Any = None# field vectorizer: Any = None# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents classmethod from_documents(documents: Iterable[langchain.schema.Document], *, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any) → langchain.retrievers.tfidf.TFIDFRetriever[source]# classmethod from_texts(texts: Iterable[str], metadatas: Optional[Iterable[dict]] = None, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any) → langchain.retrievers.tfidf.TFIDFRetriever[source]# get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents pydantic model langchain.retrievers.TimeWeightedVectorStoreRetriever[source]# Retriever combining embedding similarity with recency. field decay_rate: float = 0.01# The exponential decay factor used as (1.0-decay_rate)**(hrs_passed). field 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. field k: int = 4# The maximum number of documents to retrieve in a given call. field memory_stream: List[langchain.schema.Document] [Optional]# The memory_stream of documents to search through. field other_score_keys: List[str] = []#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-10
field other_score_keys: List[str] = []# Other keys in the metadata to factor into the score, e.g. ‘importance’. field search_kwargs: dict [Optional]# Keyword arguments to pass to the vectorstore similarity search. field vectorstore: langchain.vectorstores.base.VectorStore [Required]# The vectorstore to store documents and determine salience. async aadd_documents(documents: List[langchain.schema.Document], **kwargs: Any) → List[str][source]# Add documents to vectorstore. add_documents(documents: List[langchain.schema.Document], **kwargs: Any) → List[str][source]# Add documents to vectorstore. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Return documents that are relevant to the query. get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Return documents that are relevant to the query. get_salient_docs(query: str) → Dict[int, Tuple[langchain.schema.Document, float]][source]# Return documents that are salient to the query. class langchain.retrievers.VespaRetriever(app: Vespa, body: Dict, content_field: str, metadata_fields: Optional[Sequence[str]] = None)[source]# async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-11
Parameters query – string to find relevant documents for 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) → langchain.retrievers.vespa_retriever.VespaRetriever[source]# 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) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents_with_filter(query: str, *, _filter: Optional[str] = None) → List[langchain.schema.Document][source]#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-12
class langchain.retrievers.WeaviateHybridSearchRetriever(client: Any, index_name: str, text_key: str, alpha: float = 0.5, k: int = 4, attributes: Optional[List[str]] = None, create_schema_if_missing: bool = True)[source]# class Config[source]# Configuration for this pydantic object. arbitrary_types_allowed = True# extra = 'forbid'# add_documents(docs: List[langchain.schema.Document], **kwargs: Any) → List[str][source]# Upload documents to Weaviate. async aget_relevant_documents(query: str, where_filter: Optional[Dict[str, object]] = None) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str, where_filter: Optional[Dict[str, object]] = None) → List[langchain.schema.Document][source]# Look up similar documents in Weaviate. pydantic model langchain.retrievers.WikipediaRetriever[source]# It is effectively a wrapper for WikipediaAPIWrapper. It wraps load() to get_relevant_documents(). It uses all WikipediaAPIWrapper arguments without any change. async aget_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
7db38aa60b44-13
Parameters query – string to find relevant documents for Returns List of relevant documents class langchain.retrievers.ZepRetriever(session_id: str, url: str, top_k: Optional[int] = None)[source]# 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://getzep.github.io/deployment/quickstart/ async aget_relevant_documents(query: str, metadata: Optional[Dict] = None) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents get_relevant_documents(query: str, metadata: Optional[Dict] = None) → List[langchain.schema.Document][source]# Get documents relevant for a query. Parameters query – string to find relevant documents for Returns List of relevant documents previous Vector Stores next Document Compressors By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/retrievers.html
4001009da5ed-0
.rst .pdf Docstore Docstore# Wrappers on top of docstores. class langchain.docstore.InMemoryDocstore(_dict: Dict[str, langchain.schema.Document])[source]# Simple in memory docstore in the form of a dict. add(texts: Dict[str, langchain.schema.Document]) → None[source]# Add texts to in memory dictionary. search(search: str) → Union[str, langchain.schema.Document][source]# Search via direct lookup. class langchain.docstore.Wikipedia[source]# Wrapper around wikipedia API. search(search: str) → Union[str, langchain.schema.Document][source]# Try to search for wiki page. If page exists, return the page summary, and a PageWithLookups object. If page does not exist, return similar entries. previous Indexes next Text Splitter By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/docstore.html
4092f5c0fde6-0
.rst .pdf Memory Memory# class langchain.memory.CassandraChatMessageHistory(contact_points: List[str], session_id: str, port: int = 9042, username: str = 'cassandra', password: str = 'cassandra', keyspace_name: str = 'chat_history', table_name: str = 'message_store')[source]# Chat message history that stores history in Cassandra. Parameters contact_points – list of ips to connect to Cassandra cluster session_id – arbitrary key that is used to store the messages of a single chat session. port – port to connect to Cassandra cluster username – username to connect to Cassandra cluster password – password to connect to Cassandra cluster keyspace_name – name of the keyspace to use table_name – name of the table to use add_message(message: langchain.schema.BaseMessage) → None[source]# Append the message to the record in Cassandra clear() → None[source]# Clear session memory from Cassandra property messages: List[langchain.schema.BaseMessage]# Retrieve the messages from Cassandra pydantic model langchain.memory.ChatMessageHistory[source]# field messages: List[langchain.schema.BaseMessage] = []# add_message(message: langchain.schema.BaseMessage) → None[source]# Add a self-created message to the store clear() → None[source]# Remove all messages from the store pydantic model langchain.memory.CombinedMemory[source]# Class for combining multiple memories’ data together. Validators check_input_key » memories check_repeated_memory_variable » memories field memories: List[langchain.schema.BaseMemory] [Required]# For tracking all the memories that should be accessed. clear() → None[source]# Clear context from this session for every memory.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/memory.html
4092f5c0fde6-1
clear() → None[source]# Clear context from this session for every memory. load_memory_variables(inputs: Dict[str, Any]) → Dict[str, str][source]# Load all vars from sub-memories. save_context(inputs: Dict[str, Any], outputs: Dict[str, str]) → None[source]# Save context from this session for every memory. property memory_variables: List[str]# All the memory variables that this instance provides. pydantic model langchain.memory.ConversationBufferMemory[source]# Buffer for storing conversation memory. field ai_prefix: str = 'AI'# field human_prefix: str = 'Human'# load_memory_variables(inputs: Dict[str, Any]) → Dict[str, Any][source]# Return history buffer. property buffer: Any# String buffer of memory. pydantic model langchain.memory.ConversationBufferWindowMemory[source]# Buffer for storing conversation memory. field ai_prefix: str = 'AI'# field human_prefix: str = 'Human'# field k: int = 5# load_memory_variables(inputs: Dict[str, Any]) → Dict[str, str][source]# Return history buffer. property buffer: List[langchain.schema.BaseMessage]# String buffer of memory. pydantic model langchain.memory.ConversationEntityMemory[source]# Entity extractor & summarizer to memory. field ai_prefix: str = 'AI'# field chat_history_key: str = 'history'# field entity_cache: List[str] = []#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/memory.html
4092f5c0fde6-2
field entity_extraction_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nThe conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\nConversation history:\nPerson #1: how\'s it going today?\nAI: "It\'s going great! How about you?"\nPerson #1: good! busy working on Langchain. lots to do.\nAI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"\nLast line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/memory.html
4092f5c0fde6-3
line:\nPerson #1: i\'m trying to improve Langchain\'s interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I\'m working with Person #2.\nOutput: Langchain, Person #2\nEND OF EXAMPLE\n\nConversation history (for reference only):\n{history}\nLast line of conversation (for extraction):\nHuman: {input}\n\nOutput:', template_format='f-string', validate_template=True)#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/memory.html
4092f5c0fde6-4
field entity_store: langchain.memory.entity.BaseEntityStore [Optional]# field entity_summarization_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['entity', 'summary', 'history', 'input'], output_parser=None, partial_variables={}, template='You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.\nThe update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.\n\nIf there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), return the existing summary unchanged.\n\nFull conversation history (for context):\n{history}\n\nEntity to summarize:\n{entity}\n\nExisting summary of {entity}:\n{summary}\n\nLast line of conversation:\nHuman: {input}\nUpdated summary:', template_format='f-string', validate_template=True)# field human_prefix: str = 'Human'# field k: int = 3# field llm: langchain.base_language.BaseLanguageModel [Required]# clear() → None[source]# Clear memory contents. load_memory_variables(inputs: Dict[str, Any]) → Dict[str, Any][source]# Return history buffer. save_context(inputs: Dict[str, Any], outputs: Dict[str, str]) → None[source]# Save context from this conversation to buffer. property buffer: List[langchain.schema.BaseMessage]# pydantic model langchain.memory.ConversationKGMemory[source]# Knowledge graph memory for storing conversation memory.
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/memory.html
4092f5c0fde6-5
Knowledge graph memory for storing conversation memory. Integrates with external knowledge graph to store and retrieve information about knowledge triples in the conversation. field ai_prefix: str = 'AI'#
rtdocs_stable/api.python.langchain.com/en/stable/reference/modules/memory.html