Financial Analysis Agent

Overview

This recipe demonstrates how to build an AI-powered financial analysis agent using Airtop’s browser automation capabilities combined with OpenAI’s GPT-4o model and Vercel AI’s SDK. The agent can autonomously navigate financial websites, extract stock data, and analyze the data without human intervention. Airtop is used as a tool in the Vercel AI SDK, and this simple example shows how you can instruct an LLM to call Airtop autonomously to navigate and interact with the web.

The complete source code is available on GitHub.

Prerequisites

Before getting started, ensure you have:

  • Node.js installed on your system
  • PNPM package manager installed. See here for installation steps.
  • A Node Version Manager (NVM preferably).
  • An Airtop API key. You can get one for free.
  • OpenAI API key with GPT-4o access

What it Does

Below is a demo of this recipe. You can sign up to create an API key for free and try it out yourself!

Getting Started

  1. Clone the repository:
$$ git clone https://github.com/airtop-ai/examples-typescript
>$ cd examples-typescript/examples/tool-use-vercel
  1. Follow the setup instructions in the root README to install dependencies and build packages.

What the Service Does

1. Session and Browser Management

The service handles browser session initialization and cleanup:

1async initializeSessionAndBrowser() {
2 const createSessionResponse = await this.client.sessions.create({
3 configuration: {
4 timeoutMinutes: 10,
5 },
6 });
7
8 const session = createSessionResponse.data;
9 const windowResponse = await this.client.windows.create(session.id);
10 const windowInfo = await this.client.windows.getWindowInfo(
11 session.id,
12 windowResponse.data.windowId
13 );
14
15 return { session, windowInfo };
16}

2. AI Tools Configuration

The service configures three main tools for the AI agent using Vercel AI:

  1. URL Loading Tool:
1loadUrl: tool({
2 description: "Load a URL",
3 parameters: z.object({
4 url: z.string().describe("The URL to load"),
5 }),
6 execute: async ({ url }) => {
7 await this.client.windows.loadUrl(this.sessionId, this.windowId, { url });
8 return { data: "URL loaded" };
9 },
10}),
  1. Data Extraction Tool:
1extractData: tool({
2 description: "Extract data from the page",
3 parameters: z.object({
4 prompt: z.string().describe("The natural language query/prompt"),
5 }),
6 execute: async ({ prompt }) => {
7 const result = await this.client.windows.pageQuery(
8 this.sessionId,
9 this.windowId,
10 { prompt }
11 );
12 return { data: result.data.modelResponse };
13 },
14}),
  1. Click Interaction Tool:
1clickButton: tool({
2 description: "Click an element on the page",
3 parameters: z.object({
4 elementDescription: z.string().describe("The element to click"),
5 }),
6 execute: async ({ elementDescription }) => {
7 const result = await this.client.windows.click(
8 this.sessionId,
9 this.windowId,
10 { elementDescription }
11 );
12 return { data: result.data.modelResponse };
13 },
14}),

By configuring Airtop as a tool, the agent can call into Airtop independently as it generates and executes its plan. While you can call Airtop explicitly in your agents, this is an excellent pattern for when you need a more complex agent reasoning and deciding to act on the web autonomously.

5. AI Analysis Implementation

The analysis process is orchestrated through the performAnalysis method:

1async performAnalysis(sessionId: string, windowId: string): Promise<string> {
2 this.sessionId = sessionId;
3 this.windowId = windowId;
4
5 const { text } = await this.sendPrompt({
6 goal: GOAL
7 });
8
9 return text;
10}

6. AI Prompt Engineering

A carefully crafted prompt guides the AI agent. This prompt gives high-level instructions to the LLM and inserts a high-level goal. By including tool configuration, some guidelines, and a goal, the LLM will produce tool calls into Airtop when necessary.

prompt: `
You are a financial analyst. You are given a goal and a set of tools.
You will use the tools to achieve the goal.
When accessing historical information:
1. Click on ONE time period button (e.g., "1D" or "5D")
2. IMMEDIATELY after clicking, extract the data
3. Move on to the next time period and repeat
Do not click multiple buttons in sequence without extracting data.
Goal: ${goal}
`

Running the Agent

To run the financial analysis agent:

  1. Set up your environment variables:
$export AIRTOP_API_KEY=your_key_here
>export OPENAI_API_KEY=your_key_here
  1. Execute the script:
$$ pnpm run cli

Example Output

The agent will provide structured output like:

Analysis: Here are the results for the NVDA stock:
- **Current Price**: $131.14
- **Growth Percentages**:
- **1D**: -1.25%
- **5D**: 2.95%
- **1M**: -1.25%
- **6M**: 12.92%
- **YTD**: -3.15%
- **1Y**: 81.81%
- **5Y**: 123.90%

Best Practices

  1. Error Handling

    • Implement robust error handling for network issues
    • Add retry logic for failed interactions
    • Validate data extraction results
  2. Rate Limiting

    • Respect API rate limits for both Airtop and OpenAI
    • Implement exponential backoff for retries
  3. Session Management

    • Always clean up sessions after use
    • Implement session timeout handling
    • Monitor session resource usage

Summary

This recipe implements a simple financial analysis tool using Vercel AI SDK and Airtop. If you are building an agentic workflow, use this pattern to get started working with Airtop as a tool. You can follow this pattern with other agentic frameworks like CrewAI or Langchain.