第 4 章 · 第一个 Agent
本章目标:掌握
new Agent()的完整构造参数,学会用 instructions 设计行为,并用 generate/stream 两种方式获取输出。
4.1 Agent 的构造参数
Mastra 的 Agent 由四个核心要素构成:
typescript
// src/mastra/agents/chef-agent.ts
import { Agent } from '@mastra/core/agent';
export const chefAgent = new Agent({
// 唯一标识,用于 mastra.getAgent('chef') 取用
id: 'chef',
// 显示名称(Studio 面板中展示)
name: 'Chef Agent',
// 系统提示词:定义角色、能力边界与行为准则
instructions: `
You are a professional chef.
Always answer in Chinese.
Suggest recipes based on ingredients the user has.`,
// 模型:provider/model 字符串格式
model: 'openai/gpt-5-mini',
});| 参数 | 必填 | 说明 |
|---|---|---|
id | 推荐 | 实例内唯一 ID,getAgent 的键 |
name | 是 | 人类可读名称 |
instructions | 是 | 系统提示词,决定角色与行为 |
model | 是 | "provider/model" 字符串 |
tools | 否 | 工具集合(第 5-6 章展开) |
4.2 instructions 设计三原则
instructions 相当于传统软件的"配置文件 + 规范文档",写好它比换模型更能提升效果:
typescript
const goodInstructions = `
You are a customer support agent for an e-commerce platform.
# 职责范围
- 解答订单、物流、退换货问题
- 无法处理的问题引导用户联系人工客服
# 输出规范
- 始终使用中文回答
- 回复不超过 150 字
- 涉及退款时必须先确认订单号
# 禁止行为
- 不承诺具体退款到账时间
- 不透露内部系统信息
`;三条原则:定角色(你是谁)、划边界(只做什么/不做什么)、给格式(语言、长度、结构要求)。
4.3 generate:一次性生成
注册后即可调用。generate() 返回完整结果:
typescript
// src/index.ts —— 入口脚本(Node 22+ 可直接运行 ts)
import { mastra } from './mastra';
const chef = mastra.getAgent('chef');
// 阻塞式调用:等待完整回复
const res = await chef.generate([
{ role: 'user', content: '我有鸡蛋和西红柿,推荐一个菜' },
]);
console.log(res.text);
// 推荐你做经典的西红柿炒鸡蛋……也可以直接传字符串,Mastra 会自动包装成消息数组。
4.4 stream:流式输出
面向用户的场景用 stream() 边生成边推送,首字延迟大幅降低:
typescript
// 流式调用:逐段接收文本增量
const stream = await chef.stream('解释一下分子料理的原理');
for await (const chunk of stream.textStream) {
// 每个 chunk 是一小段新增文本
process.stdout.write(chunk);
}typescript
// Web 服务中的流式响应示例(配合框架返回 SSE)
const stream = await chef.stream(userMessage);
return new Response(stream.textStream, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});4.5 本章小结
- Agent 四要素:id / name / instructions / model,tools 后续章节加入;
- instructions 三原则:定角色、划边界、给格式;
generate()一次拿全量结果,适合后台任务;stream()流式输出,适合用户交互;- 通过
mastra.getAgent(id)从注册中心取用实例。
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. new Agent({...}) 的 model 参数正确取值是?
2. 需要把 AI 结果写入数据库的后台任务,应优先选用哪个方法?
3. 下列哪条 instructions 写法最符合最佳实践?
4. stream() 与 generate() 的关系是?
🛠️ 动手实践
- 创建一个 "code reviewer" Agent,instructions 中规定:只输出 JSON 格式的
{score, issues[]}结构。 - 分别用 generate 和 stream 调用同一个问题,用计时器对比首字节到达时间。
- 故意写一条自相矛盾的 instructions(如"只用英文回答"和"始终用中文"),观察模型的取舍倾向。