langchain_community.vectorstores.lantern.Lantern

class langchain_community.vectorstores.lantern.Lantern(connection_string: str, embedding_function: Embeddings, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None)[source]

Postgres with the lantern extension as a vector store.

lantern uses sequential scan by default. but you can create a HNSW index using the create_hnsw_index method. - connection_string is a postgres connection string. - embedding_function any embedding function implementing

langchain.embeddings.base.Embeddings interface.

  • collection_name is the name of the collection to use. (default: langchain)
    • NOTE: This is the name of the table in which embedding data will be stored

      The table will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables.

  • distance_strategy is the distance strategy to use. (default: EUCLIDEAN)
    • EUCLIDEAN is the euclidean distance.

    • COSINE is the cosine distance.

    • HAMMING is the hamming distance.

  • pre_delete_collection if True, will delete the collection if it exists.

    (default: False) - Useful for testing.

Attributes

distance_function

distance_strategy

embeddings

Access the query embedding object if available.

Methods

__init__(connection_string, embedding_function)

aadd_documents(documents, **kwargs)

Async run more documents through the embeddings and add to the vectorstore.

aadd_texts(texts[, metadatas])

Async run more texts through the embeddings and add to the vectorstore.

add_documents(documents, **kwargs)

Add or update documents in the vectorstore.

add_embeddings(texts, embeddings, metadatas, ...)

add_texts(texts[, metadatas, ids])

Run more texts through the embeddings and add to the vectorstore.

adelete([ids])

Async delete by vector ID or other criteria.

afrom_documents(documents, embedding, **kwargs)

Async return VectorStore initialized from documents and embeddings.

afrom_texts(texts, embedding[, metadatas])

Async return VectorStore initialized from texts and embeddings.

aget_by_ids(ids, /)

Async get documents by their IDs.

amax_marginal_relevance_search(query[, k, ...])

Async return docs selected using the maximal marginal relevance.

amax_marginal_relevance_search_by_vector(...)

Async return docs selected using the maximal marginal relevance.

as_retriever(**kwargs)

Return VectorStoreRetriever initialized from this VectorStore.

asearch(query, search_type, **kwargs)

Async return docs most similar to query using a specified search type.

asimilarity_search(query[, k])

Async return docs most similar to query.

asimilarity_search_by_vector(embedding[, k])

Async return docs most similar to embedding vector.

asimilarity_search_with_relevance_scores(query)

Async return docs and relevance scores in the range [0, 1].

asimilarity_search_with_score(*args, **kwargs)

Async run similarity search with distance.

astreaming_upsert(items, /, batch_size, **kwargs)

aupsert(items, /, **kwargs)

connect()

connection_string_from_db_params(driver, ...)

Return connection string from database parameters.

create_collection()

create_hnsw_extension()

create_hnsw_index([dims, m, ...])

Create HNSW index on collection.

create_tables_if_not_exists()

delete([ids])

Delete vectors by ids or uuids.

delete_collection()

drop_index()

drop_table()

drop_tables()

from_documents(documents, embedding[, ...])

Initialize a vector store with a set of documents.

from_embeddings(text_embeddings, embedding)

Construct Lantern wrapper from raw documents and pre- generated embeddings.

from_existing_index(embedding[, ...])

Get instance of an existing Lantern store.This method will return the instance of the store without inserting any new embeddings

from_texts(texts, embedding[, metadatas, ...])

Initialize Lantern vectorstore from list of texts.

get_by_ids(ids, /)

Get documents by their IDs.

max_marginal_relevance_search(query[, k, ...])

Return docs selected using the maximal marginal relevance.

max_marginal_relevance_search_by_vector(...)

Return docs selected using the maximal marginal relevance

max_marginal_relevance_search_with_score(query)

Return docs selected using the maximal marginal relevance with score.

max_marginal_relevance_search_with_score_by_vector(...)

Return docs selected using the maximal marginal relevance with score

search(query, search_type, **kwargs)

Return docs most similar to query using a specified search type.

similarity_search(query[, k, filter])

Return docs most similar to query.

similarity_search_by_vector(embedding[, k, ...])

Return docs most similar to embedding vector.

similarity_search_with_relevance_scores(query)

Return docs and relevance scores in the range [0, 1].

similarity_search_with_score(query[, k, filter])

Run similarity search with distance.

similarity_search_with_score_by_vector(embedding)

streaming_upsert(items, /, batch_size, **kwargs)

upsert(items, /, **kwargs)

Parameters
  • connection_string (str) –

  • embedding_function (Embeddings) –

  • distance_strategy (DistanceStrategy) –

  • collection_name (str) –

  • collection_metadata (Optional[dict]) –

  • pre_delete_collection (bool) –

  • logger (Optional[logging.Logger]) –

  • relevance_score_fn (Optional[Callable[[float], float]]) –

__init__(connection_string: str, embedding_function: Embeddings, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, collection_name: str = 'langchain', collection_metadata: Optional[dict] = None, pre_delete_collection: bool = False, logger: Optional[Logger] = None, relevance_score_fn: Optional[Callable[[float], float]] = None) None[source]
Parameters
  • connection_string (str) –

  • embedding_function (Embeddings) –

  • distance_strategy (DistanceStrategy) –

  • collection_name (str) –

  • collection_metadata (Optional[dict]) –

  • pre_delete_collection (bool) –

  • logger (Optional[Logger]) –

  • relevance_score_fn (Optional[Callable[[float], float]]) –

Return type

None

async aadd_documents(documents: List[Document], **kwargs: Any) List[str]

Async run more documents through the embeddings and add to the vectorstore.

Parameters
  • documents (List[Document]) – Documents to add to the vectorstore.

  • kwargs (Any) – Additional keyword arguments.

Returns

List of IDs of the added texts.

Raises

ValueError – If the number of IDs does not match the number of documents.

Return type

List[str]

async aadd_texts(texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any) List[str]

Async run more texts through the embeddings and add to the vectorstore.

Parameters
  • texts (Iterable[str]) – Iterable of strings to add to the vectorstore.

  • metadatas (Optional[List[dict]]) – Optional list of metadatas associated with the texts. Default is None.

  • **kwargs (Any) – vectorstore specific parameters.

Returns

List of ids from adding the texts into the vectorstore.

Raises
  • ValueError – If the number of metadatas does not match the number of texts.

  • ValueError – If the number of ids does not match the number of texts.

Return type

List[str]

add_documents(documents: List[Document], **kwargs: Any) List[str]

Add or update documents in the vectorstore.

Parameters
  • documents (List[Document]) – Documents to add to the vectorstore.

  • kwargs (Any) – Additional keyword arguments. if kwargs contains ids and documents contain ids, the ids in the kwargs will receive precedence.

Returns

List of IDs of the added texts.

Raises

ValueError – If the number of ids does not match the number of documents.

Return type

List[str]

add_embeddings(texts: List[str], embeddings: List[List[float]], metadatas: List[dict], ids: List[str], **kwargs: Any) None[source]
Parameters
  • texts (List[str]) –

  • embeddings (List[List[float]]) –

  • metadatas (List[dict]) –

  • ids (List[str]) –

  • kwargs (Any) –

Return type

None

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[str]) – Iterable of strings to add to the vectorstore.

  • metadatas (Optional[List[dict]]) – 可选的与文本关联的元数据列表。

  • **kwargs (Any) – vectorstore 特定参数。 其中一个 kwargs 应该是 ids,它是与文本关联的 id 列表。

  • ids (Optional[List[str]]) –

  • **kwargs

Returns

List of ids from adding the texts into the vectorstore.

Raises
  • ValueError – If the number of metadatas does not match the number of texts.

  • ValueError – If the number of ids does not match the number of texts.

Return type

List[str]

async adelete(ids: Optional[List[str]] = None, **kwargs: Any) Optional[bool]

Async delete by vector ID or other criteria.

Parameters
  • ids (Optional[List[str]]) – 要删除的 id 列表。 如果为 None,则删除全部。 默认为 None。

  • **kwargs (Any) – 子类可能使用的其他关键字参数。

Returns

如果删除成功,则为 True,否则为 False;如果未实现,则为 None。

Return type

Optional[bool]

async classmethod afrom_documents(documents: List[Document], embedding: Embeddings, **kwargs: Any) VST

Async return VectorStore initialized from documents and embeddings.

Parameters
  • documents (List[Document]) – 要添加到向量存储的文档列表。

  • embedding (Embeddings) – 要使用的嵌入函数。

  • kwargs (Any) – Additional keyword arguments.

Returns

从文档和嵌入初始化的 VectorStore。

Return type

VectorStore

async classmethod afrom_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any) VST

Async return VectorStore initialized from texts and embeddings.

Parameters
  • texts (List[str]) – 要添加到向量存储的文本。

  • embedding (Embeddings) – 要使用的嵌入函数。

  • metadatas (Optional[List[dict]]) – Optional list of metadatas associated with the texts. Default is None.

  • kwargs (Any) – Additional keyword arguments.

Returns

从文本和嵌入初始化的 VectorStore。

Return type

VectorStore

async aget_by_ids(ids: Sequence[str], /) List[Document]

Async get documents by their IDs.

返回的文档应将 ID 字段设置为向量存储中文档的 ID。

如果某些 ID 未找到或存在重复 ID,则返回的文档可能少于请求的文档。

用户不应假定返回文档的顺序与输入 ID 的顺序匹配。 相反,用户应依赖返回文档的 ID 字段。

如果某些 ID 没有找到文档,此方法**不应**引发异常。

Parameters

ids (Sequence[str]) – 要检索的 id 列表。

Returns

文档列表。

Return type

List[Document]

0.2.11 版本新增功能。

Async return docs selected using the maximal marginal relevance.

最大边际相关性优化了与查询的相似性以及所选文档之间的多样性。

Parameters
  • query (str) – 用于查找相似文档的文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • fetch_k (int) – 要提取并传递给 MMR 算法的文档数量。 默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,它确定结果之间多样性的程度,其中 0 对应于最大多样性,1 对应于最小多样性。 默认为 0.5。

  • kwargs (Any) –

Returns

通过最大边际相关性选择的文档列表。

Return type

List[Document]

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[Document]

Async return docs selected using the maximal marginal relevance.

最大边际相关性优化了与查询的相似性以及所选文档之间的多样性。

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 要返回的文档数量。 默认为 4。

  • fetch_k (int) – 要提取并传递给 MMR 算法的文档数量。 默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,它确定结果之间多样性的程度,其中 0 对应于最大多样性,1 对应于最小多样性。 默认为 0.5。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

通过最大边际相关性选择的文档列表。

Return type

List[Document]

as_retriever(**kwargs: Any) VectorStoreRetriever

Return VectorStoreRetriever initialized from this VectorStore.

Parameters

**kwargs (Any) –

传递给搜索函数的关键字参数。 可以包括: search_type (Optional[str]): 定义检索器应执行的搜索类型。

可以是 “similarity”(默认)、“mmr” 或 “similarity_score_threshold”。

search_kwargs (Optional[Dict]): 传递给搜索函数的关键字参数。
可以包括如下内容

k: 要返回的文档数量(默认值:4) score_threshold: 相似度分数阈值的最小相关性阈值

用于 similarity_score_threshold

fetch_k: 要传递给 MMR 算法的文档数量

(默认值:20)

lambda_mult: MMR 返回的结果的多样性;

1 表示最小多样性,0 表示最大多样性。 (默认值:0.5)

filter: 按文档元数据筛选

Returns

VectorStore 的 Retriever 类。

Return type

VectorStoreRetriever

示例

# Retrieve more documents with higher diversity
# Useful if your dataset has many similar documents
docsearch.as_retriever(
    search_type="mmr",
    search_kwargs={'k': 6, 'lambda_mult': 0.25}
)

# Fetch more documents for the MMR algorithm to consider
# But only return the top 5
docsearch.as_retriever(
    search_type="mmr",
    search_kwargs={'k': 5, 'fetch_k': 50}
)

# Only retrieve documents that have a relevance score
# Above a certain threshold
docsearch.as_retriever(
    search_type="similarity_score_threshold",
    search_kwargs={'score_threshold': 0.8}
)

# Only get the single most similar document from the dataset
docsearch.as_retriever(search_kwargs={'k': 1})

# Use a filter to only retrieve documents from a specific paper
docsearch.as_retriever(
    search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}
)
async asearch(query: str, search_type: str, **kwargs: Any) List[Document]

Async return docs most similar to query using a specified search type.

Parameters
  • query (str) – 输入文本。

  • search_type (str) – 要执行的搜索类型。 可以是 “similarity”、“mmr” 或 “similarity_score_threshold”。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询最相似的文档列表。

Raises

ValueError – 如果 search_type 不是 “similarity”、“mmr” 或 “similarity_score_threshold” 之一。

Return type

List[Document]

Async return docs most similar to query.

Parameters
  • query (str) – 输入文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询最相似的文档列表。

Return type

List[Document]

async asimilarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) List[Document]

Async return docs most similar to embedding vector.

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 要返回的文档数量。 默认为 4。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询向量最相似的文档列表。

Return type

List[Document]

async asimilarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]]

Async return docs and relevance scores in the range [0, 1].

0 表示不相似,1 表示最相似。

Parameters
  • query (str) – 输入文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • **kwargs (Any) –

    要传递给相似性搜索的 kwargs。 应包括: score_threshold:可选,介于 0 到 1 之间的浮点值,用于

    筛选检索到的文档结果集

Returns

(doc, similarity_score) 元组的列表

Return type

List[Tuple[Document, float]]

async asimilarity_search_with_score(*args: Any, **kwargs: Any) List[Tuple[Document, float]]

Async run similarity search with distance.

Parameters
  • *args (Any) – 传递给搜索方法的参数。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

(doc, similarity_score) 元组的列表。

Return type

List[Tuple[Document, float]]

astreaming_upsert(items: AsyncIterable[Document], /, batch_size: int, **kwargs: Any) AsyncIterator[UpsertResponse]

Beta

在 0.2.11 中添加。 API 可能会发生变化。

以流式方式 Upsert 文档。 streaming_upsert 的异步版本。

Parameters
  • items (AsyncIterable[Document]) – 要添加到向量存储的文档的可迭代对象。

  • batch_size (int) – 每次批量 upsert 的大小。

  • kwargs (Any) – 附加关键字参数。 kwargs 应仅包含所有文档通用的参数。 (例如,索引超时、重试策略等)kwargs 不应包含 id 以避免语义不明确。 而是应将 ID 作为 Document 对象的一部分提供。

Yields

UpsertResponse – 响应对象,其中包含在向量存储中成功添加或更新的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

AsyncIterator[UpsertResponse]

0.2.11 版本新增功能。

async aupsert(items: Sequence[Document], /, **kwargs: Any) UpsertResponse

Beta

在 0.2.11 中添加。 API 可能会发生变化。

在向量存储中添加或更新文档。 upsert 的异步版本。

如果提供了 Document 对象的 ID 字段,则 upsert 功能应使用该字段。 如果未提供 ID,则 upsert 方法可以自由地为文档生成 ID。

当指定了 ID 并且文档已存在于向量存储中时,upsert 方法应使用新数据更新文档。 如果文档不存在,则 upsert 方法应将文档添加到向量存储中。

Parameters
  • items (Sequence[Document]) – 要添加到向量存储的文档序列。

  • kwargs (Any) – Additional keyword arguments.

Returns

响应对象,其中包含在向量存储中成功添加或更新的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

UpsertResponse

0.2.11 版本新增功能。

connect() Connection[source]
Return type

Connection

classmethod connection_string_from_db_params(driver: str, host: str, port: int, database: str, user: str, password: str) str[source]

Return connection string from database parameters.

Parameters
  • driver (str) –

  • host (str) –

  • port (int) –

  • database (str) –

  • user (str) –

  • password (str) –

Return type

str

create_collection() None[source]
Return type

None

create_hnsw_extension() None[source]
Return type

None

create_hnsw_index(dims: int = 1536, m: int = 16, ef_construction: int = 64, ef_search: int = 64, **_kwargs: Any) None[source]

Create HNSW index on collection.

HNSW 索引的可选关键字参数

engine: “nmslib”, “faiss”, “lucene”; 默认值:“nmslib”

ef:k-NN 搜索期间使用的动态列表的大小。 值越高,搜索越准确,但速度越慢;默认值:64

ef_construction:k-NN 图创建期间使用的动态列表的大小。 值越高,图越准确,但索引速度越慢;默认值:64

m:为每个新元素创建的双向链接数。 对内存消耗有很大影响。 介于 2 和 100 之间;默认值:16

dims:集合中向量的维度。 默认值:1536

Parameters
  • dims (int) –

  • m (int) –

  • ef_construction (int) –

  • ef_search (int) –

  • _kwargs (Any) –

Return type

None

create_tables_if_not_exists() None[source]
Return type

None

delete(ids: Optional[List[str]] = None, **kwargs: Any) None[source]

Delete vectors by ids or uuids.

Parameters
  • ids (Optional[List[str]]) – 要删除的 id 列表。

  • kwargs (Any) –

Return type

None

delete_collection() None[source]
Return type

None

drop_index() None[source]
Return type

None

drop_table() None[source]
Return type

None

drop_tables() None[source]
Return type

None

classmethod from_documents(documents: List[Document], embedding: Embeddings, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) Lantern[source]

Initialize a vector store with a set of documents.

需要 Postgres 连接字符串。“可以将其作为 connection_string 参数传递,或者设置 LANTERN_CONNECTION_STRING 环境变量。

  • connection_string 是 Postgres 连接字符串。

  • documentsDocument 列表,用于初始化向量存储。

  • embeddingEmbeddings,将用于

    嵌入发送的文本。如果未发送任何内容,则将使用多语言 Tensorflow Universal Sentence Encoder。

  • collection_name is the name of the collection to use. (default: langchain)
    • NOTE: This is the name of the table in which embedding data will be stored

      The table will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables.

  • distance_strategy is the distance strategy to use. (default: EUCLIDEAN)
    • EUCLIDEAN is the euclidean distance.

    • COSINE is the cosine distance.

    • HAMMING is the hamming distance.

  • ids 要插入到集合中的行 ID。

  • pre_delete_collection if True, will delete the collection if it exists.

    (default: False) - Useful for testing.

Parameters
  • documents (List[Document]) –

  • embedding (Embeddings) –

  • collection_name (str) –

  • distance_strategy (DistanceStrategy) –

  • ids (Optional[List[str]]) –

  • pre_delete_collection (bool) –

  • kwargs (Any) –

Return type

Lantern

classmethod from_embeddings(text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', ids: Optional[List[str]] = None, pre_delete_collection: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, **kwargs: Any) Lantern[source]

Construct Lantern wrapper from raw documents and pre- generated embeddings.

需要 Postgres 连接字符串。“可以将其作为 connection_string 参数传递,或者设置 LANTERN_CONNECTION_STRING 环境变量。

列表 idstext_embeddingsmetadatas 中元素的顺序应匹配,以便每行都与正确的值关联。

  • connection_string 是 Postgres 数据库的完整连接字符串

  • text_embeddings 是包含元组 (文本, 嵌入) 的数组

    用于插入到集合中。

  • embeddingEmbeddings,将用于

    嵌入发送的文本。如果未发送任何内容,则将使用多语言 Tensorflow Universal Sentence Encoder。

  • metadatas 要插入到集合中的行元数据。

  • collection_name is the name of the collection to use. (default: langchain)
    • NOTE: This is the name of the table in which embedding data will be stored

      The table will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables.

  • ids 要插入到集合中的行 ID。

  • pre_delete_collection if True, will delete the collection if it exists.

    (default: False) - Useful for testing.

  • distance_strategy is the distance strategy to use. (default: EUCLIDEAN)
    • EUCLIDEAN is the euclidean distance.

    • COSINE is the cosine distance.

    • HAMMING is the hamming distance.

Parameters
  • text_embeddings (List[Tuple[str, List[float]]]) –

  • embedding (Embeddings) –

  • metadatas (Optional[List[dict]]) –

  • collection_name (str) –

  • ids (Optional[List[str]]) –

  • pre_delete_collection (bool) –

  • distance_strategy (DistanceStrategy) –

  • kwargs (Any) –

Return type

Lantern

classmethod from_existing_index(embedding: Embeddings, collection_name: str = 'langchain', pre_delete_collection: bool = False, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, **kwargs: Any) Lantern[source]

Get instance of an existing Lantern store.This method will return the instance of the store without inserting any new embeddings

需要 Postgres 连接字符串。“可以将其作为 connection_string 参数传递,或者设置 LANTERN_CONNECTION_STRING 环境变量。

  • connection_string 是 Postgres 连接字符串。

  • embeddingEmbeddings,将用于

    嵌入发送的文本。如果未发送任何内容,则将使用多语言 Tensorflow Universal Sentence Encoder。

  • collection_name is the name of the collection to use. (default: langchain)
    • NOTE: This is the name of the table in which embedding data will be stored

      The table will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables.

  • ids 要插入到集合中的行 ID。

  • pre_delete_collection if True, will delete the collection if it exists.

    (default: False) - Useful for testing.

  • distance_strategy is the distance strategy to use. (default: EUCLIDEAN)
    • EUCLIDEAN is the euclidean distance.

    • COSINE is the cosine distance.

    • HAMMING is the hamming distance.

Parameters
  • embedding (Embeddings) –

  • collection_name (str) –

  • pre_delete_collection (bool) –

  • distance_strategy (DistanceStrategy) –

  • kwargs (Any) –

Return type

Lantern

classmethod from_texts(texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = 'langchain', distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any) Lantern[source]

从文本列表初始化 Lantern 向量存储。 嵌入将使用提供的 embedding 类生成。

列表 idstextsmetadatas 中元素的顺序应匹配,以便每行都与正确的值关联。

需要 Postgres 连接字符串。“可以将其作为 connection_string 参数传递,或者设置 LANTERN_CONNECTION_STRING 环境变量。

  • connection_string 是 Postgres 数据库的完整连接字符串

  • texts 要插入到集合中的文本。

  • embeddingEmbeddings,将用于

    嵌入发送的文本。如果未发送任何内容,则将使用多语言 Tensorflow Universal Sentence Encoder。

  • metadatas 要插入到集合中的行元数据。

  • collection_name is the name of the collection to use. (default: langchain)
    • NOTE: This is the name of the table in which embedding data will be stored

      The table will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables.

  • distance_strategy is the distance strategy to use. (default: EUCLIDEAN)
    • EUCLIDEAN is the euclidean distance.

    • COSINE is the cosine distance.

    • HAMMING is the hamming distance.

  • ids 要插入到集合中的行 ID。

  • pre_delete_collection if True, will delete the collection if it exists.

    (default: False) - Useful for testing.

Parameters
  • texts (List[str]) –

  • embedding (Embeddings) –

  • metadatas (Optional[List[dict]]) –

  • collection_name (str) –

  • distance_strategy (DistanceStrategy) –

  • ids (Optional[List[str]]) –

  • pre_delete_collection (bool) –

  • kwargs (Any) –

Return type

Lantern

get_by_ids(ids: Sequence[str], /) List[Document]

Get documents by their IDs.

返回的文档应将 ID 字段设置为向量存储中文档的 ID。

如果某些 ID 未找到或存在重复 ID,则返回的文档可能少于请求的文档。

用户不应假定返回文档的顺序与输入 ID 的顺序匹配。 相反,用户应依赖返回文档的 ID 字段。

如果某些 ID 没有找到文档,此方法**不应**引发异常。

Parameters

ids (Sequence[str]) – 要检索的 id 列表。

Returns

文档列表。

Return type

List[Document]

0.2.11 版本新增功能。

Return docs selected using the maximal marginal relevance.

最大边际相关性优化查询的相似性和多样性

在选定的文档中。

Parameters
  • query (str) – 用于查找相似文档的文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • fetch_k (int) – 要提取以传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,它确定结果之间多样性的程度,其中 0 对应于最大多样性,1 对应于最小多样性。 默认为 0.5。

  • filter (Optional[Dict[str, str]]) – 按元数据过滤。默认为 None。

  • kwargs (Any) –

Returns

通过最大边际相关性选择的文档列表。

Return type

List[Document]

max_marginal_relevance_search_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) List[Document][source]
Return docs selected using the maximal marginal relevance

到嵌入向量。

最大边际相关性优化查询的相似性和多样性

在选定的文档中。

Parameters
  • embedding (str) – 用于查找相似文档的文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • fetch_k (int) – 要提取以传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,它确定结果之间多样性的程度,其中 0 对应于最大多样性,1 对应于最小多样性。 默认为 0.5。

  • filter (Optional[Dict[str, str]]) – 按元数据过滤。默认为 None。

  • kwargs (Any) –

Returns

通过最大边际相关性选择的文档列表。

Return type

List[Document]

max_marginal_relevance_search_with_score(query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[dict] = None, **kwargs: Any) List[Tuple[Document, float]][source]

Return docs selected using the maximal marginal relevance with score.

最大边际相关性优化查询的相似性和多样性

在选定的文档中。

Parameters
  • query (str) – 用于查找相似文档的文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • fetch_k (int) – 要提取以传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,它确定结果之间多样性的程度,其中 0 对应于最大多样性,1 对应于最小多样性。 默认为 0.5。

  • filter (Optional[Dict[str, str]]) – 按元数据过滤。默认为 None。

  • kwargs (Any) –

Returns

通过最大边际选择的文档列表

与查询的相关性以及每个文档的分数。

Return type

List[Tuple[Document, float]]

max_marginal_relevance_search_with_score_by_vector(embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any) List[Tuple[Document, float]][source]
Return docs selected using the maximal marginal relevance with score

到嵌入向量。

最大边际相关性优化查询的相似性和多样性

在选定的文档中。

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 要返回的文档数量。 默认为 4。

  • fetch_k (int) – 要提取以传递给 MMR 算法的文档数量。默认为 20。

  • lambda_mult (float) – 介于 0 和 1 之间的数字,它确定结果之间多样性的程度,其中 0 对应于最大多样性,1 对应于最小多样性。 默认为 0.5。

  • filter (Optional[Dict[str, str]]) – 按元数据过滤。默认为 None。

  • kwargs (Any) –

Returns

通过最大边际选择的文档列表

与查询的相关性以及每个文档的分数。

Return type

List[Tuple[Document, float]]

search(query: str, search_type: str, **kwargs: Any) List[Document]

Return docs most similar to query using a specified search type.

Parameters
  • query (str) – 输入文本

  • search_type (str) – 要执行的搜索类型。 可以是 “similarity”、“mmr” 或 “similarity_score_threshold”。

  • **kwargs (Any) – 传递给搜索方法的参数。

Returns

与查询最相似的文档列表。

Raises

ValueError – 如果 search_type 不是 “similarity”、“mmr” 或 “similarity_score_threshold” 之一。

Return type

List[Document]

Return docs most similar to query.

Parameters
  • query (str) – 输入文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • **kwargs (Any) – 传递给搜索方法的参数。

  • filter (Optional[dict]) –

  • **kwargs

Returns

与查询最相似的文档列表。

Return type

List[Document]

similarity_search_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None, **kwargs: Any) List[Document][source]

Return docs most similar to embedding vector.

Parameters
  • embedding (List[float]) – 用于查找相似文档的嵌入向量。

  • k (int) – 要返回的文档数量。 默认为 4。

  • **kwargs (Any) – 传递给搜索方法的参数。

  • filter (Optional[dict]) –

  • **kwargs

Returns

与查询向量最相似的文档列表。

Return type

List[Document]

similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) List[Tuple[Document, float]]

Return docs and relevance scores in the range [0, 1].

0 表示不相似,1 表示最相似。

Parameters
  • query (str) – 输入文本。

  • k (int) – 要返回的文档数量。 默认为 4。

  • **kwargs (Any) –

    要传递给相似性搜索的 kwargs。 应包括: score_threshold:可选,介于 0 到 1 之间的浮点值,用于

    筛选检索到的文档结果集。

Returns

(doc, similarity_score) 元组的列表。

Return type

List[Tuple[Document, float]]

similarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None) List[Tuple[Document, float]][source]

Run similarity search with distance.

Parameters
  • *args – 传递给搜索方法的参数。

  • **kwargs – 传递给搜索方法的参数。

  • query (str) –

  • k (int) –

  • filter (Optional[dict]) –

Returns

(doc, similarity_score) 元组的列表。

Return type

List[Tuple[Document, float]]

similarity_search_with_score_by_vector(embedding: List[float], k: int = 4, filter: Optional[dict] = None) List[Tuple[Document, float]][source]
Parameters
  • embedding (List[float]) –

  • k (int) –

  • filter (Optional[dict]) –

Return type

List[Tuple[Document, float]]

streaming_upsert(items: Iterable[Document], /, batch_size: int, **kwargs: Any) Iterator[UpsertResponse]

Beta

在 0.2.11 中添加。 API 可能会发生变化。

以流式方式更新文档。

Parameters
  • items (Iterable[Document]) – 要添加到向量存储的可迭代文档。

  • batch_size (int) – 每次批量 upsert 的大小。

  • kwargs (Any) – 额外的关键字参数。kwargs 应该只包含所有文档通用的参数。(例如,索引超时、重试策略等)kwargs 不应包含 ids 以避免语义模糊。相反,ID 应该作为 Document 对象的一部分提供。

Yields

UpsertResponse – 响应对象,其中包含在向量存储中成功添加或更新的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

Iterator[UpsertResponse]

0.2.11 版本新增功能。

upsert(items: Sequence[Document], /, **kwargs: Any) UpsertResponse

Beta

在 0.2.11 中添加。 API 可能会发生变化。

Add or update documents in the vectorstore.

如果提供了 Document 对象的 ID 字段,则 upsert 功能应使用该字段。 如果未提供 ID,则 upsert 方法可以自由地为文档生成 ID。

当指定了 ID 并且文档已存在于向量存储中时,upsert 方法应使用新数据更新文档。 如果文档不存在,则 upsert 方法应将文档添加到向量存储中。

Parameters
  • items (Sequence[Document]) – 要添加到向量存储的文档序列。

  • kwargs (Any) – Additional keyword arguments.

Returns

响应对象,其中包含在向量存储中成功添加或更新的 ID 列表,以及未能添加或更新的 ID 列表。

Return type

UpsertResponse

0.2.11 版本新增功能。

使用 Lantern 的示例