> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gbox.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Mastra

> Build AI agents with GBOX and Mastra.

## Overview

Mastra is a powerful framework for building AI agents that can interact with GBOX's headless browser infrastructure. It allows you to create sophisticated AI assistants that can automate tasks, perform web scraping, and interact with web applications.

## Getting Started

<Steps>
  <Step title="Install Dependencies">
    Install the necessary dependencies for your project.

    <CodeGroup>
      ```bash npm theme={null}
      npm install gbox-sdk @mastra/core mastra @ai-sdk/openai playwright-core dotenv typescript tsx @types/node
      ```

      ```bash pnpm theme={null}
      pnpm install gbox-sdk @mastra/core mastra @ai-sdk/openai playwright-core dotenv typescript tsx @types/node
      ```

      ```bash yarn theme={null}
      yarn add gbox-sdk @mastra/core mastra @ai-sdk/openai playwright-core dotenv typescript tsx @types/node
      ```
    </CodeGroup>
  </Step>

  <Step title="Add Environment Variables">
    Create a `.env` file in your project root and add your GBOX API key:

    ```dotenv theme={null}
    GBOX_API_KEY=your_gbox_api_key
    OPENAI_API_KEY=your_openai_api_key
    ```
  </Step>

  <Step title="Create Tools">
    Create `src/mastra/tools/index.ts` with the following content:

    ```typescript theme={null}
    import GboxSDK from "gbox-sdk";
    import { chromium } from "playwright-core";
    import { createTool } from "@mastra/core/tools";
    import dotenv from "dotenv";
    import { z } from "zod";

    // Load environment variables
    dotenv.config();

    export const searchRedditTool = createTool({
        id: "reddit-search",
        description: "Search Reddit for relevant information",
        inputSchema: z.object({
            query: z.string().optional().describe("The search query for Reddit"),
        }),
        outputSchema: z.object({
            success: z.boolean(),
            message: z.array(z.any()),
        }),
        execute: async ({ context }) => {
            try {
                const gboxSDK = new GboxSDK({
                    apiKey: process.env.GBOX_API_KEY || "",
                });
                const box = await gboxSDK.create({ type: "linux" });
                const cdpUrl = await box.browser.cdpUrl();

                try {
                    const browser = await chromium.connectOverCDP(cdpUrl);
                    const browserContext = await browser.newContext();
                    const page = await browserContext.newPage();

                    // Construct the search URL
                    const searchUrl = `https://search-new.pullpush.io/?type=submission&q=${context.query}`;
                    await page.goto(searchUrl);

                    // Wait for results to load
                    await page.waitForSelector("div.results", { timeout: 10000 });

                    // Extract search results
                    const results = await page.evaluate(() => {
                        const posts = document.querySelectorAll(
                            "div.results div:has(h1)"
                        );
                        return Array.from(posts).map((post) => ({
                            title: post.querySelector("h1")?.textContent?.trim(),
                            content: post.querySelector("div")?.textContent?.trim(),
                        }));
                    });

                    // Close the browser
                    await browser.close();
                    console.log("Browser closed");

                    // Terminate the box
                    await box.terminate();
                    console.log("Box terminated");

                    return {
                        success: true,
                        message: results.slice(0, 5),
                    };
                } catch (error) {
                    console.error("Error connecting to browser:", error);
                    return {
                        success: false,
                        message: [],
                    };
                }
            } catch (error: any) {
                throw new Error(`Stagehand action failed: ${error.message}`);
            }
        },
    });
    ```
  </Step>

  <Step title="Create Mastra Agent">
    Create `src/mastra/agents/index.ts` with the following content:

    ```typescript theme={null}
    import { createOpenAI } from "@ai-sdk/openai";
    import { Agent } from "@mastra/core/agent";
    import { searchRedditTool } from "../tools";
    import dotenv from "dotenv";

    // Load environment variables
    dotenv.config();

    // Configure OpenAI with API key
    const openai = createOpenAI({
        apiKey: process.env.OPENAI_API_KEY || "",
    });

    export const webAgent = new Agent({
        name: "Web Assistant",
        instructions: `
      You are product manager and a helpful web assistant that can navigate websites and extract information.
        You can use the searchReddit tool to find relevant information on Reddit.
        When searching for information:
        1. Use the searchReddit tool to find relevant posts
        2. Summarize the key findings from multiple posts
        3. Highlight different perspectives or opinions found
        4. Provide context about the discussions
      `,
        model: openai("gpt-4o"),
        tools: { searchRedditTool },
    });
    ```
  </Step>

  <Step title="Initialize Mastra">
    Create `src/mastra/index.ts` with the following content:

    ```typescript theme={null}
    import { Mastra } from "@mastra/core/mastra";
    import { ConsoleLogger } from "@mastra/core/logger";
    import { webAgent } from "./agents";

    export const mastra = new Mastra({
        agents: { webAgent },
        logger: new ConsoleLogger({
            name: "Mastra",
            level: "info",
        }),
    });
    ```
  </Step>

  <Step title="Run the Agent">
    Add a script to run the agent in `package.json`:

    ```json theme={null}
    "scripts": {
        "dev": "mastra dev"
    }
    ```

    Then, run the agent using:

    ```bash theme={null}
    npm run dev
    ```
  </Step>
</Steps>
