Upstash 儲存空間
Upstash 儲存空間實作採用與 Redis 相容的 Upstash key-value store,提供適合 serverless 的儲存解決方案。
定價
搭配 Upstash 使用 Mastra 時,由於 Agent 對話期間會產生大量 Redis 指令,隨用隨付模式可能導致意外的高額費用。強烈建議使用固定費率方案,讓費用更容易預估。詳情請參閱 Upstash 定價,相關背景請參閱 GitHub issue #5850。
不支援可觀測性
安裝「安裝」的直接連結
- 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:
string
Upstash Redis URL
token:
string
Upstash Redis 驗證 token
prefix?:
string
= mastra:
所有已儲存項目的 key prefix
其他注意事項「其他注意事項」的直接連結
Key 結構「Key 結構」的直接連結
Upstash 儲存空間實作使用 key-value 結構:
- Thread key:
{prefix}thread:{threadId} - 訊息 key:
{prefix}message:{messageId} - Metadata key:
{prefix}metadata:{entityId}
Serverless 的優點「Serverless 的優點」的直接連結
Upstash 儲存空間特別適合 serverless 部署:
- 不需要管理連線
- 依請求計費
- 提供全域複寫選項
- 與 edge 相容
資料持久化「資料持久化」的直接連結
Upstash 提供:
- 自動資料持久化
- 時間點還原
- 跨區域複寫選項
效能注意事項「效能注意事項」的直接連結
若要取得最佳效能:
- 使用適當的 key prefix 整理資料
- 監控 Redis 記憶體用量
- 視需要考慮資料到期政策
使用範例「使用範例」的直接連結
為 Agent 新增記憶體「為 Agent 新增記憶體」的直接連結
若要為 Agent 新增 Upstash 記憶體,請使用 Memory 類別,以 UpstashStore 建立新的 storage key,並以 UpstashVector 建立新的 vector key。此設定可以指向遠端服務或本機環境。
src/mastra/agents/example-upstash-agent.ts
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 設定此請求的回憶範圍。設定 lastMessages: 5 以限制依時間順序回憶的訊息數量,並使用 semanticRecall 擷取 topK: 3 筆最相關訊息;其中包含 messageRange: 2 筆相鄰訊息,作為各配對結果的上下文。
src/test-upstash-agent.ts
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)
}