ExamplesAgentsHierarchical Multi-Agent System

Hierarchical Multi-Agent System

This example demonstrates how to create a hierarchical multi-agent system where agents interact through tool functions, with one agent coordinating the work of others.

The system consists of three agents:

  1. A Publisher agent (supervisor) that orchestrates the process
  2. A Copywriter agent that writes the initial content
  3. An Editor agent that refines the content

First, define the Copywriter agent and its tool:

const copywriterAgent = new Agent({
  name: "Copywriter",
  instructions: "You are a copywriter agent that writes blog post copy.",
  model: {
    provider: "ANTHROPIC",
    name: "claude-3-5-sonnet-20241022",
    toolChoice: "required",
  },
});
 
const copywriterTool = createTool({
  id: "copywriter-agent",
  description: "Calls the copywriter agent to write blog post copy.",
  inputSchema: z.object({
    topic: z.string().describe("Blog post topic"),
  }),
  outputSchema: z.object({
    copy: z.string().describe("Blog post copy"),
  }),
  execute: async ({ context }) => {
    const result = await copywriterAgent.generate(
      `Create a blog post about ${context.topic}`,
    );
    return { copy: result.text };
  },
});

Next, define the Editor agent and its tool:

const editorAgent = new Agent({
  name: "Editor",
  instructions: "You are an editor agent that edits blog post copy.",
  model: {
    provider: "OPEN_AI",
    name: "gpt-4o",
  },
});
 
const editorTool = createTool({
  id: "editor-agent",
  description: "Calls the editor agent to edit blog post copy.",
  inputSchema: z.object({
    copy: z.string().describe("Blog post copy"),
  }),
  outputSchema: z.object({
    copy: z.string().describe("Edited blog post copy"),
  }),
  execute: async ({ context }) => {
    const result = await editorAgent.generate(
      `Edit the following blog post only returning the edited copy: ${context.copy}`,
    );
    return { copy: result.text };
  },
});

Finally, create the Publisher agent that coordinates the others:

const publisherAgent = new Agent({
  name: "publisherAgent",
  instructions:
    "You are a publisher agent that first calls the copywriter agent to write blog post copy about a specific topic and then calls the editor agent to edit the copy. Just return the final edited copy.",
  model: {
    provider: "ANTHROPIC",
    name: "claude-3-5-sonnet-20241022",
  },
  tools: { copywriterTool, editorTool },
});
 
const mastra = new Mastra({
  agents: { publisherAgent },
});

To use the entire system:

async function main() {
  const agent = mastra.getAgent("publisherAgent");
  const result = await agent.generate(
    "Write a blog post about React JavaScript frameworks. Only return the final edited copy.",
  );
  console.log(result.text);
}
 
main();





View Example on GitHub

MIT 2025 © Nextra.