构建 AI 股票 Agent
在本指南中,你将创建一个 Agent,用于获取某个股票代码前一日的收盘价。你会先创建一个 Tool 并将其添加到 Agent,然后使用该 Agent 获取股票价格。
前提条件前提条件的直接链接
- 已安装 Node.js
v22.13.0或更高版本 - 受支持的 Model Provider 提供的 API 密钥
- 现有的 Mastra 项目(按照安装指南设置新项目)
创建 Agent创建 Agent的直接链接
要在 Mastra 中创建 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 server运行 Agent server的直接链接
了解如何通过 Mastra API 与 Agent 交互。
你可以使用
mastra dev命令,将 Agent 作为服务运行:mastra dev该命令会启动一个 server,开放用于与已注册 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 获取股票价格,并返回结果。