Embed
Mastra 使用 AI SDK 的 embed 和 embedMany 函数为文本输入生成向量嵌入,从而支持相似度搜索和 RAG workflow。
单个嵌入单个嵌入的直接链接
embed 函数为单个文本输入生成向量嵌入:
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
})
参数参数的直接链接
model:
EmbeddingModel
要使用的嵌入模型(例如 openai.embedding('text-embedding-3-small'))
value:
string | Record<string, any>
要嵌入的文本内容或对象
maxRetries?:
number
= 2
每次嵌入调用的最大重试次数。设为 0 可禁用重试。
abortSignal?:
AbortSignal
用于取消请求的可选中止信号
headers?:
Record<string, string>
请求的附加 HTTP 标头(仅适用于基于 HTTP 的 Provider)
返回值返回值的直接链接
embedding:
number[]
输入的嵌入向量
多个嵌入多个嵌入的直接链接
要一次嵌入多个文本,请使用 embedMany 函数:
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
})
参数参数的直接链接
model:
EmbeddingModel
要使用的嵌入模型(例如 openai.embedding('text-embedding-3-small'))
values:
string[] | Record<string, any>[]
要嵌入的文本内容或对象数组
maxRetries?:
number
= 2
每次嵌入调用的最大重试次数。设为 0 可禁用重试。
abortSignal?:
AbortSignal
用于取消请求的可选中止信号
headers?:
Record<string, string>
请求的附加 HTTP 标头(仅适用于基于 HTTP 的 Provider)
返回值返回值的直接链接
embeddings:
number[][]
与输入值对应的嵌入向量数组
使用示例使用示例的直接链接
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 中嵌入的更多详细信息,请参阅: