Embed
Mastra 使用 AI SDK 的 embed 及 embedMany 函式,為文字輸入產生向量嵌入,從而支援相似度搜尋及 RAG 工作流程。
單一嵌入單一嵌入 的直接連結
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 的嵌入功能,請參閱: