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.
Prerequisites
- Node.js
v20.0or later installed - An API key from a supported Model Provider
- An existing Mastra project (Follow the installation guide to set up a new project)
Creating the Agent
To create an agent in Mastra use the Agent class to define it and then register it with Mastra.
Create a new file
src/mastra/agents/stockAgent.tsand define your agent:src/mastra/agents/stockAgent.tsimport { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
export const stockAgent = new 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-4o-mini"),
});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 },
});
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.
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 ({ context: { symbol } }) => {
console.log("Using tool to fetch stock price for", symbol);
return {
symbol,
currentPrice: await getStockPrice(symbol),
};
},
});Inside
src/mastra/agents/stockAgent.tsimport your newly createdstockPricestool and add it to the agent.src/mastra/agents/stockAgent.tsimport { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { stockPrices } from "../tools/stockPrices";
export const stockAgent = new 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-4o-mini"),
tools: {
stockPrices,
},
});
Running the Agent Server
Learn how to interact with your agent through Mastra's API.
You can run your agent as a service using the
mastra devcommand:mastra devThis will start a server exposing endpoints to interact with your registered agents. Within the playground you can test your
stockAgentandstockPricestool through a UI.By default,
mastra devruns onhttp://localhost:4111. Your Stock agent will be available at:POST http://localhost:4111/api/agents/stockAgent/generateYou 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)?" }
]
}'Expected Response:
You should receive a JSON response similar to:
{
"text": "The current price of Apple (AAPL) is $174.55.",
"agent": "Stock Agent"
}This indicates that your agent successfully processed the request, used the
stockPricestool to fetch the stock price, and returned the result.