跳到主要内容

将 Mastra 部署到 Netlify

使用 @mastra/deployer-netlify 在 Netlify 上部署 Mastra Server。该 deployer 会打包代码并生成符合 Netlify Frameworks API.netlify 目录,随时可供部署。你可以部署为 Serverless Function(默认),也可以部署为边缘函数,以获得更低延迟和更长执行时间。

信息

本指南介绍如何部署 Mastra Server。如果你使用的是 Server 适配器Web 框架,请按该框架的常规方式进行部署。

开始之前
开始之前的直接链接

你需要一个 Mastra 应用和一个 Netlify 账户。

注意

Netlify Functions 使用临时文件系统,因此配置的所有 Storage(包括 observability Storage)都必须在外部托管。如果你将 LibSQLStore 与文件 URL 配合使用,请改用远程托管的数据库。

安装
安装的直接链接

@mastra/deployer-netlify 包添加到项目:

npm install @mastra/deployer-netlify@latest

导入 NetlifyDeployer,并在 Mastra 配置中将其设置为 deployer:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { NetlifyDeployer } from '@mastra/deployer-netlify'

export const mastra = new Mastra({
deployer: new NetlifyDeployer(),
})

如需改为部署为边缘函数,请传入 { target: 'edge' }

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { NetlifyDeployer } from '@mastra/deployer-netlify'

export const mastra = new Mastra({
deployer: new NetlifyDeployer({
target: 'edge',
}),
})

边缘函数在最靠近用户的边缘位置使用 Deno 运行。它们没有硬性执行超时(只有 CPU 时间限制),因此更适合长时运行的 AI Workflow。详情请参阅构造函数选项

在项目根目录中创建包含以下内容的 netlify.toml 文件:

[build]
command = "mastra build"

部署
部署的直接链接

设置项目后,将其推送到你选择的远程 Git Provider(例如 GitHub)。

  1. 将仓库连接到 Netlify。在设置过程中,Netlify 会检测 netlify.toml 文件,并将构建命令设置为 mastra build

    备注

    请设置运行应用所需的环境变量(例如模型 Provider API Key)。

  2. 准备就绪后,单击 **Deploy(部署)**按钮,等待首次部署完成。系统会提示已部署一个 函数。

  3. 访问 https://<random-slug>.netlify.app/api/agents 验证部署;该端点应返回 Agent 的 JSON 列表。

    由于 Mastra Server 会为每个 API 端点添加 /api 前缀,因此发出请求时必须将其添加到 URL 中。

    信息

    Netlify Function 通常部署在 https://<random-slug>.netlify.app/.netlify/functions/apiNetlifyDeployer 会将来自 /* 的所有请求重定向到 /.netlify/functions/api/:splat,因此无需在 URL 中包含 .netlify/functions 前缀。

  4. 现在可以通过 HTTP 调用 Mastra 端点。

    注意

    在公开暴露端点之前,请设置身份验证