🧠

Mastraでマルチエージェントワークフローを動かすまでの備忘録

に公開

背景

現在、社内でAIチャットボットを開発しています。こちらのAIチャットボットでは、質問を投げるとまず社内のナレッジ情報を検索し、検索にヒットしない場合はWeb検索を行い回答を返すような動作を期待しています。このようなエージェントを階層型マルチエージェントで構築しようとしたところ、いくつか問題点が出てきました。たとえば社内のナレッジ情報が検索ヒットせずWeb検索を実行しても、Web検索結果ではなくLLMが生成した結果を回答に使うといった問題が発生しました。

このような結果になってしまったのはAIエージェントのシステムプロンプトの記述のみで条件分岐のような制御を行っているためだと考えました。そこで今回はAIチャットボットにマルチエージェントワークフローを適用することを視野に入れ、前段階としていったんMastraの公式サンプルコードにあるマルチエージェントワークフローの動作検証を行います。社内プロダクトで使用しているライブラリのバージョンだとMastraの公式サンプルコードが動かなかったため、備忘録として今回動作検証したプログラムをこちらの記事に記載しました。

環境

項目 バージョン
OS Windows11
ランタイム Node.js v22.14.0
主要ライブラリ "@ai-sdk/azure": "^1.3.23", "@mastra/core": "^0.10.4", "zod": "^3.25.76"
LLM Azure OpenAI(gpt-4.1-mini)

公式のサンプルコードについて

サンプルにおけるマルチエージェントワークフローでは以下の2つのエージェントが登場します。

  • ブログの記事を書くCopywriterエージェント
  • ブログ記事の編集を行うEditorエージェント

この2つのエージェントがワークフローで逐次的に呼び出されひとつのブログ記事を作成します。
サンプルコードでは「React JavaScript frameworks」の記事を書くため、ワークフローを実行しています。

ソースコード

import { Agent } from '@mastra/core/agent';
import { createWorkflow, createStep } from '@mastra/core/workflows';
import { createAzure } from "@ai-sdk/azure";
import { config } from "./config.js";
import { z } from "zod";

// Azure接続
const azure = createAzure({ apiKey: config.apiKey, resourceName: config.resourceName });

// Copywriterエージェント
const copywriterAgent = new Agent({
  name: "Copywriter",
  instructions: "You are a copywriter agent that writes blog post copy.",
  model: azure('gpt-4.1-mini'),
});

// Copywriterステップ
const copywriterStep = new createStep({
  id: "copywriterStep",
  execute: async (context) => {
    const topic = context?.inputData?.topic;
    const result = await copywriterAgent.generate(`Create a blog post about ${topic}`);
    return { copy: result.text };
  },
});

// Editorエージェント
const editorAgent = new Agent({
  name: "Editor",
  instructions: "You are an editor agent that edits blog post copy.",
  model: azure('gpt-4.1-mini'),
});

// Editorステップ
const editorStep = new createStep({
  id: "editorStep",
  execute: async ( context ) => {
    const copy = context?.inputData?.copy;
    const result = await editorAgent.generate(`Edit the following blog post: ${copy}`);
    return { copy: result.text };
  },
});

// ワークフロー定義
const myWorkflow = new createWorkflow({
  name: "my-workflow",
  triggerSchema: z.object({ topic: z.string() }),
});

// ステップを順番に登録
myWorkflow.then(copywriterStep).then(editorStep).commit();

// ワークフロー実行
const res = await myWorkflow.createRun().start({ inputData: { topic: "React JavaScript frameworks" } });

console.dir(res.result);

ポイント

  1. WorkflowStepとをimportするのではなく、createWorkflowcreateStepのimportを行う。

  2. copywriterStep、editorStepの各ステップで渡されるコンテキスト情報の取得の仕方はcontext?.triggerData?.<data_name>ではなくcontext?.inputData?.<data_name>のようなかたちで行う。

  3. workflowのステップの登録はmyWorkflow.step(...).then(...).commit()ではなく、myWorkflow.then(copywriterStep).then(editorStep).commit();のように行う。(全てthenで登録を行う)

実行結果

以下のような記事が作成されました。

{
  copy: '**Exploring React JavaScript Frameworks: Building Modern Web Applications with Ease**\n' +
    '\n' +
    'In the ever-evolving world of web development, React has emerged as one of the most popular JavaScript libraries for building user interfaces. Developed and maintained by Facebook, React offers a component-based architecture that simplifies the creation of interactive and dynamic web applications. Beyond the core React library, a rich ecosystem of frameworks built around React enhances its capabilities and streamlines the development process. In this blog post, we’ll explore some of the top React JavaScript frameworks and how they can help you build modern web applications with ease.\n' +
    '\n' +
    '### What is React?\n' +
    '\n' +
    'Before diving into frameworks, it’s important to understand what React itself is. React is a JavaScript library focused on building UI components. It allows developers to create reusable components that manage their own state and efficiently update and render just the right parts of the UI when data changes. React’s virtual DOM and declarative syntax have made it a favorite among developers for building fast and scalable web apps.\n' +
    '\n' +
    '### Why Use a React Framework?\n' +
    '\n' +
    'While React provides the building blocks for UI development, it doesn’t prescribe how to handle routing, state management, server-side rendering, or other common application needs. This is where React frameworks come in. They offer a more opinionated structure and come bundled with tools and features that simplify complex tasks, allowing developers to focus on building features rather than configuring infrastructure.\n' +
    '\n' +
    '### Top React JavaScript Frameworks\n' +
    '\n' +
    '#### 1. Next.js\n' +
    '\n' +
    'Next.js is arguably the most popular React framework today. It offers server-side rendering (SSR), static site generation (SSG), and incremental static regeneration out of the box. This means you can build fast, SEO-friendly websites and web apps with minimal configuration. Next.js also supports API routes, making it easy to build full-stack applications.\n' +
    '\n' +
    '**Key Features:**\n' +
    '- Hybrid static and server rendering\n' +
    '- File-based routing system\n' +
    '- Built-in CSS and Sass support\n' +
    '- API routes for backend functionality\n' +
    '- Automatic code splitting and optimization\n' +
    '\n' +
    '#### 2. Gatsby\n' +
    '\n' +
    'Gatsby is a React-based framework focused on building blazing-fast static websites. It pulls data from various sources like CMSs, APIs, and databases during build time to generate static HTML files. This approach results in highly performant sites with excellent SEO.\n' +
    '\n' +
    '**Key Features:**\n' +
    '- Static site generation\n' +
    '- Rich plugin ecosystem\n' +
    '- GraphQL data layer for flexible data sourcing\n' +
    '- Optimized image handling\n' +
    '- Progressive Web App (PWA) support\n' +
    '\n' +
    '#### 3. Remix\n' +
    '\n' +
    'Remix is a newer React framework that emphasizes web standards and server-side rendering. It provides a seamless developer experience with nested routing, data loading, and error handling baked in. Remix aims to deliver fast, resilient web apps with minimal client-side JavaScript.\n' +
    '\n' +
    '**Key Features:**\n' +
    '- Nested routes with data loading\n' +
    '- Built-in form handling and validation\n' +
    '- Server-side rendering with streaming\n' +
    '- Focus on progressive enhancement\n' +
    '- Flexible deployment options\n' +
    '\n' +
    '#### 4. Razzle\n' +
    '\n' +
    'Razzle abstracts the complex configuration needed for server-side rendering with React. It provides a universal JavaScript framework that works with any backend, allowing you to build SSR apps without worrying about Webpack or Babel setup.\n' +
    '\n' +
    '**Key Features:**\n' +
    '- Zero-config SSR setup\n' +
    '- Supports multiple frameworks (React, Vue, etc.)\n' +
    '- Customizable build pipeline\n' +
    '- Compatible with any backend technology\n' +
    '\n' +
    '### Choosing the Right Framework\n' +
    '\n' +
    'Selecting the right React framework depends on your project requirements:\n' +
    '\n' +
    '- **For SEO-focused, dynamic web apps:** Next.js is an excellent choice.\n' +
    '- **For static sites with rich content:** Gatsby excels.\n' +
    '- **For web standards and progressive enhancement:** Remix offers a modern approach.\n' +
    '- **For flexible SSR with minimal configuration:** Razzle is worth considering.\n' +
    '\n' +
    '### Conclusion\n' +
    '\n' +
    'React’s flexibility and component-based architecture have revolutionized front-end development. By leveraging React frameworks like Next.js, Gatsby, Remix, or Razzle, developers can accelerate their workflow, improve performance, and build scalable, maintainable web applications. Whether you’re building a blog, e-commerce site, or complex web app, there’s a React framework tailored to your needs.\n' +
    '\n' +
    'Start exploring these frameworks today and take your React projects to the next level!\n' +
    '\n' +
    '---\n' +
    '\n' +
    '**Have you used any of these React frameworks? Share your experiences and favorite features in the comments below!**'
}

まとめ & 次のステップ

  • 弊社プロダクトで使っているライブラリのバージョンでマルチエージェントワークフローを動作させました
  • 次のステップとして社内ナレッジ検索とWeb検索を呼び分けるようなマルチエージェントワークフローを実現させたいです
セリオ株式会社 テックブログ

Discussion