在 Hono 项目中集成 Mastra
本指南将介绍如何使用 Mastra 和 Hono 构建一个可调用 Tool 的 AI Agent。借助 Hono server adapter,你无需自行编写路由或运行单独的 Mastra 服务器,即可将 Agent 公开为 HTTP 端点。
开始之前开始之前的直接链接
- 你需要受支持的模型 Provider所提供的 API 密钥。如果没有偏好,请使用 OpenAI。
- 安装 Node.js
v22.13.0或更高版本
创建新的 Hono 应用(可选)创建新的 Hono 应用(可选)的直接链接
如果已有 Hono 应用,请跳到下一步。
运行以下命令以创建新的 Hono 应用:
- npm
- pnpm
- Yarn
- Bun
npm create hono@latest mastra-hono -- --template nodejs --install --pm npm
pnpm create hono mastra-hono --template nodejs --install --pm npm
yarn create hono mastra-hono --template nodejs --install --pm npm
bunx create-hono mastra-hono --template nodejs --install --pm npm
这会创建名为 mastra-hono 的项目,你也可以将其替换为任意名称。
初始化 Mastra初始化 Mastra的直接链接
进入 Hono 项目目录:
cd mastra-hono
运行 mastra init。出现提示时,选择 Provider(例如 OpenAI)并输入密钥:
- npm
- pnpm
- Yarn
- Bun
npx mastra@latest init
pnpm dlx mastra@latest init
yarn dlx mastra@latest init
bun x mastra@latest init
这会创建一个 src/mastra 文件夹,其中包含示例天气 Agent 和以下文件:
index.ts- Mastra 配置,包括 memorytools/weather-tool.ts- 获取指定位置天气的 Toolagents/weather-agent.ts- 使用该 Tool 的天气 Agent 及其提示词
稍后你会把 src/mastra/index.ts 文件传给 Hono server adapter。
添加 server adapter添加 server adapter的直接链接
安装 Hono server adapter 软件包:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/hono@latest
pnpm add @mastra/hono@latest
yarn add @mastra/hono@latest
bun add @mastra/hono@latest
打开 Hono 入口文件 src/index.ts,添加所需的导入和初始化代码:
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { type HonoBindings, type HonoVariables, MastraServer } from '@mastra/hono'
import { mastra } from './mastra/index.js'
const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>()
const server = new MastraServer({ app, mastra })
await server.init()
app.get('/', c => {
return c.text('Hello Hono!')
})
serve(
{
fetch: app.fetch,
port: 3000,
},
info => {
console.log(`Server is running on http://localhost:${info.port}`)
},
)
使用现有 Hono app 和根 mastra 实例初始化 MastraServer。调用 init() 会注册 Mastra 中间件并公开所有可用的 Mastra 端点。
测试 Agent测试 Agent的直接链接
默认情况下,Mastra 端点添加在 /api 子路径下,并使用你的 Agent/Workflow ID。由 mastra init 创建的默认 weather-agent 可通过 /api/agents/weather-agent 访问。
启动 Hono 服务器:
- npm
- pnpm
- Yarn
- Bun
npm run dev
pnpm run dev
yarn dev
bun run dev
在另一个终端窗口中,使用 curl 向天气 Agent 提问:
curl -X POST http://localhost:3000/api/agents/weather-agent/generate -H "Content-Type: application/json" -d "{\"messages\":[{\"role\":\"user\",\"content\":\"What is the weather like in Seoul?\"}]}"
后续步骤后续步骤的直接链接
恭喜你使用 Hono 构建了 Mastra Agent!🎉
接下来,你可以使用自己的 Tool 和逻辑扩展项目:
准备就绪后,可进一步了解 Mastra 与 Hono 的集成方式: