Configure the Browserbase SDK and create a tool that can search Reddit:
import { anthropic, createAgent, createNetwork, createTool,} from "@inngest/agent-kit";import { z } from "zod";import { chromium } from "playwright-core";import Browserbase from "@browserbasehq/sdk";const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY as string,});// Create a tool to search Reddit using Browserbaseconst searchReddit = createTool({ name: "search_reddit", description: "Search Reddit posts and comments", parameters: z.object({ query: z.string().describe("The search query for Reddit"), }), handler: async ({ query }, { step }) => { return await step?.run("search-on-reddit", async () => { // Create a new session const session = await bb.sessions.create(); // Connect to the session const browser = await chromium.connectOverCDP(session.connectUrl); try { const page = await browser.newPage(); // Construct the search URL const searchUrl = `https://search-new.pullpush.io/?type=submission&q=${query}`; console.log(searchUrl); 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(), })); }); console.log("results", JSON.stringify(results, null, 2)); return results.slice(0, 5); // Return top 5 results } finally { await browser.close(); } }); },});
Configure your BROWSERBASE_API_KEY in the .env file. You can find your API key in the Browserbase dashboard.
Build tools using Browserbase with Inngest’s step.run() function. This ensures the tool only runs once across multiple runs.See the multi-step tools page for more on step.run().
// Add the tool to the agentsearchAgent.tools.push(searchReddit);// Run the agent with a queryconst executor = redditSearchNetwork.createExecutor();// Execute the network with a queryconst execution = await executor.execute({ input: "Find discussions about climate change solutions",});console.log(execution.output);