Skip to main content

构建人工智能股票代理

🌐 Building an AI Stock Agent

在本指南中,你将创建一个简单的代理,用于获取指定股票符号的前一天收盘价。你将学习如何创建一个工具,将其添加到代理中,以及如何使用代理获取股票价格。

🌐 In this guide, you're going to create a simple agent that fetches the last day's closing stock price for a given symbol. You'll learn how to create a tool, add it to an agent, and use the agent to fetch stock prices.

先决条件
Direct link to 先决条件

🌐 Prerequisites

  • 已安装 Node.js v22.13.0 或更高版本
  • 来自支持的模型提供商的 API 密钥
  • 一个现有的 Mastra 项目(按照安装指南设置新项目)

创建代理
Direct link to 创建代理

🌐 Creating the Agent

要在 Mastra 中创建一个代理,使用 Agent 类来定义它,然后将其注册到 Mastra。

🌐 To create an agent in Mastra use the Agent class to define it and then register it with Mastra.

  1. 创建一个新文件 src/mastra/agents/stockAgent.ts 并定义你的代理:

    🌐 Create a new file src/mastra/agents/stockAgent.ts and define your 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.1",
    });
  2. 在你的 src/mastra/index.ts 文件中,注册代理:

    🌐 In your src/mastra/index.ts file, register the agent:

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

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

创建股票价格工具
Direct link to 创建股票价格工具

🌐 Creating the Stock Price Tool

到目前为止,股票代理还不知道当前的股票价格。要改变这一点,需要创建一个工具并将其添加到代理中。

🌐 So far the Stock Agent doesn't know anything about the current stock prices. To change this, create a tool and add it to the agent.

  1. 创建一个新文件 src/mastra/tools/stockPrices.ts。在其中,添加一个 stockPrices 工具,用于获取指定股票代码的前一天收盘价:

    🌐 Create a new file src/mastra/tools/stockPrices.ts. Inside, add a stockPrices tool that will fetch the last day's closing stock price for a given symbol:

    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 工具,并将其添加到代理中。

    🌐 Inside src/mastra/agents/stockAgent.ts import your newly created stockPrices tool and add it to the 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.1",
    tools: {
    stockPrices,
    },
    });

运行代理服务器
Direct link to 运行代理服务器

🌐 Running the Agent Server

了解如何通过 Mastra 的 API 与你的代理进行交互。

🌐 Learn how to interact with your agent through Mastra's API.

  1. 你可以使用 mastra dev 命令将你的代理作为服务运行:

    🌐 You can run your agent as a service using the mastra dev command:

    mastra dev

    这将启动一个服务器,开放端点以与你注册的代理进行交互。在 Studio 中,你可以通过界面测试你的 stockAgentstockPrices 工具。

    🌐 This will start a server exposing endpoints to interact with your registered agents. Within Studio you can test your stockAgent and stockPrices tool through a UI.

  2. 默认情况下,mastra dev 运行在 http://localhost:4111 上。你的股票代理将可在以下位置使用:

    🌐 By default, mastra dev runs on http://localhost:4111. Your Stock agent will be available at:

    POST http://localhost:4111/api/agents/stockAgent/generate
  3. 你可以使用 curl 在命令行与代理进行交互:

    🌐 You can interact with the agent using curl from the command line:

    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 响应:

    🌐 You should receive a JSON response similar to:

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

    这表明你的代理已成功处理请求,使用 stockPrices 工具获取了股票价格,并返回了结果。

    🌐 This indicates that your agent successfully processed the request, used the stockPrices tool to fetch the stock price, and returned the result.