跳到主要内容
DeepInfraEmbeddings 类利用 DeepInfra API 为给定的文本输入生成嵌入。本指南将引导您完成 DeepInfraEmbeddings 类的设置和使用,帮助您将其无缝集成到您的项目中。

安装

如下所示安装 @langchain/community
有关安装 LangChain 软件包的一般说明,请参阅此部分
npm
npm i @langchain/community @langchain/core

初始化

通过此集成,您可以使用 DeepInfra 嵌入模型来获取文本数据的嵌入。这是嵌入模型的链接 首先,您需要在 DeepInfra 网站上注册并从此处获取 API 令牌。您可以从模型卡复制名称并在代码中使用它们。 要使用 DeepInfraEmbeddings 类,您需要 DeepInfra 的 API 令牌。您可以将此令牌直接传递给构造函数,或者将其设置为环境变量 (DEEPINFRA_API_TOKEN)。

基本用法

以下是创建 DeepInfraEmbeddings 实例的方法
import { DeepInfraEmbeddings } from "@langchain/community/embeddings/deepinfra";

const embeddings = new DeepInfraEmbeddings({
  apiToken: "YOUR_API_TOKEN",
  modelName: "sentence-transformers/clip-ViT-B-32", // Optional, defaults to "sentence-transformers/clip-ViT-B-32"
  batchSize: 1024, // Optional, defaults to 1024
});
如果未提供 apiToken,它将从 DEEPINFRA_API_TOKEN 环境变量中读取。

生成嵌入

嵌入单个查询

要为单个文本查询生成嵌入,请使用 embedQuery 方法
const embedding = await embeddings.embedQuery(
  "What would be a good company name for a company that makes colorful socks?"
);
console.log(embedding);

嵌入多个文档

要为多个文档生成嵌入,请使用 embedDocuments 方法。此方法将根据 batchSize 参数自动处理批处理
const documents = [
  "Document 1 text...",
  "Document 2 text...",
  "Document 3 text...",
];

const embeddingsArray = await embeddings.embedDocuments(documents);
console.log(embeddingsArray);

自定义请求

您可以通过传递 configuration 参数来自定义 SDK 发送请求的基本 URL
const customEmbeddings = new DeepInfraEmbeddings({
  apiToken: "YOUR_API_TOKEN",
  configuration: {
    baseURL: "https://your_custom_url.com",
  },
});
如果需要,这允许您通过自定义端点路由请求。

错误处理

如果未提供 API 令牌且无法在环境变量中找到,将抛出错误
try {
  const embeddings = new DeepInfraEmbeddings();
} catch (error) {
  console.error("DeepInfra API token not found");
}

示例

以下是设置和使用 DeepInfraEmbeddings 类的完整示例
import { DeepInfraEmbeddings } from "@langchain/community/embeddings/deepinfra";

const embeddings = new DeepInfraEmbeddings({
  apiToken: "YOUR_API_TOKEN",
  modelName: "sentence-transformers/clip-ViT-B-32",
  batchSize: 512,
});

async function runExample() {
  const queryEmbedding = await embeddings.embedQuery("Example query text.");
  console.log("Query Embedding:", queryEmbedding);

  const documents = ["Text 1", "Text 2", "Text 3"];
  const documentEmbeddings = await embeddings.embedDocuments(documents);
  console.log("Document Embeddings:", documentEmbeddings);
}

runExample();

反馈与支持

如有反馈或问题,请联系feedback@deepinfra.com
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.