跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

withMastra()

Wraps an AI SDK model with Mastra processors and/or memory.

Usage example
Usage example的直接链接

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?',
})

Parameters
Parameters的直接链接

model:

LanguageModelV2 | LanguageModelV3
Any AI SDK v5 or v6 language model (e.g., openai('gpt-5.4'), anthropic('claude-opus-4-6')).

options?:

WithMastraOptions
Configuration object for processors and memory.
WithMastraOptions

inputProcessors?:

InputProcessor[]
Input processors to run before the LLM call.

outputProcessors?:

OutputProcessor[]
Output processors to run on the LLM response.

memory?:

WithMastraMemoryOptions
Memory configuration - enables automatic message history persistence.
WithMastraMemoryOptions

storage:

MemoryStorage
Memory storage domain for message persistence. Get it from a composite store using await storage.getStore('memory').

threadId:

string
Thread ID for conversation persistence.

resourceId?:

string
Resource ID (user/session identifier).

lastMessages?:

number | false
Number of recent messages to retrieve, or false to disable.

semanticRecall?:

WithMastraSemanticRecallOptions
Semantic recall configuration (RAG-based memory retrieval).

workingMemory?:

MemoryConfig['workingMemory']
Working memory configuration (persistent user data).

readOnly?:

boolean
Read-only mode - prevents saving new messages.

Returns
Returns的直接链接

A wrapped model compatible with generateText, streamText, generateObject, and streamObject.

Streaming behavior
Streaming behavior的直接链接

Output processors that implement processOutputResult run after the stream finishes. Consume the stream to completion to persist message history and semantic recall.

On this page