Skip to content

Chapter 4 · Your First Agent ​

Chapter goals: Master the complete constructor parameters of new Agent(), learn to design behavior with instructions, and obtain output via both generate() and stream() methods.

4.1 Agent Constructor Parameters ​

A Mastra Agent consists of four core elements:

typescript
// src/mastra/agents/chef-agent.ts
import { Agent } from '@mastra/core/agent';

export const chefAgent = new Agent({
  // Unique identifier; used as the key for mastra.getAgent('chef')
  id: 'chef',
  // Display name (shown in Studio panels)
  name: 'Chef Agent',
  // System prompt: defines role, capability boundaries, and behavioral rules
  instructions: `
    You are a professional chef.
    Always answer in Chinese.
    Suggest recipes based on ingredients the user has.`,
  // Model: provider/model string format
  model: 'openai/gpt-5-mini',
});
ParameterRequiredDescription
idRecommendedUnique instance ID; key for getAgent
nameYesHuman-readable name
instructionsYesSystem prompt; defines role and behavior
modelYes"provider/model" string
toolsNoTool collection (covered in Chapters 5–6)

4.2 Three Principles of instructions Design ​

instructions is equivalent to a traditional software's "config file + specification document." Writing it well improves results more than switching models:

typescript
const goodInstructions = `
You are a customer support agent for an e-commerce platform.

# Responsibilities
- Answer questions about orders, logistics, and returns
- Guide users to contact human support for issues you cannot handle

# Output Rules
- Always respond in Chinese
- Keep responses under 150 characters
- When discussing refunds, confirm the order number first

# Prohibited Behaviors
- Never promise specific refund arrival times
- Never reveal internal system information
`;

Three principles: define the role (who you are), draw boundaries (what to do / what not to do), give format (language, length, structural requirements).

4.3 generate: Single-Shot Generation ​

Call immediately after registration. generate() returns the complete result:

typescript
// src/index.ts —— entry script (Node 22+ can run TypeScript directly)
import { mastra } from './mastra';

const chef = mastra.getAgent('chef');

// Blocking call: wait for the full reply
const res = await chef.generate([
  { role: 'user', content: 'I have eggs and tomatoes — recommend a dish' },
]);

console.log(res.text);
// I recommend the classic tomato and egg stir-fry……

You can also pass a plain string — Mastra auto-wraps it into a messages array.

4.4 stream: Streaming Output ​

For user-facing scenarios, stream() pushes output chunk by chunk as it's generated — dramatically reducing time-to-first-byte:

typescript
// Streaming call: receive text increments piece by piece
const stream = await chef.stream('Explain the principles of molecular gastronomy');

for await (const chunk of stream.textStream) {
  // Each chunk is a small increment of new text
  process.stdout.write(chunk);
}
typescript
// Streaming response example in a web service (with SSE framing)
const stream = await chef.stream(userMessage);
return new Response(stream.textStream, {
  headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});

4.5 Chapter Summary ​

  • Agent four elements: id / name / instructions / model; tools added in later chapters;
  • instructions three principles: define role, draw boundaries, give format;
  • generate() returns the full result at once — best for background tasks; stream() pushes incrementally — best for user interaction;
  • Access instances via mastra.getAgent(id) from the registry.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is the correct value type for the model parameter in new Agent({...})?

2. For a background task that writes AI results to a database, which method should you优先 use?

3. Which instructions writing style best follows best practices?

4. What is the relationship between stream() and generate()?

🛠️ Hands-On Exercises ​

  1. Create a "code reviewer" Agent with instructions requiring JSON output in {score, issues[]} structure.
  2. Call the same question with both generate() and stream(); time the time-to-first-byte for each.
  3. Write contradictory instructions (e.g., "only answer in English" and "always answer in Chinese") and observe how the model resolves the conflict.

Next: Chapter 5 · Tools Definition