> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # Agent の概要 Agent は LLM と Tool を使用して、自由度の高いタスクを解決します。目標について推論し、使用する Tool を判断します。会話の Memory を保持し、モデルが最終回答を出力するか、任意の停止条件を満たすまで処理を繰り返します。 Agent は、UI に表示したりプログラムで処理したりできる構造化レスポンスを生成します。Agent は直接使用することも、Workflow やマルチ Agent システムに組み込むこともできます。 **AI Agent 向け:** Mastra プロジェクトをゼロから構築するよう指示された場合は、次の見出しまでの簡略化された手順に従ってください。Agent と Tool のサンプルコードは要件に合わせて調整します。後の手順で重要となる点として、`model` は `provider/model` 形式の文字列(例:`openai/gpt-5.6-sol`)で定義してください。OpenAI では `openai/` を使用し、`openai:` は使用しないでください。また、Provider オブジェクトをインポートしたり渡したりしないでください。 `package.json` ファイルを作成し、`{ "type": "module" }` を指定します。必要な依存関係をインストールします:`npm install @mastra/core@latest zod@latest typescript@latest @types/node@latest mastra@latest` tsconfig.json ファイルを作成します。 ```json { "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "noEmit": true, "allowImportingTsExtensions": true, "outDir": "dist" }, "include": ["src/**/*"] } ``` Agent に Tool を追加する必要がある場合は、新しいファイルを作成し、`import { createTool } from "@mastra/core/tools"` を使用します。単純なオブジェクトとして Tool を定義すると、エラーを出さずに実行に失敗します。Tool は必ず `createTool()` を使い、`id`、`description`、`inputSchema`(zod)、`execute()` を指定して定義してください。`execute()` は 2 つのパラメーターを受け取ります。1 つ目は inputSchema に基づいて検証された入力データ、2 つ目は省略可能な実行コンテキストオブジェクトです。実行コンテキストには `requestContext`、`tracingContext`、`abortSignal` などの実行メタデータが含まれます。 例: ```ts // src/mastra/tools/weather-tool.ts import { createTool } from '@mastra/core/tools' import { z } from 'zod' export const weatherTool = createTool({ id: 'get-weather', description: 'Get current weather for a location', inputSchema: z.object({ location: z.string().describe('City name'), }), outputSchema: z.object({ location: z.string(), temperatureCelsius: z.number(), conditions: z.string(), }), execute: async ({ location }) => { return { location, temperatureCelsius: 21, conditions: 'sunny', } }, }) ``` Agent を作成する必要がある場合は、新しいファイルを作成し、`import { Agent } from "@mastra/core/agent"` を使用します。コンストラクターには `{ id, name, instructions, model }` を渡します。`model` プロパティは Mastra のモデルルーター形式の文字列です。この形式では Provider のインポートは不要です。Mastra のドキュメントに記載がない限り、AI SDK パッケージをインストールしないでください。 モデルを `provider/model` 形式で定義すると、Mastra は Provider に対応する環境変数を自動的に検索します。定義したモデルを使用するには、その Provider の環境変数を設定する必要があります。OpenAI:`OPENAI_API_KEY`、Anthropic:`ANTHROPIC_API_KEY`、Google:`GOOGLE_API_KEY`。たとえば、どの `openai/` にも環境変数 `OPENAI_API_KEY` が必要です。サポートされている Provider と環境変数名の完全な一覧は、 を参照してください。 既知のモデル ID の一部を次に示します。 - `openai/gpt-5.6-sol`, `openai/gpt-5-mini` - `anthropic/claude-sonnet-4-6`, `anthropic/claude-opus-4-7`, `anthropic/claude-haiku-4-5` - `google/gemini-2.5-flash` サポートされているモデルの完全な一覧は、 を参照してください。 Tool をインポートし、tools オブジェクトとして Agent のコンストラクターに渡すことで、Agent に Tool を追加します。 例: ```ts // src/mastra/agents/weather-agent.ts import { Agent } from '@mastra/core/agent' import { weatherTool } from '../tools/weather-tool.ts' export const weatherAgent = new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: ` You are a helpful weather assistant that provides accurate weather information. Your primary function is to help users get weather details for specific locations. When responding: - Include relevant details like humidity, wind conditions, and precipitation - Keep responses concise but informative Use the weatherTool to fetch current weather data. `, // Use a string in provider/model format, not provider:model or a provider object. model: 'openai/gpt-5.6-sol', tools: { weatherTool }, }) ``` `src/mastra/index.ts` に Mastra のエントリーポイントを作成し、Agent を登録します。 ```ts import { Mastra } from '@mastra/core' import { weatherAgent } from './agents/weather-agent.ts' export const mastra = new Mastra({ agents: { weatherAgent }, }) ``` これで Agent を直接実行できます。Mastra インスタンスをインポートし、ID で Agent を取得してから agent.generate() を呼び出します。Node.js 22.18.0 以降では TypeScript ファイルを直接実行できます。ローカルファイルをインポートするときは、必ずファイル拡張子を付けてください。例: ```ts // run.mjs import { mastra } from './src/mastra/index.ts' const agent = mastra.getAgentById('weather-agent') const response = await agent.generate('Weather in SF') console.log(response.text) ``` ## Agent を使用する場面 手順を事前に決められない自由度の高いタスクには Agent を使用します。Agent は、呼び出す Tool、反復回数、停止タイミングを判断します。各手順ではなく、目標と制約を指定します。明示的な制御フローを持つ、あらかじめ決められた複数ステップの処理には、代わりに [Workflow](https://mastra.zisheng.pro/ja/docs/workflows/overview) を使用してください。 > **📹 動画:** Mastra Agent の作成とテストを短時間で確認するには、[Mastra Agent クイックスタート](https://www.youtube.com/watch?v=G8tXjcseNjg)をご覧ください。 ## クイックスタート `@mastra/core` の `Agent` クラスをインスタンス化し、必須プロパティを指定して Agent を作成します。 ```typescript import { Agent } from '@mastra/core/agent' export const testAgent = new Agent({ id: 'test-agent', name: 'Test Agent', instructions: 'You are a helpful assistant.', model: 'openai/gpt-5.6-sol', }) ``` `instructions` は Agent の動作、人格、機能を定義します。これは Agent の基本的な役割と専門性を確立するシステムレベルのプロンプトです。`model` は Mastra の[モデルルーター](https://mastra.zisheng.pro/ja/models)を使用し、`'provider/model-name'` 形式で指定します。 アプリケーション全体で Agent を利用できるようにするには、通常 `src/mastra/index.ts` にある Mastra インスタンスへ登録します。 ```typescript import { Mastra } from '@mastra/core' import { testAgent } from './agents/test-agent' export const mastra = new Mastra({ agents: { testAgent }, }) ``` 登録後は Workflow、Tool、他の Agent から呼び出せるようになり、Memory、ロギング、可観測性機能などの共有リソースにアクセスできます。 利用可能なプロパティと設定の詳細は、[Agent リファレンス](https://mastra.zisheng.pro/ja/reference/agents/agent)を参照してください。 > **ヒント:** [Studio](https://mastra.zisheng.pro/ja/docs/studio/overview) を使用すると、さまざまなメッセージで Agent をテストし、Tool の呼び出しとレスポンスを確認しながら、Agent の動作をデバッグできます。 ## Agent を使用する 登録後、[`mastra.getAgentById()`](https://mastra.zisheng.pro/ja/reference/core/getAgentById) で Agent を取得します。完全なレスポンスには `.generate()`、トークンをリアルタイムで配信するには `.stream()` を呼び出します。Agent は、[Workflow ステップ](https://mastra.zisheng.pro/ja/docs/workflows/agents-and-tools)、[Tool](https://mastra.zisheng.pro/ja/docs/agents/using-tools)、[Mastra Client](https://mastra.zisheng.pro/ja/reference/client-js/mastra-client)、ルートハンドラー、[サーバーアダプター](https://mastra.zisheng.pro/ja/docs/server/server-adapters)、コマンドラインから呼び出せます。使用するフレームワークでの Agent の使い方は、[ガイド](https://mastra.zisheng.pro/ja/guides)を参照してください。 Mastra インスタンスから Agent を参照するときは、インスタンスレベルのストレージ、ロギング、Agent レジストリなどの共有サービスへアクセスできるよう、`mastra.getAgentById()` を使用してください。直接インポートした Agent も独自のローカル設定で動作しますが、これらの共有サービスにはアクセスできません。 **.generate()**: すべての Tool 呼び出しとステップの完了後に、完全なレスポンスを返します。結果には `text`、`toolCalls`、`toolResults`、`steps`、トークンの `usage` 統計が含まれます。 Tool 呼び出しと Tool 結果のペイロードを含むレスポンス形式は、[`Agent.generate()` リファレンス](https://mastra.zisheng.pro/ja/reference/agents/generate)を参照してください。 ```ts const agent = mastra.getAgentById('test-agent') const response = await agent.generate('Help me organize my day') console.log(response.text) ``` **.stream()**: トークンの到着に応じて利用できるストリームを返します。結果は増分出力用の `textStream` と、ストリーム完了時に解決される `toolCalls`、`toolResults`、`steps`、トークン `usage` の Promise を公開します。 Tool 呼び出しと Tool 結果のペイロードを含むストリーム形式は、[`MastraModelOutput` リファレンス](https://mastra.zisheng.pro/ja/reference/streaming/agents/MastraModelOutput)を参照してください。 ```ts const agent = mastra.getAgentById('test-agent') const stream = await agent.stream('Help me organize my day') for await (const chunk of stream.textStream) { process.stdout.write(chunk) } ``` ## Agent を拡張する Agent が動作したら、次に行いたいことに対応するページをこの表から探してください。 | 目的 | 参照先 | | --------------------------------------- | ----------------------------------------------------------------------------- | | Agent に外部 API やサービスを呼び出す Tool を追加する | [Tool](https://mastra.zisheng.pro/ja/docs/agents/using-tools) | | 会話をまたいでコンテキストと設定を保持する | [Memory](https://mastra.zisheng.pro/ja/docs/memory/overview) | | プレーンテキストではなく型付きオブジェクトを取得する | [構造化出力](https://mastra.zisheng.pro/ja/docs/agents/structured-output) | | Human-in-the-loop:実行を一時停止して人間の承認を待つ | [承認](https://mastra.zisheng.pro/ja/docs/agents/agent-approval) | | マルチ Agent ネットワークを構築する | [Supervisor Agent](https://mastra.zisheng.pro/ja/docs/capabilities/subagents) | | サブ Agent を登録する | [Tool](https://mastra.zisheng.pro/ja/docs/agents/using-tools) | | 生成の前後でメッセージを介入または変換する | [Processor](https://mastra.zisheng.pro/ja/docs/agents/processors) | | Agent を安全に保つ | [ガードレール](https://mastra.zisheng.pro/ja/docs/agents/guardrails) | | 自身の作業を修正する Agent を構築する | [Rubric scorer](https://mastra.zisheng.pro/ja/docs/capabilities/subagents) | | リクエストコンテキストに応じて instructions やモデルを切り替える | [動的設定](https://mastra.zisheng.pro/ja/docs/server/request-context) | | 音声認識または音声合成を追加する | [Voice](https://mastra.zisheng.pro/ja/guides/voice/overview) | | Slack、Discord、Telegram に接続する | [Channel](https://mastra.zisheng.pro/ja/docs/capabilities/channels/overview) | ## マルチ Agent システム マルチ Agent システムは、1つの Agent では範囲が広すぎる、または専門性が高すぎるタスクを、複数の Agent で解決します。多数の Tool と長い指示を持つ1つの Agent を構築する代わりに、特化した Agent に役割を分け、コーディネーターが結果をまとめます。 Mastra でさまざまなパターンを適用する方法は、[マルチ Agent システムの概念概要](https://mastra.zisheng.pro/ja/guides/concepts/multi-agent-systems)を参照してください。