Skip to main content

Mixedbread AI

MixedbreadAIEmbeddings 类使用 Mixedbread AI API 为给定文本生成嵌入向量。本指南将指导你设置和使用 MixedbreadAIEmbeddings 类,帮助你有效地将其集成到项目中。

¥The MixedbreadAIEmbeddings class uses the Mixedbread AI API to generate text embeddings. This guide will walk you through setting up and using the MixedbreadAIEmbeddings class, helping you integrate it into your project effectively.

安装

¥Installation

要安装 @langchain/mixedbread-ai 包,请使用以下命令:

¥To install the @langchain/mixedbread-ai package, use the following command:

npm install @langchain/mixedbread-ai @langchain/core

初始化

¥Initialization

首先,在 Mixedbread AI 网站上注册并从 此处 获取 API 密钥。然后,你可以使用此键初始化 MixedbreadAIEmbeddings 类。

¥First, sign up on the Mixedbread AI website and get your API key from here. You can then use this key to initialize the MixedbreadAIEmbeddings class.

你可以将 API 密钥直接传递给构造函数,也可以将其设置为环境变量 (MXBAI_API_KEY)。

¥You can pass the API key directly to the constructor or set it as an environment variable (MXBAI_API_KEY).

基本用法

¥Basic Usage

以下是如何创建 MixedbreadAIEmbeddings 实例:

¥Here’s how to create an instance of MixedbreadAIEmbeddings:

import { MixedbreadAIEmbeddings } from "@langchain/mixedbread-ai";

const embeddings = new MixedbreadAIEmbeddings({
apiKey: "YOUR_API_KEY",
// Optionally specify model
// model: "mixedbread-ai/mxbai-embed-large-v1",
});

如果未提供 apiKey,则会从 MXBAI_API_KEY 环境变量中读取。

¥If the apiKey is not provided, it will be read from the MXBAI_API_KEY environment variable.

生成嵌入

¥Generating Embeddings

嵌入单个查询

¥Embedding a Single Query

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

¥To generate embeddings for a single text query, use the embedQuery method:

const embedding = await embeddings.embedQuery(
"Represent this sentence for searching relevant passages: Is baking fun?"
);
console.log(embedding);

嵌入多个文档

¥Embedding Multiple Documents

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

¥To generate embeddings for multiple documents, use the embedDocuments method. This method handles batching automatically based on the batchSize parameter:

const documents = ["Baking bread is fun", "I love baking"];

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

自定义请求

¥Customizing Requests

你可以通过传递其他参数来自定义 SDK。

¥You can customize the SDK by passing additional parameters.

const customEmbeddings = new MixedbreadAIEmbeddings({
apiKey: "YOUR_API_KEY",
baseUrl: "...",
maxRetries: 6,
});

错误处理

¥Error Handling

如果未提供 API 密钥,且在环境变量中找不到该密钥,则会抛出错误:

¥If the API key is not provided and cannot be found in the environment variables, an error will be thrown:

try {
const embeddings = new MixedbreadAIEmbeddings();
} catch (error) {
console.error(error);
}

¥Related