株価エージェント
私たちは、指定されたシンボルの前日の終値を取得するシンプルなエージェントを作成します。この例では、ツールを作成し、それをエージェントに追加して、株価を取得するためにエージェントを使用する方法を示します。
プロジェクト構造
stock-price-agent/
├── src/
│ ├── agents/
│ │ └── stockAgent.ts
│ ├── tools/
│ │ └── stockPrices.ts
│ └── index.ts
├── package.json
└── .env
プロジェクトの初期化と依存関係のインストール
まず、プロジェクト用の新しいディレクトリを作成し、そこに移動します:
mkdir stock-price-agent
cd stock-price-agent
新しいNode.jsプロジェクトを初期化し、必要な依存関係をインストールします:
npm init -y
npm install @mastra/core@latest zod @ai-sdk/openai
環境変数の設定
プロジェクトのルートに.env
ファイルを作成して、OpenAI APIキーを保存します。
.env
OPENAI_API_KEY=your_openai_api_key
必要なディレクトリとファイルを作成します:
mkdir -p src/agents src/tools
touch src/agents/stockAgent.ts src/tools/stockPrices.ts src/index.ts
株価ツールの作成
次に、指定されたシンボルの前日終値を取得するツールを作成します。
src/tools/stockPrices.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
const getStockPrice = async (symbol: string) => {
const data = await fetch(
`https://mastra-stock-data.vercel.app/api/stock-data?symbol=${symbol}`,
).then((r) => r.json());
return data.prices["4. close"];
};
export const stockPrices = createTool({
id: "Get Stock Price",
inputSchema: z.object({
symbol: z.string(),
}),
description: `Fetches the last day's closing stock price for a given symbol`,
execute: async ({ context: { symbol } }) => {
console.log("Using tool to fetch stock price for", symbol);
return {
symbol,
currentPrice: await getStockPrice(symbol),
};
},
});
エージェントにツールを追加する
エージェントを作成し、stockPrices
ツールを追加します。
src/agents/stockAgent.ts
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import * as tools from "../tools/stockPrices";
export const stockAgent = new Agent<typeof tools>({
name: "Stock Agent",
instructions:
"You are a helpful assistant that provides current stock prices. When asked about a stock, use the stock price tool to fetch the stock price.",
model: openai("gpt-4o-mini"),
tools: {
stockPrices: tools.stockPrices,
},
});
Mastraインスタンスの設定
エージェントとツールを使用してMastraインスタンスを初期化する必要があります。
src/index.ts
import { Mastra } from "@mastra/core";
import { stockAgent } from "./agents/stockAgent";
export const mastra = new Mastra({
agents: { stockAgent },
});
アプリケーションの提供
アプリケーションを直接実行する代わりに、mastra dev
コマンドを使用してサーバーを起動します。これにより、エージェントがREST APIエンドポイントを通じて公開され、HTTPを介して対話できるようになります。
ターミナルで、以下のコマンドを実行してMastraサーバーを起動します:
mastra dev --dir src
このコマンドにより、プレイグラウンド内でstockPricesツールとstockAgentをテストすることができます。
これにより、サーバーが起動し、エージェントが以下のURLで利用可能になります:
http://localhost:4111/api/agents/stockAgent/generate
cURLでエージェントをテストする
サーバーが実行されたら、curl
を使用してエージェントのエンドポイントをテストできます:
curl -X POST http://localhost:4111/api/agents/stockAgent/generate \
-H "Content-Type: application/json" \
-d '{
"messages": [
{ "role": "user", "content": "What is the current stock price of Apple (AAPL)?" }
]
}'
予想される応答:
以下のようなJSON応答が返ってくるはずです:
{
"text": "The current price of Apple (AAPL) is $174.55.",
"agent": "Stock Agent"
}
これは、エージェントがリクエストを正常に処理し、stockPrices
ツールを使用して株価を取得し、結果を返したことを示しています。