Upstash 儲存
Upstash 儲存實作使用 Upstash 的 Redis 相容 key-value store,提供適合 serverless 的儲存方案。
將 Mastra 與 Upstash 配合使用時,由於 Agent 對話期間會產生大量 Redis 指令,按用量收費模式可能導致意料之外的高昂費用。我們強烈建議使用固定收費計劃,以便預計成本。詳情請參閱 Upstash 收費,背景資料則請參閱 GitHub issue #5850。
Upstash storage 不支援 observability domain。MastraStorageExporter 的 Trace 無法保存至 Upstash,而當 Upstash 是唯一 storage provider 時,Studio 的 observability 功能亦無法運作。如要啟用 observability,請使用 composite storage,將 observability 資料路由至 ClickHouse 等受支援的 Provider。
安裝安裝 的直接連結
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/upstash@latest
pnpm add @mastra/upstash@latest
yarn add @mastra/upstash@latest
bun add @mastra/upstash@latest
用法用法 的直接連結
import { UpstashStore } from '@mastra/upstash'
const storage = new UpstashStore({
id: 'upstash-storage',
url: process.env.UPSTASH_URL,
token: process.env.UPSTASH_TOKEN,
})
參數參數 的直接連結
url:
token:
prefix?:
補充說明補充說明 的直接連結
Key 結構Key 結構 的直接連結
Upstash 儲存實作採用 key-value 結構:
- Thread key:
{prefix}thread:{threadId} - 訊息 key:
{prefix}message:{messageId} - Metadata key:
{prefix}metadata:{entityId}
Serverless 優勢Serverless 優勢 的直接連結
Upstash storage 特別適合 serverless 部署:
- 無需管理連線
- 按請求收費
- 提供全域複寫選項
- 與 edge 相容
資料持久性資料持久性 的直接連結
Upstash 提供:
- 自動保存資料
- 時點復原
- 跨區域複寫選項
效能考慮效能考慮 的直接連結
要取得最佳效能:
- 使用合適的 key prefix 整理資料
- 監察 Redis 記憶體使用量
- 有需要時考慮資料到期政策
用法範例用法範例 的直接連結
為 Agent 加入 memory為 Agent 加入 memory 的直接連結
要為 Agent 加入 Upstash memory,請使用 Memory class,以 UpstashStore 建立新的 storage key,並以 UpstashVector 建立新的 vector key。設定可指向遙距服務或本機環境。
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { UpstashStore } from '@mastra/upstash'
export const upstashAgent = new Agent({
id: 'upstash-agent',
name: 'Upstash Agent',
instructions:
'You are an AI agent with the ability to automatically recall memories from previous interactions.',
model: 'openai/gpt-5.6-sol',
memory: new Memory({
storage: new UpstashStore({
id: 'upstash-agent-storage',
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
}),
options: {
generateTitle: true, // Explicitly enable automatic title generation
},
}),
})
使用 Agent使用 Agent 的直接連結
使用 memoryOptions 設定此請求的 recall 範圍。設定 lastMessages: 5 以限制根據新近程度 recall 的內容,並使用 semanticRecall 擷取最相關的 topK: 3 則訊息,包括每個相符項目前後各 messageRange: 2 則訊息作為內容脈絡。
import 'dotenv/config'
import { mastra } from './mastra'
const threadId = '123'
const resourceId = 'user-456'
const agent = mastra.getAgent('upstashAgent')
const message = await agent.stream('My name is Mastra', {
memory: {
thread: threadId,
resource: resourceId,
},
})
await message.textStream.pipeTo(new WritableStream())
const stream = await agent.stream("What's my name?", {
memory: {
thread: threadId,
resource: resourceId,
},
memoryOptions: {
lastMessages: 5,
semanticRecall: {
topK: 3,
messageRange: 2,
},
},
})
for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}