跳至主要內容

建構 AI 股票 Agent

在本指南中,你將建立一個 Agent,用來擷取指定股票代號前一日的收盤價。你會建立一個 tool 並將它加入 Agent,接著使用 Agent 擷取股票價格。

先決條件
「先決條件」的直接連結

  • 已安裝 Node.js v22.13.0 或更新版本
  • 具備受支援 Model Provider 的 API key
  • 已有 Mastra 專案(請依照安裝指南設定新專案)

建立 Agent
「建立 Agent」的直接連結

若要在 Mastra 中建立 Agent,請使用 Agent class 定義 Agent,再向 Mastra 註冊。

  1. 建立新檔案 src/mastra/agents/stockAgent.ts 並定義 Agent:

    src/mastra/agents/stockAgent.ts
    import { 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',
    })
  2. src/mastra/index.ts 檔案中註冊 Agent:

    src/mastra/index.ts
    import { Mastra } from '@mastra/core'
    import { stockAgent } from './agents/stockAgent'

    export const mastra = new Mastra({
    agents: { stockAgent },
    })

建立股票價格 tool
「建立股票價格 tool」的直接連結

Stock Agent 目前還不知道任何即時股票價格資訊。若要改變這一點,請建立一個 tool 並將它加入 Agent。

  1. 建立新檔案 src/mastra/tools/stockPrices.ts。在其中新增 stockPrices tool,用來擷取指定股票代號前一日的收盤價:

    src/mastra/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 inputData => {
    console.log('Using tool to fetch stock price for', inputData.symbol)
    return {
    symbol: inputData.symbol,
    currentPrice: await getStockPrice(inputData.symbol),
    }
    },
    })
  2. src/mastra/agents/stockAgent.ts 中匯入剛建立的 stockPrices tool,並將它加入 Agent。

    src/mastra/agents/stockAgent.ts
    import { 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 server
「執行 Agent server」的直接連結

了解如何透過 Mastra API 與 Agent 互動。

  1. 你可以使用 mastra dev command,將 Agent 作為服務執行:

    mastra dev

    這會啟動伺服器並公開 endpoint,讓你與已註冊的 Agent 互動。在 Studio 中,你可以透過 UI 測試 stockAgentstockPrices tool。

  2. mastra dev 預設會在 http://localhost:4111 執行。Stock Agent 可透過下列位置存取:

    POST http://localhost:4111/api/agents/stockAgent/generate
  3. 你可以從 command line 使用 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 response:

    {
    "text": "The current price of Apple (AAPL) is $174.55.",
    "agent": "Stock Agent"
    }

    這表示 Agent 已成功處理 request、使用 stockPrices tool 擷取股票價格,並傳回結果。