跳至主要內容

Embed

Mastra 使用 AI SDK 的 embedembedMany 函式,為文字輸入產生向量嵌入,以支援相似度搜尋與 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 嵌入功能的詳細資訊,請參閱: