> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Embed Mastra 使用 AI SDK 的 `embed` 及 `embedMany` 函式,為文字輸入產生向量嵌入,從而支援相似度搜尋及 RAG 工作流程。 ## 單一嵌入 `embed` 函式會為單一文字輸入產生向量嵌入: ```typescript 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`): 要嵌入的文字內容或物件 **maxRetries** (`number`): 每次嵌入呼叫的重試次數上限。設為 0 可停用重試。 (Default: `2`) **abortSignal** (`AbortSignal`): 用於取消請求的可選中止訊號 **headers** (`Record`): 請求的額外 HTTP 標頭(只適用於以 HTTP 為基礎的 Provider) ### 傳回值 **embedding** (`number[]`): 輸入內容的嵌入向量 ## 多個嵌入 如要一次嵌入多段文字,請使用 `embedMany` 函式: ```typescript 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[]`): 要嵌入的文字內容或物件陣列 **maxRetries** (`number`): 每次嵌入呼叫的重試次數上限。設為 0 可停用重試。 (Default: `2`) **abortSignal** (`AbortSignal`): 用於取消請求的可選中止訊號 **headers** (`Record`): 請求的額外 HTTP 標頭(只適用於以 HTTP 為基礎的 Provider) ### 傳回值 **embeddings** (`number[][]`): 與輸入值對應的嵌入向量陣列 ## 使用範例 ```typescript 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 的嵌入功能,請參閱: - [AI SDK 嵌入概覽](https://sdk.vercel.ai/docs/ai-sdk-core/embeddings) - [embed()](https://sdk.vercel.ai/docs/reference/ai-sdk-core/embed) - [embedMany()](https://sdk.vercel.ai/docs/reference/ai-sdk-core/embed-many)