跳至主要內容

在你的 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 create hono@latest mastra-hono -- --template nodejs --install --pm npm

這會建立名為 mastra-hono 的專案,但你可以替換成任何想要的名稱。

初始化 Mastra
「初始化 Mastra」的直接連結

進入 Hono 專案目錄:

cd mastra-hono

執行 mastra init。出現提示時,選擇 Provider(例如 OpenAI)並輸入金鑰:

npx mastra@latest init

這會建立 src/mastra 資料夾,其中包含範例天氣 Agent 和下列檔案:

  • index.ts - Mastra 設定,包含記憶功能
  • tools/weather-tool.ts - 擷取指定位置天氣資訊的 Tool
  • agents/weather-agent.ts- 使用該 Tool 的天氣 Agent,並包含提示詞

稍後你會將 src/mastra/index.ts 檔案傳遞給 Hono server adapter。

加入 server adapter
「加入 server adapter」的直接連結

安裝 Hono server adapter 套件:

npm install @mastra/hono@latest

開啟位於 src/index.ts 的 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}`)
},
)

MastraServer 會使用既有的 Hono app 和根 ⁠mastra 執行個體進行初始化。呼叫 ⁠init() 會註冊 Mastra middleware,並公開所有可用的 Mastra 端點。

測試你的 Agent
「測試你的 Agent」的直接連結

Mastra 端點預設會加入 /api 子路徑下,並使用 Agent/Workflow ID。由 mastra init 建立的預設 weather-agent 可在 /api/agents/weather-agent 使用。

啟動 Hono 伺服器:

npm 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 和邏輯擴充專案:

  • 深入了解 Agent
  • 為 Agent 加入專屬的 Tool
  • 為 Agent 加入類似人類的記憶

準備好後,進一步了解 Mastra 如何與 Hono 整合: