跳到主要内容

Upstash 存储

Upstash 存储实现使用兼容 Redis 的 Upstash 键值存储,提供适合 serverless 的存储方案。

定价

将 Mastra 与 Upstash 配合使用时,由于 Agent 对话期间会生成大量 Redis 命令,按量付费模式可能导致费用意外升高。我们强烈建议使用固定价格套餐以获得可预测的成本。详情请参阅 Upstash 定价和了解背景的 GitHub issue #5850

不支持 Observability

Upstash 存储不支持 observability 域。来自 MastraStorageExporter 的 Trace 无法持久化到 Upstash,并且仅将 Upstash 作为存储 Provider 时,Studio 的 observability 功能无法使用。若要启用 observability,请使用组合存储将 observability 数据路由到 ClickHouse 等受支持的 Provider。

安装
安装的直接链接

npm install @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 身份验证令牌

prefix?:

string
= mastra:
所有存储项的键前缀

补充说明
补充说明的直接链接

键结构
键结构的直接链接

Upstash 存储实现使用键值结构:

  • Thread 键:{prefix}thread:{threadId}
  • Message 键:{prefix}message:{messageId}
  • Metadata 键:{prefix}metadata:{entityId}

Serverless 优势
Serverless 优势的直接链接

Upstash 存储尤其适合 serverless 部署:

  • 无需管理连接
  • 按请求计费
  • 提供全球复制选项
  • 兼容 Edge

数据持久化
数据持久化的直接链接

Upstash 提供:

  • 自动数据持久化
  • 时间点恢复
  • 跨区域复制选项

性能注意事项
性能注意事项的直接链接

为获得最佳性能:

  • 使用合适的键前缀组织数据
  • 监控 Redis 内存使用情况
  • 如有需要,考虑数据过期策略

使用示例
使用示例的直接链接

向 Agent 添加 memory
向 Agent 添加 memory的直接链接

要向 Agent 添加 Upstash memory,请使用 Memory class,创建一个使用 UpstashStore 的新 storage 键,以及一个使用 UpstashVector 的新 vector 键。配置可以指向远程服务或本地设置。

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 限定本次请求的 recall 范围。设置 lastMessages: 5 以限制基于最近消息的 recall,并使用 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)
}