Skip to main content
Open In Colab在 GitHub 上打开

自定义嵌入

LangChain 与许多第三方嵌入模型集成。在本指南中,我们将向您展示如何创建自定义 Embedding 类,以防内置类尚不存在。嵌入在自然语言处理应用程序中至关重要,因为它们将文本转换为算法可以理解的数字形式,从而支持广泛的应用程序,例如相似性搜索、文本分类和聚类。

使用标准 Embeddings 接口实现嵌入将允许你的嵌入在现有的LangChain抽象(例如,作为支持 VectorStore 的嵌入或使用 CacheBackedEmbeddings 缓存)。

接口

当前的EmbeddingsLangChain 中的 abstraction 旨在对文本数据进行作。在此实现中,输入是单个字符串或字符串列表,输出是数字数组(向量)列表,其中每个向量表示 将输入文本嵌入到某个 n 维空间中。

您的自定义嵌入必须实现以下方法:

方法/属性描述必需/可选
embed_documents(texts)Generates embeddings for a list of strings.Required
embed_query(text)Generates an embedding for a single text query.Required
aembed_documents(texts)Asynchronously generates embeddings for a list of strings.Optional
aembed_query(text)Asynchronously generates an embedding for a single text query.Optional

这些方法确保您的 embedding 模型可以无缝集成到 LangChain 框架中,从而为可扩展性和性能优化提供同步和异步功能。

注意

Embeddings当前未实现 Runnable 接口,也不是 pydantic 的实例BaseModel.

嵌入查询与文档

embed_queryembed_documents方法是必需的。这些方法都运行 在字符串输入上。访问Document.page_contentattributes 的处理 由 Vector Store 出于遗留原因使用嵌入模型。

embed_query接受单个字符串并返回单个 embedding 作为 float 列表。 如果您的模型具有不同的嵌入查询模式与基础文档,则可以 实现此方法来处理该问题。

embed_documents接收字符串列表,并返回 embeddings 列表作为 float 列表的列表。

注意

embed_documents接受纯文本列表,而不是 LangChain 列表Document对象。此方法的名称 在 LangChain 的未来版本中可能会发生变化。

实现

例如,我们将实现一个返回常量向量的简单嵌入模型。此模型仅用于说明目的。

from typing import List

from langchain_core.embeddings import Embeddings


class ParrotLinkEmbeddings(Embeddings):
"""ParrotLink embedding model integration.

# TODO: Populate with relevant params.
Key init args — completion params:
model: str
Name of ParrotLink model to use.

See full list of supported init args and their descriptions in the params section.

# TODO: Replace with relevant init params.
Instantiate:
.. code-block:: python

from langchain_parrot_link import ParrotLinkEmbeddings

embed = ParrotLinkEmbeddings(
model="...",
# api_key="...",
# other params...
)

Embed single text:
.. code-block:: python

input_text = "The meaning of life is 42"
embed.embed_query(input_text)

.. code-block:: python

# TODO: Example output.

# TODO: Delete if token-level streaming isn't supported.
Embed multiple text:
.. code-block:: python

input_texts = ["Document 1...", "Document 2..."]
embed.embed_documents(input_texts)

.. code-block:: python

# TODO: Example output.

# TODO: Delete if native async isn't supported.
Async:
.. code-block:: python

await embed.aembed_query(input_text)

# multiple:
# await embed.aembed_documents(input_texts)

.. code-block:: python

# TODO: Example output.

"""

def __init__(self, model: str):
self.model = model

def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed search docs."""
return [[0.5, 0.6, 0.7] for _ in texts]

def embed_query(self, text: str) -> List[float]:
"""Embed query text."""
return self.embed_documents([text])[0]

# optional: add custom async implementations here
# you can also delete these, and the base class will
# use the default implementation, which calls the sync
# version in an async executor:

# async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
# """Asynchronous Embed search docs."""
# ...

# async def aembed_query(self, text: str) -> List[float]:
# """Asynchronous Embed query text."""
# ...
API 参考:嵌入

让我们测试一下 🧪

embeddings = ParrotLinkEmbeddings("test-model")
print(embeddings.embed_documents(["Hello", "world"]))
print(embeddings.embed_query("Hello"))
[[0.5, 0.6, 0.7], [0.5, 0.6, 0.7]]
[0.5, 0.6, 0.7]

贡献

我们欢迎 Embedding 模型对 LangChain 代码库的贡献。

如果您打算为新的提供商提供嵌入模型(例如,使用一组新的依赖项或 SDK),我们鼓励您在单独的langchain-*集成包。这将使您能够适当地管理依赖项和对软件包进行版本控制。请参阅我们的贡献指南,了解此过程的演练。