跳到主要内容

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", // 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


此页面对您有帮助吗?


您也可以留下详细的反馈 在 GitHub 上.