嵌入
🌐 Embed
Mastra 使用 AI SDK 的 embed 和 embedMany 功能为文本输入生成向量嵌入,从而实现相似性搜索和 RAG 工作流程。
🌐 Mastra uses the AI SDK's embed and embedMany functions to generate vector embeddings for text inputs, enabling similarity search and RAG workflows.
单个嵌入Direct link to 单个嵌入
🌐 Single Embedding
embed 函数为单个文本输入生成向量嵌入:
🌐 The embed function generates a vector embedding for a single text input:
import { embed } from "ai";
import { ModelRouterEmbeddingModel } from "@mastra/core/llm";
const result = await embed({
model: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
value: "Your text to embed",
maxRetries: 2, // optional, defaults to 2
});
参数Direct link to 参数
🌐 Parameters
model:
EmbeddingModel
The embedding model to use (e.g. openai.embedding('text-embedding-3-small'))
value:
string | Record<string, any>
The text content or object to embed
maxRetries?:
number
= 2
Maximum number of retries per embedding call. Set to 0 to disable retries.
abortSignal?:
AbortSignal
Optional abort signal to cancel the request
headers?:
Record<string, string>
Additional HTTP headers for the request (only for HTTP-based providers)
返回值Direct link to 返回值
🌐 Return Value
embedding:
number[]
The embedding vector for the input
多重嵌入Direct link to 多重嵌入
🌐 Multiple Embeddings
要一次嵌入多个文本,请使用 embedMany 函数:
🌐 For embedding multiple texts at once, use the embedMany function:
import { embedMany } from "ai";
const result = await embedMany({
model: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
values: ["First text", "Second text", "Third text"],
maxRetries: 2, // optional, defaults to 2
});
参数Direct link to 参数
🌐 Parameters
model:
EmbeddingModel
The embedding model to use (e.g. openai.embedding('text-embedding-3-small'))
values:
string[] | Record<string, any>[]
Array of text content or objects to embed
maxRetries?:
number
= 2
Maximum number of retries per embedding call. Set to 0 to disable retries.
abortSignal?:
AbortSignal
Optional abort signal to cancel the request
headers?:
Record<string, string>
Additional HTTP headers for the request (only for HTTP-based providers)
返回值Direct link to 返回值
🌐 Return Value
embeddings:
number[][]
Array of embedding vectors corresponding to the input values
示例用法Direct link to 示例用法
🌐 Example Usage
import { embed, embedMany } from "ai";
// Single embedding
const singleResult = await embed({
model: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
value: "What is the meaning of life?",
});
// Multiple embeddings
const multipleResult = await embedMany({
model: new ModelRouterEmbeddingModel("openai/text-embedding-3-small"),
values: [
"First question about life",
"Second question about universe",
"Third question about everything",
],
});
有关 Vercel AI SDK 中嵌入的更多详细信息,请参见:
🌐 For more detailed information about embeddings in the Vercel AI SDK, see: