建立 AI 股票 Agent
在本指南中,你會建立一個 Agent,用來擷取指定股票代號上一個交易日的收市價。你會建立一個 Tool 並將它加入 Agent,然後使用 Agent 擷取股票價格。
先決條件先決條件 的直接連結
- 已安裝 Node.js
v22.13.0或更新版本 - 由支援的模型 Provider 提供的 API 金鑰
- 現有的 Mastra 項目(按照安裝指南設定新項目)
建立 Agent建立 Agent 的直接連結
要在 Mastra 中建立 Agent,請使用 Agent 類別定義 Agent,然後向 Mastra 註冊。
建立新檔案
src/mastra/agents/stockAgent.ts,並定義你的 Agent:src/mastra/agents/stockAgent.tsimport { Agent } from '@mastra/core/agent'export const stockAgent = new Agent({id: 'stock-agent',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-5.6-sol',})在
src/mastra/index.ts檔案中註冊 Agent:src/mastra/index.tsimport { Mastra } from '@mastra/core'import { stockAgent } from './agents/stockAgent'export const mastra = new Mastra({agents: { stockAgent },})
建立股票價格 Tool建立股票價格 Tool 的直接連結
Stock Agent 尚未掌握任何目前股票價格的資料。要加入這項功能,請建立一個 Tool 並將它加入 Agent。
建立新檔案
src/mastra/tools/stockPrices.ts。在檔案中加入stockPricesTool,用來擷取指定股票代號上一個交易日的收市價:src/mastra/tools/stockPrices.tsimport { 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 inputData => {console.log('Using tool to fetch stock price for', inputData.symbol)return {symbol: inputData.symbol,currentPrice: await getStockPrice(inputData.symbol),}},})在
src/mastra/agents/stockAgent.ts中匯入剛建立的stockPricesTool,並將它加入 Agent。src/mastra/agents/stockAgent.tsimport { Agent } from '@mastra/core/agent'import { stockPrices } from '../tools/stockPrices'export const stockAgent = new Agent({id: 'stock-agent',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-5.6-sol',tools: {stockPrices,},})
執行 Agent 伺服器執行 Agent 伺服器 的直接連結
了解如何透過 Mastra 的 API 與 Agent 互動。
你可以使用
mastra dev指令,以服務形式執行 Agent:mastra dev這會啟動伺服器,並公開可與已註冊 Agent 互動的端點。你可以在 Studio 中透過 UI 測試
stockAgent和stockPricesTool。mastra dev預設在http://localhost:4111執行。你的 Stock Agent 可透過以下端點存取:POST http://localhost:4111/api/agents/stockAgent/generate你可以在命令列使用
curl與 Agent 互動: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"}這表示 Agent 已成功處理請求,使用
stockPricesTool 擷取股票價格,並傳回結果。