构建人工智能股票代理
🌐 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
创建代理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.
创建一个新文件
src/mastra/agents/stockAgent.ts并定义你的代理:🌐 Create a new file
src/mastra/agents/stockAgent.tsand define your 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.1",
});在你的
src/mastra/index.ts文件中,注册代理:🌐 In your
src/mastra/index.tsfile, register the agent:src/mastra/index.tsimport { 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.
创建一个新文件
src/mastra/tools/stockPrices.ts。在其中,添加一个stockPrices工具,用于获取指定股票代码的前一天收盘价:🌐 Create a new file
src/mastra/tools/stockPrices.ts. Inside, add astockPricestool that will fetch the last day's closing stock price for a given symbol: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中导入你新创建的stockPrices工具,并将其添加到代理中。🌐 Inside
src/mastra/agents/stockAgent.tsimport your newly createdstockPricestool and add it to the 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.1",
tools: {
stockPrices,
},
});
运行代理服务器Direct link to 运行代理服务器
🌐 Running the Agent Server
了解如何通过 Mastra 的 API 与你的代理进行交互。
🌐 Learn how to interact with your agent through Mastra's API.
你可以使用
mastra dev命令将你的代理作为服务运行:🌐 You can run your agent as a service using the
mastra devcommand:mastra dev这将启动一个服务器,开放端点以与你注册的代理进行交互。在 Studio 中,你可以通过界面测试你的
stockAgent和stockPrices工具。🌐 This will start a server exposing endpoints to interact with your registered agents. Within Studio you can test your
stockAgentandstockPricestool through a UI.默认情况下,
mastra dev运行在http://localhost:4111上。你的股票代理将可在以下位置使用:🌐 By default,
mastra devruns onhttp://localhost:4111. Your Stock agent will be available at:POST http://localhost:4111/api/agents/stockAgent/generate你可以使用
curl在命令行与代理进行交互:🌐 You can interact with the agent using
curlfrom 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
stockPricestool to fetch the stock price, and returned the result.