Skip to main content

DeepInfra 嵌入模型

DeepInfraEmbeddings 类利用 DeepInfra API 为给定的文本输入生成嵌入。本指南将指导您完成 DeepInfraEmbeddings 类的安装和使用,帮助您将其无缝集成到您的项目中。

安装

按照以下方式安装 @langchain/community 包:

:::提示 请参阅安装集成包的一般说明部分。 :::

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", // 可选,默认为 "sentence-transformers/clip-ViT-B-32"
batchSize: 1024, // 可选,默认为 1024
});

如果没有提供 apiToken,它将从 DEEPINFRA_API_TOKEN 环境变量中读取。

生成嵌入

嵌入单个查询

要为单个文本查询生成嵌入,请使用 embedQuery 方法:

const embedding = await embeddings.embedQuery(
"为一家生产彩色袜子的公司取个好名字是什么?"
);
console.log(embedding);

嵌入多个文档

要为多个文档生成嵌入,请使用 embedDocuments 方法。此方法将根据 batchSize 参数自动处理批处理:

const documents = [
"文档 1 文本...",
"文档 2 文本...",
"文档 3 文本...",
];

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 密钥");
}

示例

以下是如何设置和使用 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("示例查询文本。");
console.log("查询嵌入:", queryEmbedding);

const documents = ["文本 1", "文本 2", "文本 3"];
const documentEmbeddings = await embeddings.embedDocuments(documents);
console.log("文档嵌入:", documentEmbeddings);
}

runExample();

反馈与支持

如需反馈或疑问,请联系 [email protected]

相关内容


Was this page helpful?


You can also leave detailed feedback on GitHub.