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
Install Dependencies
Install the necessary dependencies for your project.
npm install gbox-sdk @mastra/core mastra @ai-sdk/openai playwright-core dotenv typescript tsx @types/node
Add Environment Variables
Create a .env
file in your project root and add your Gbox API key:
GBOX_API_KEY=your_gbox_api_key
OPENAI_API_KEY=your_openai_api_key
Create Tools
Create src/mastra/tools/index.ts
with the following content:
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}`);
}
},
});
Create Mastra Agent
Create src/mastra/agents/index.ts
with the following content:
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 },
});
Initialize Mastra
Create src/mastra/index.ts
with the following content:
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",
}),
});
Run the Agent
Add a script to run the agent in package.json
:
"scripts": {
"dev": "mastra dev"
}
Then, run the agent using: