マルチエージェントワークフロー
この例では、ワーカーエージェントとスーパーバイザーエージェントの間で作業成果物を受け渡しながら、エージェントベースのワークフローを作成する方法を示します。
この例では、2つのエージェントを順番に呼び出すシーケンシャルなワークフローを作成します。
- 最初のブログ記事を書くCopywriterエージェント
- コンテンツを洗練させるEditorエージェント
まず、必要な依存関係をインポートします。
import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";
import { Agent } from "@mastra/core/agent";
import { Step, Workflow } from "@mastra/core/workflows";
import { z } from "zod";
最初のブログ記事を生成するCopywriterエージェントを作成します。
const copywriterAgent = new Agent({
name: "Copywriter",
instructions: "You are a copywriter agent that writes blog post copy.",
model: anthropic("claude-3-5-sonnet-20241022"),
});
エージェントを実行し、レスポンスを処理するCopywriterステップを定義します。
const copywriterStep = new Step({
id: "copywriterStep",
execute: async ({ context }) => {
if (!context?.triggerData?.topic) {
throw new Error("Topic not found in trigger data");
}
const result = await copywriterAgent.generate(
`Create a blog post about ${context.triggerData.topic}`,
);
console.log("copywriter result", result.text);
return {
copy: result.text,
};
},
});
Copywriterのコンテンツを洗練させるEditorエージェントを設定します。
const editorAgent = new Agent({
name: "Editor",
instructions: "You are an editor agent that edits blog post copy.",
model: openai("gpt-4o-mini"),
});
Copywriterの出力を処理するEditorステップを作成します。
const editorStep = new Step({
id: "editorStep",
execute: async ({ context }) => {
const copy = context?.getStepResult<{ copy: number }>(
"copywriterStep",
)?.copy;
const result = await editorAgent.generate(
`Edit the following blog post only returning the edited copy: ${copy}`,
);
console.log("editor result", result.text);
return {
copy: result.text,
};
},
});
ワークフローを構成し、ステップを実行します。
const myWorkflow = new Workflow({
name: "my-workflow",
triggerSchema: z.object({
topic: z.string(),
}),
});
// Run steps sequentially.
myWorkflow.step(copywriterStep).then(editorStep).commit();
const { runId, start } = myWorkflow.createRun();
const res = await start({
triggerData: { topic: "React JavaScript frameworks" },
});
console.log("Results: ", res.results);
View Example on GitHub