Skip to Content
エージェントシステムプロンプトの変更

システムプロンプトの変更

エージェントを作成する際、instructions はその挙動に関する一般的なルールを定義します。これらはエージェントの役割や人格、全体的な方針を定め、すべてのやり取りで一貫して適用されます。特定のリクエストに限ってエージェントの応答傾向に影響を与えたい場合は、元の instructions を変更せずに、.generate()system プロンプトを渡せます。

この例では、system プロンプトを使ってエージェントの声をハリー・ポッターのさまざまな登場人物風に切り替え、コアの設定を変えずに同じエージェントがスタイルを適応できることを示しています。

前提条件

この例では openai モデルを使用します。.env ファイルに OPENAI_API_KEY を追加してください。

.env
OPENAI_API_KEY=<your-api-key>

エージェントの作成

エージェントを定義し、instructions を指定します。これは既定の動作を定義し、実行時にシステムプロンプトが与えられない場合の応答方針を示します。

src/mastra/agents/example-harry-potter-agent.ts
import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; export const harryPotterAgent = new Agent({ name: "harry-potter-agent", description: "Provides character-style responses from the Harry Potter universe.", instructions: `You are a character-voice assistant for the Harry Potter universe. Reply in the speaking style of the requested character (e.g., Harry, Hermione, Ron, Dumbledore, Snape, Hagrid). If no character is specified, default to Harry Potter.`, model: openai("gpt-4o") });

設定オプションの一覧については、Agent を参照してください。

エージェントの登録

エージェントを使用するには、メインの Mastra インスタンスに登録します。

src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra"; import { harryPotterAgent } from "./agents/example-harry-potter-agent"; export const mastra = new Mastra({ // ... agents: { harryPotterAgent } });

デフォルトのキャラクターの応答

getAgent() を使ってエージェントを取得し、プロンプトを渡して generate() を呼び出します。指示にあるとおり、キャラクターを指定しない場合、このエージェントは Harry Potter の口調がデフォルトになります。

src/test-harry-potter-agent.ts
import "dotenv/config"; import { mastra } from "./mastra"; const agent = mastra.getAgent("harryPotterAgent"); const response = await agent.generate("What is your favorite room in Hogwarts?"); console.log(response.text);

キャラクターの口調を変更する

実行時に別の system プロンプトを与えることで、エージェントの口調を別のキャラクターに切り替えられます。これにより、元の指示を変えることなく、そのリクエストに対するエージェントの応答が変わります。

src/test-harry-potter-agent.ts
import "dotenv/config"; import { mastra } from "./mastra"; const agent = mastra.getAgent("harryPotterAgent"); const response = await agent.generate([ { role: "system", content: "You are Draco Malfoy." }, { role: "user", content: "What is your favorite room in Hogwarts?" } ]); console.log(response.text);
View Example on GitHub (outdated)

関連項目