Skip to main content
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

相关