2

手工 createTool + Agent,并调用 generate

按官方 condensed 指南手写 weather tool 与 weather agent,注册到 Mastra,用 generate 打出第一句回复。

图文22 分钟Mastra 官方文档 ↗

课程目录2 / 2

学习位置仅保存在当前浏览器,有效期 180 天。

01 / 图文教材

图文讲义

本课严格按官方 Get started condensed instructions 手写最小可调用工具 Agent。

关键规则(官方强调):

  • 工具必须用 createTool()——普通对象定义会静默不执行
  • model 必须是 provider/model 字符串,不要写 openai: 前缀,也不要传入 provider 对象
  • 本地文件 import 需带扩展名(如 .ts
  • 直接跑 TS 示例需要 Node.js 22.18.0+

官方来源

步骤 1:初始化最小工程

目标:建立 ESM 工程并安装官方列出的依赖。

操作

mkdir mastra-manual-demo
cd mastra-manual-demo

写入 package.json

{
  "type": "module"
}

安装依赖:

npm install \
  @mastra/core@latest \
  zod@latest \
  typescript@latest \
  @types/node@latest \
  mastra@latest

写入 tsconfig.json(官方结构):

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "bundler",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}

预期结果

  • node_modules 中出现 @mastra/core
  • npm install 无报错

排错

  • peer 依赖警告可先忽略;若 install 失败,升级 npm 或清理后重试

步骤 2:定义 tool(createTool)

目标:用官方签名创建 weather tool 文件。

操作

创建文件 src/mastra/tools/weather-tool.ts

// src/mastra/tools/weather-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const weatherTool = createTool({
  id: 'get-weather',
  description: 'Get current weather for a location',
  inputSchema: z.object({
    location: z.string().describe('City name'),
  }),
  outputSchema: z.object({
    location: z.string(),
    temperatureCelsius: z.number(),
    conditions: z.string(),
  }),
  execute: async ({ location }) => {
    return {
      location,
      temperatureCelsius: 21,
      conditions: 'sunny',
    }
  },
})

要点:

  • execute 唯一签名是 execute(inputData, context)
  • 第一参是通过 inputSchema 校验后的输入
  • 不需要 context 时可省略第二参

预期结果

  • 文件路径正确;IDE / 编辑器无语法错误

排错

  • 若工具从不被调用:确认使用了 createTool,而不是普通对象字面量

步骤 3:定义 agent 并挂上 tool

目标:创建 Weather Agent,modelprovider/model 字符串。

操作

创建文件 src/mastra/agents/weather-agent.ts

// src/mastra/agents/weather-agent.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool.ts'

export const weatherAgent = new Agent({
  id: 'weather-agent',
  name: 'Weather Agent',
  instructions: `
You are a helpful weather assistant
that provides accurate weather information.

Your primary function is to help users get
weather details for specific locations.
When responding:
- Include relevant details like humidity,
  wind conditions, and precipitation
- Keep responses concise but informative

Use the weatherTool to fetch current weather data.
`,
  // provider/model string — not provider:model
  // and not a provider object.
  model: 'openai/gpt-5.6-sol',
  tools: { weatherTool },
})

官方当前示例模型 ID 还包括:openai/gpt-5-minianthropic/claude-sonnet-4-6anthropic/claude-opus-4-7anthropic/claude-haiku-4-5google/gemini-2.5-flash。完整列表见 Mastra models

预期结果

  • Agent 文件可被后续 index.ts 导入
  • tools: { weatherTool } 已挂载

排错

  • 模型报错:核对 provider/ 前缀与环境变量名是否匹配

步骤 4:注册到 Mastra 入口

目标:在 src/mastra/index.ts 导出 mastra 实例。

操作

创建文件 src/mastra/index.ts

// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { weatherAgent } from './agents/weather-agent.ts'

export const mastra = new Mastra({
  agents: { weatherAgent },
})

预期结果

  • 可用 mastra.getAgentById('weather-agent') 取到 Agent

步骤 5:设置环境变量并调用 generate

目标:用官方 run.mjs 跑通第一次 generate

操作

export OPENAI_API_KEY=你的密钥

创建项目根目录 run.mjs

// run.mjs
import { mastra } from './src/mastra/index.ts'

const agent = mastra.getAgentById('weather-agent')
const response = await agent.generate(
  'Weather in SF',
)
console.log(response.text)

运行:

node run.mjs

预期结果

  • 终端打印助手文本
  • 内容应引用 weatherTool 返回的旧金山天气(示例数据为 21°C / sunny;真实模型措辞可变)

排错

  • 缺 API Key:应失败并提示环境变量——补上后再跑
  • ERR_MODULE_NOT_FOUND:确认本地 import 带了 .ts 扩展名,且 Node ≥ 22.18.0
  • 工具未触发:回到步骤 2,确认 createTooltools: { weatherTool }

可选:用 .stream() 代替 .generate() 做流式输出(见 Agents overview)。

步骤 6:本课验收清单

  • 工具经 createTool 定义,而非普通对象
  • modelprovider/model 字符串,且环境变量已设
  • mastra.getAgentById('weather-agent')generate 返回 response.text
  • 本地文件 import 均带 .ts 扩展名

延伸阅读(官方)

  • 框架集成:Quickstart 内 “Integrate with your framework”
  • Templates / use cases:见 Mastra Docs

代码与命令摘录自 Mastra 官方文档;品牌/封面图来自 mastra.ai 官方资源。