動的コンテキスト
動的エージェントは、文脈入力に応じて実行時に振る舞いと能力を柔軟に変化させます。固定的な構成に頼るのではなく、ユーザーや環境、シナリオに合わせて調整し、単一のエージェントでパーソナライズされたコンテキストに即した応答を提供できるようにします。
前提条件
この例では openai
モデルを使用します。.env
ファイルに OPENAI_API_KEY
を追加してください。
.env
OPENAI_API_KEY=<your-api-key>
エージェントの作成
runtimeContext
で提供される動的な値を使って、Mastra Cloud のテクニカルサポートを返すエージェントを作成します。
src/mastra/agents/example-support-agent.ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
export const supportAgent = new Agent({
name: "support-agent",
description: "Returns technical support for mastra cloud based on runtime context",
instructions: async ({ runtimeContext }) => {
const userTier = runtimeContext.get("user-tier");
const language = runtimeContext.get("language");
return `You are a customer support agent for [Mastra Cloud](https://mastra.ai/en/docs/mastra-cloud/overview).
The current user is on the ${userTier} tier.
Support guidance:
${userTier === "free" ? "- Give basic help and link to documentation." : ""}
${userTier === "pro" ? "- Offer detailed technical support and best practices." : ""}
${userTier === "enterprise" ? "- Provide priority assistance with tailored solutions." : ""}
Always respond in ${language}.`;
},
model: openai("gpt-4o")
});
設定オプションの一覧については Agent を参照してください。
エージェントの登録
エージェントを利用するには、メインの Mastra インスタンスに登録してください。
src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { supportAgent } from "./agents/example-support-agent";
export const mastra = new Mastra({
// ...
agents: { supportAgent }
});
使用例
set()
で RuntimeContext
を設定し、続いて getAgent()
でエージェント参照を取得し、最後にプロンプトとともに runtimeContext
を渡して generate()
を呼び出します。
src/test-support-agent.ts
import "dotenv/config";
import { mastra } from "./mastra";
import { RuntimeContext } from "@mastra/core/runtime-context";
type SupportRuntimeContext = {
"user-tier": "free" | "pro" | "enterprise";
language: "en" | "es" | "ja";
};
const runtimeContext = new RuntimeContext<SupportRuntimeContext>();
runtimeContext.set("user-tier", "free");
runtimeContext.set("language", "ja");
const agent = mastra.getAgent("supportAgent");
const response = await agent.generate("Can Mastra Cloud handle long-running requests?", {
runtimeContext
});
console.log(response.text);