withMastra()
使用 Mastra 处理器和/或 memory 封装 AI SDK 模型。
使用示例使用示例的直接链接
src/example.ts
import { openai } from '@ai-sdk/openai'
import { generateText } from 'ai'
import { withMastra } from '@mastra/ai-sdk'
import type { Processor } from '@mastra/core/processors'
const loggingProcessor: Processor<'logger'> = {
id: 'logger',
async processInput({ messages }) {
console.log('Input:', messages.length, 'messages')
return messages
},
}
const model = withMastra(openai('gpt-5.4'), {
inputProcessors: [loggingProcessor],
})
const { text } = await generateText({
model,
prompt: 'What is 2 + 2?',
})
参数参数的直接链接
model:
LanguageModelV2 | LanguageModelV3
任意 AI SDK v5 或 v6 语言模型(例如
openai('gpt-5.4')、anthropic('claude-opus-4-6'))。options?:
WithMastraOptions
处理器和 memory 的配置对象。
WithMastraOptions
inputProcessors?:
InputProcessor[]
在调用 LLM 前运行的 input processor。
outputProcessors?:
OutputProcessor[]
对 LLM 响应运行的 output processor。
memory?:
WithMastraMemoryOptions
Memory 配置,用于启用消息历史记录的自动持久化。
WithMastraMemoryOptions
storage:
MemoryStorage
用于持久化消息的 memory storage domain。可通过
await storage.getStore('memory') 从 composite store 获取。threadId:
string
用于持久化对话的 thread ID。
resourceId?:
string
Resource ID(用户/session 标识符)。
lastMessages?:
number | false
要检索的近期消息数量;设为 false 可禁用。
semanticRecall?:
WithMastraSemanticRecallOptions
semantic recall 配置(基于 RAG 的 memory 检索)。
workingMemory?:
MemoryConfig['workingMemory']
working memory 配置(持久化用户数据)。
readOnly?:
boolean
只读模式,可阻止保存新消息。
返回值返回值的直接链接
封装后的模型,与 generateText、streamText、generateObject 和 streamObject 兼容。
流式传输行为流式传输行为的直接链接
实现 processOutputResult 的 output processor 会在 stream 结束后运行。请完整消费 stream,以持久化消息历史记录和 semantic recall。