### Installation and Setup Source: https://hyperbrowser.ai/docs/integrations/llamaindex Instructions on how to install the necessary packages and configure environment variables for Hyperbrowser and LlamaIndex. ```APIDOC ## Installation and Setup To get started with LlamaIndex and Hyperbrowser, you can install the necessary packages using pip: ```bash pip install llama-index-core llama-index-readers-web hyperbrowser ``` And you should configure credentials by setting the following environment variables: `HYPERBROWSER_API_KEY=` You can get an API Key easily from the [dashboard](https://app.hyperbrowser.ai). Once you have your API Key, add it to your `.env` file as `HYPERBROWSER_API_KEY` or you can pass it via the `api_key` argument in the `HyperbrowserWebReader` constructor. ``` -------------------------------- ### Installation and Setup Source: https://hyperbrowser.ai/docs/integrations/ai-function-calling Instructions for installing the required SDKs and configuring environment variables to enable Hyperbrowser AI function calling. ```APIDOC ## Installation ### Description Install the necessary packages to integrate Hyperbrowser with OpenAI or Anthropic. ### NPM `npm install @hyperbrowser/sdk dotenv openai` ### Yarn `yarn add @hyperbrowser/sdk dotenv openai` ### Pip `pip install hyperbrowser openai python-dotenv` ### UV `uv add @hyperbrowser/sdk dotenv openai` ## Environment Configuration ### Description Configure your environment variables to authenticate with Hyperbrowser and OpenAI. ### Required Variables - **HYPERBROWSER_API_KEY** (string) - Required - Obtain from the Hyperbrowser dashboard. - **OPENAI_API_KEY** (string) - Required - Your OpenAI API key. ### Example .env file ``` HYPERBROWSER_API_KEY=your_key_here OPENAI_API_KEY=your_openai_key_here ``` ``` -------------------------------- ### Gemini Computer Use - Quick Start (Python) Source: https://hyperbrowser.ai/docs/agents/gemini-computer-use Provides a Python example using the Hyperbrowser SDK to start a Gemini Computer Use task and wait for its result. ```APIDOC ## Start and Wait Gemini Computer Use Task (Python) ### Description This Python example demonstrates how to use the Hyperbrowser SDK to initiate a Gemini Computer Use task and wait for its completion. The `start_and_wait` method simplifies the process by handling the task execution and result retrieval. ### Method `client.agents.gemini_computer_use.start_and_wait(params)` ### Parameters #### Request Body - **params** (StartGeminiComputerUseTaskParams) - Required - Parameters for starting the task. - **task** (string) - Required - The natural language instruction for Gemini. - **max_steps** (int) - Optional - The maximum number of steps Gemini can take. ### Request Example ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartGeminiComputerUseTaskParams import os from dotenv import load_dotenv load_dotenv() client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) result = client.agents.gemini_computer_use.start_and_wait( params=StartGeminiComputerUseTaskParams( task="Go to Hacker News and tell me the title of the top post", max_steps=20 ) ) print(f"Output:\n{result.data.final_result}") ``` ### Response #### Success Response (200) - **data** (object) - Contains the task results. - **final_result** (string) - The final output from the Gemini Computer Use task. #### Response Example ```json { "jobId": "job_abc123", "status": "completed", "data": { "final_result": "The title of the top post is 'New AI Breakthrough'." } } ``` ``` -------------------------------- ### Quickstart: Navigate and Screenshot with Computer Actions (Node.js/Python) Source: https://hyperbrowser.ai/docs/sessions/computer-actions Demonstrates how to initiate a session, navigate to a URL using keyboard shortcuts, and capture a screenshot using computer actions. This example covers focusing the address bar, typing a URL, pressing Enter, and then taking a screenshot. It's useful for scenarios where DOM automation is not feasible. ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); async function main() { const session = await client.sessions.create(); try { // Focus address bar and navigate await client.computerAction.pressKeys(session, ["Control_L", "l"]); await client.computerAction.typeText(session, "https://example.com"); await client.computerAction.pressKeys(session, ["Return"]); const shot = await client.computerAction.screenshot(session); console.log(shot.screenshot); // base64 } finally { await client.sessions.stop(session.id); } } main().catch(console.error); ``` ```python from hyperbrowser import Hyperbrowser import os from dotenv import load_dotenv load_dotenv() client = Hyperbrowser(api_key=os.environ["HYPERBROWSER_API_KEY"]) session = client.sessions.create() try: # Focus address bar and navigate client.computer_action.press_keys(session, keys=["Control_L", "l"]) client.computer_action.type_text(session, text="https://example.com") client.computer_action.press_keys(session, keys=["Return"]) shot = client.computer_action.screenshot(session) print(shot.screenshot) # base64 finally: client.sessions.stop(session.id) ``` -------------------------------- ### Start a Crawl Job using Hyperbrowser SDK Source: https://hyperbrowser.ai/docs/api-reference/start-a-crawl-job Demonstrates how to initiate a crawl job by providing a target URL and optional scraping configurations. The example shows the implementation for both JavaScript and Python environments. ```javascript import { Hyperbrowser } from '@hyperbrowser/sdk'; const client = new Hyperbrowser({ apiKey: 'your-api-key' }); await client.crawl.start({ url: 'https://example.com', scrapeOptions: { formats: ['markdown'] } }); ``` ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartCrawlJobParams, ScrapeOptions client = Hyperbrowser(api_key='your-api-key') client.crawl.start(StartCrawlJobParams( url='https://example.com', scrape_options=ScrapeOptions( formats=['markdown'] ) )) ``` -------------------------------- ### TypeScript Quickstart for Stagehand and Hyperbrowser Source: https://hyperbrowser.ai/docs/integrations/stagehand A TypeScript example demonstrating how to create a Hyperbrowser session, attach Stagehand to it, navigate a page, perform an action, and then clean up resources. It utilizes environment variables for API keys and includes error handling. ```typescript import { config } from "dotenv"; import { Hyperbrowser } from "@hyperbrowser/sdk"; import { Stagehand } from "@browserbasehq/stagehand"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); async function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function main() { const session = await client.sessions.create({ useStealth: true, adblock: true, acceptCookies: true, }); console.log(`Watch live: ${session.liveUrl}`); const stagehand = new Stagehand({ env: "LOCAL", localBrowserLaunchOptions: { cdpUrl: session.wsEndpoint, }, }); try { await stagehand.init(); const page = stagehand.context.pages()[0]; await page.goto("https://hyperbrowser.ai"); await stagehand.act("Click on the 'Launch Browser' button"); console.log("Page title:", await page.title()); console.log("Waiting 5 seconds before closing"); await sleep(5_000); } catch (err) { console.error("Stagehand task failed:", err); } finally { await stagehand.close(); await client.sessions.stop(session.id); } } main().catch((error) => { console.error("Stagehand task failed:", error); process.exit(1); }); ``` -------------------------------- ### SDK Usage Examples Source: https://hyperbrowser.ai/docs/web-scraping/scrape Examples demonstrating how to use the Hyperbrowser SDKs in Node.js and Python to perform scraping tasks. ```APIDOC ## SDK Usage ### Node.js Example ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); const main = async () => { // Handles both starting and waiting for scrape job response const scrapeResult = await client.scrape.startAndWait({ url: "https://example.com", }); console.log("Scrape result:", scrapeResult); }; main(); ``` ### Python Example ```python import os from dotenv import load_dotenv from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartScrapeJobParams # Load environment variables from .env file load_dotenv() # Initialize Hyperbrowser client client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) def main(): # Start scraping and wait for completion scrape_result = client.scrape.start_and_wait( StartScrapeJobParams(url="https://example.com") ) print("Scrape result:\n", scrape_result.model_dump_json(indent=2)) main() ``` ``` -------------------------------- ### Start A Process Source: https://hyperbrowser.ai/docs/sdks/node Starts a long-running process within the sandbox VM. ```APIDOC ## Start A Process ### Description Starts a long-running process within the sandbox VM. ### Method POST ### Endpoint /sandbox/processes/start ### Parameters #### Request Body - **command** (string) - Required - The command to run. - **args** (array[string]) - Optional - Command arguments. - **cwd** (string) - Optional - Working directory. - **env** (object) - Optional - Environment variables. ### Request Example ```json { "command": "bash", "args": ["-lc", "sleep 30"], "cwd": "/tmp", "env": {"FOO": "bar"} } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the started process. #### Response Example ```json { "id": "process-123" } ``` ``` -------------------------------- ### Start Sandbox From Snapshot Source: https://hyperbrowser.ai/docs/sandboxes/snapshots Initializes a new sandbox using a previously created memory snapshot. You can specify both the snapshot name and its ID for precise restoration. This allows for quick environment setup and reproducible testing. ```typescript const restored = await client.sandboxes.create({ snapshotName: "node-after-setup", snapshotId: "snapshot-id", // optional but recommended }); console.log(restored.id); ``` ```python from hyperbrowser.models import CreateSandboxParams restored = client.sandboxes.create( CreateSandboxParams( snapshot_name="node-after-setup", snapshot_id="snapshot-id", # optional but recommended ) ) print(restored.id) ``` ```curl curl -X POST https://api.hyperbrowser.ai/api/sandbox \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "snapshotName": "node-after-setup", "snapshotId": "snapshot-id" }' ``` -------------------------------- ### Start a Sandbox From a Snapshot Source: https://hyperbrowser.ai/docs/sandboxes/snapshots Start a new sandbox using a previously created memory snapshot. Providing both snapshot name and ID is recommended for accuracy. ```APIDOC ## Start a Sandbox From a Snapshot ### Description Use a snapshot name to start a new sandbox. ### Method POST ### Endpoint /api/sandbox ### Parameters #### Request Body - **snapshotName** (string) - Required - The name of the snapshot to restore from. - **snapshotId** (string) - Optional but recommended - The unique identifier of the snapshot. ### Request Example ```json { "snapshotName": "node-after-setup", "snapshotId": "snapshot-id" } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the newly created sandbox. #### Response Example ```json { "id": "sandbox-xyz789" } ``` ``` -------------------------------- ### Install Hyperbrowser CLI Source: https://hyperbrowser.ai/docs/sandboxes/cli Instructions for installing the hb CLI tool using the provided installation script. ```bash curl -fsSL https://www.hyperup.sh/install.sh | sh hb version curl -fsSL https://www.hyperup.sh/install.sh | sh -s -- --version 0.1.0 ``` -------------------------------- ### Install Hyperbrowser MCP Server (Bash) Source: https://hyperbrowser.ai/docs/integrations/model-context-protocol Installs the Hyperbrowser MCP server using npm. Ensure Node.js (v14+) and npm are installed. This command initiates the server installation process. ```bash npx hyperbrowser-mcp ``` -------------------------------- ### Install Hyperbrowser SDK Source: https://hyperbrowser.ai/docs/web/search Instructions for installing the Hyperbrowser SDK using common package managers like npm, yarn, pip, and uv. ```bash npm install @hyperbrowser/sdk ``` ```bash yarn add @hyperbrowser/sdk ``` ```bash pip install hyperbrowser ``` ```bash uv add hyperbrowser ``` -------------------------------- ### Installation Source: https://hyperbrowser.ai/docs/sessions/puppeteer Install the necessary packages for Node.js and Python to use Puppeteer with Hyperbrowser. ```APIDOC ## Installation Install the necessary packages for Node.js and Python to use Puppeteer with Hyperbrowser. ### Node.js ```bash npm install @hyperbrowser/sdk puppeteer-core dotenv ``` ```bash yarn add @hyperbrowser/sdk puppeteer-core dotenv ``` ### Python ```bash pip install hyperbrowser pyppeteer python-dotenv ``` ```bash uv add hyperbrowser pyppeteer python-dotenv ``` For Node.js, use `puppeteer-core` instead of `puppeteer` since Hyperbrowser provides the browser. This saves disk space and installation time. ``` -------------------------------- ### Install Hyperbrowser SDK Source: https://hyperbrowser.ai/docs/agents/hyperagent Commands to install the necessary Hyperbrowser SDK and environment variable management packages for Node.js and Python environments. ```bash npm install @hyperbrowser/sdk dotenv ``` ```bash yarn add @hyperbrowser/sdk dotenv ``` ```bash pip install hyperbrowser python-dotenv ``` ```bash uv add hyperbrowser python-dotenv ``` -------------------------------- ### Get Top Story with HyperAgent (Python) Source: https://hyperbrowser.ai/docs/quickstart This example demonstrates using HyperAgent with the Python SDK to achieve the same task as the Node.js example: getting the top story title from Hacker News. ```APIDOC ## POST /agents/hyper-agent/start-and-wait ### Description Starts a HyperAgent task and waits for its completion. ### Method POST ### Endpoint /agents/hyper-agent/start-and-wait ### Parameters #### Request Body - **task** (string) - Required - A natural language description of the task to perform. ### Response #### Success Response (200) - **data** (object) - Contains the result of the task. - **final_result** (string) - The final result of the HyperAgent task. ### Request Example ```json { "task": "Go to Hacker News and get the title of the first post" } ``` ### Response Example ```json { "data": { "final_result": "New AI model achieves state-of-the-art results" } } ``` ``` -------------------------------- ### Computer Actions - Quickstart Source: https://hyperbrowser.ai/docs/sessions/computer-actions Demonstrates how to use computer actions to navigate to a URL, type text, and take a screenshot within a session. ```APIDOC ## Computer Actions Quickstart This example demonstrates navigating using keyboard input, typing text, and capturing a screenshot. ### Method POST ### Endpoint `/sessions/{sessionId}/computer-actions` (Conceptual - SDK wraps this) ### Parameters #### Request Body (Implicit via SDK methods) ### Request Example (Node.js) ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); async function main() { const session = await client.sessions.create(); try { // Focus address bar and navigate await client.computerAction.pressKeys(session, ["Control_L", "l"]); await client.computerAction.typeText(session, "https://example.com"); await client.computerAction.pressKeys(session, ["Return"]); const shot = await client.computerAction.screenshot(session); console.log(shot.screenshot); // base64 } finally { await client.sessions.stop(session.id); } } main().catch(console.error); ``` ### Response Example (Node.js) ```json { "screenshot": "base64_encoded_image_data" } ``` ### Request Example (Python) ```python from hyperbrowser import Hyperbrowser import os from dotenv import load_dotenv load_dotenv() client = Hyperbrowser(api_key=os.environ["HYPERBROWSER_API_KEY"]) session = client.sessions.create() try: # Focus address bar and navigate client.computer_action.press_keys(session, keys=["Control_L", "l"]) client.computer_action.type_text(session, text="https://example.com") client.computer_action.press_keys(session, keys=["Return"]) shot = client.computer_action.screenshot(session) print(shot.screenshot) # base64 finally: client.sessions.stop(session.id) ``` ### Response Example (Python) ```json { "screenshot": "base64_encoded_image_data" } ``` ``` -------------------------------- ### Get HyperAgent Task Status (JavaScript & Python) Source: https://hyperbrowser.ai/docs/api-reference/get-hyperagent-task-status This snippet demonstrates how to fetch the status of a HyperAgent task using the Hyperbrowser SDK. It requires an API key and the task ID. The function returns the current status of the task, which can be pending, running, completed, failed, or stopped. Ensure you have the '@hyperbrowser/sdk' package installed for the JavaScript example. ```javascript import { Hyperbrowser } from '@hyperbrowser/sdk'; const client = new Hyperbrowser({ apiKey: 'your-api-key' }); await client.agents.hyperAgent.getStatus('task-id'); ``` ```python from hyperbrowser import Hyperbrowser client = Hyperbrowser(api_key='your-api-key') client.agents.hyper_agent.get_status('task-id') ``` -------------------------------- ### Configure and Handle Browser Downloads Source: https://hyperbrowser.ai/docs/sessions/downloads Demonstrates how to create a browser session with download support, configure download behavior via CDP, and monitor download progress using event listeners. ```python async def main(): session = await client.sessions.create(CreateSessionParams(save_downloads=True)) browser = await connect(browserWSEndpoint=session.ws_endpoint, defaultViewport=None) page = await browser._defaultContext.newPage() cdp_client = page._client await cdp_client.send("Browser.setDownloadBehavior", {"behavior": "allow", "downloadPath": "/tmp/downloads", "eventsEnabled": True}) await page.goto("https://browser-tests-alpha.vercel.app/api/download-test") download_completed = asyncio.Event() cdp_client.on("Browser.downloadProgress", lambda event: download_completed.set() if event.get("state") in ["completed", "canceled"] else None) await page.click("#download") await asyncio.wait_for(download_completed.wait(), timeout=30) downloads_response = await waitForDownload(session.id) print("downloadsResponse", downloads_response) ``` -------------------------------- ### Get Top Story with HyperAgent (cURL) Source: https://hyperbrowser.ai/docs/quickstart This example shows how to invoke HyperAgent using a cURL command to get the top story title from Hacker News. ```APIDOC ## POST /task/hyper-agent ### Description Initiates a HyperAgent task via a cURL request. ### Method POST ### Endpoint /task/hyper-agent ### Headers - **Content-Type**: application/json - **x-api-key**: ### Parameters #### Request Body - **task** (string) - Required - A natural language description of the task to perform. ### Response #### Success Response (200) - **data** (object) - Contains the result of the task. - **finalResult** (string) - The final result of the HyperAgent task. ### Request Example ```bash curl -X POST https://api.hyperbrowser.ai/api/task/hyper-agent \ -H 'Content-Type: application/json' \ -H 'x-api-key: ' \ -d '{ "task": "Go to Hacker News and get the title of the first post" }' ``` ### Response Example ```json { "data": { "finalResult": "New AI model achieves state-of-the-art results" } } ``` ``` -------------------------------- ### Extract Job Response Examples Source: https://hyperbrowser.ai/docs/web-scraping/extract Illustrates the JSON responses for starting an extract job, checking its status, and retrieving the extracted data. Includes examples for jobId, status, and the final data payload. ```json { "jobId": "962372c4-a140-400b-8c26-4ffe21d9fb9c" } ``` ```json { "status": "completed" } ``` ```json { "jobId": "962372c4-a140-400b-8c26-4ffe21d9fb9c", "status": "completed", "data": { "heading": "Example Domain", "description": "This domain is for use in documentation examples without needing permission. Avoid use in operations." } } ``` -------------------------------- ### POST /sandbox/processes/start Source: https://hyperbrowser.ai/docs/sandboxes/processes Starts a background process that can be interacted with via stdin or monitored. ```APIDOC ## POST /sandbox/processes/start ### Description Initiates a long-running process in the background. ### Method POST ### Endpoint /sandbox/processes/start ### Request Body - **command** (string) - Required - The command to start. - **args** (array) - Optional - Arguments for the command. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the process. ``` -------------------------------- ### Execute Session Recording with Asyncio Source: https://hyperbrowser.ai/docs/sessions/recordings Demonstrates how to initiate a session recording process using Python's asyncio library. This is the entry point for running automation tasks with recording enabled. ```python if __name__ == "__main__": asyncio.run(run_with_recording()) ``` -------------------------------- ### Get Top Story with HyperAgent (Node.js) Source: https://hyperbrowser.ai/docs/quickstart This example shows how to use HyperAgent via the Node.js SDK to get the top story title from Hacker News by describing the task in natural language. ```APIDOC ## POST /agents/hyper-agent/start-and-wait ### Description Starts a HyperAgent task and waits for its completion. ### Method POST ### Endpoint /agents/hyper-agent/start-and-wait ### Parameters #### Request Body - **task** (string) - Required - A natural language description of the task to perform. ### Response #### Success Response (200) - **data** (object) - Contains the result of the task. - **finalResult** (string) - The final result of the HyperAgent task. ### Request Example ```json { "task": "Go to Hacker News and get the title of the first post" } ``` ### Response Example ```json { "data": { "finalResult": "New AI model achieves state-of-the-art results" } } ``` ``` -------------------------------- ### Asynchronous Task Execution Source: https://hyperbrowser.ai/docs/agents/openai-cua This section demonstrates how to use the asynchronous pattern to start a task and poll for its results. It includes examples in Node.js and Python. ```APIDOC ## Async Pattern When you need more control, use the async pattern to start a task and poll for results: ### Node.js Example ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); async function main() { try { // Start the task const task = await client.agents.cua.start({ task: "What is the title of the first post on Hacker News today?", llm: "gpt-5.4", useComputerAction: true, maxSteps: 25, }); console.log(`Task started: ${task.jobId}`); console.log(`Watch live: ${task.liveUrl}`); // Poll for completion let result; while (true) { result = await client.agents.cua.getStatus(task.jobId); console.log(`Status: ${result.status}`); if (result.status === "completed" || result.status === "failed") { break; } await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5s } const fullResult = await client.agents.cua.get(task.jobId); if (fullResult.status === "completed") { console.log("Result:", fullResult.data?.finalResult); console.log("Steps taken:", fullResult.data?.steps?.length); } else { console.error("Task failed:", fullResult.error); } } catch (err) { console.error(`Error: ${err.message}`); } } main(); ``` ### Python Example ```python import asyncio from hyperbrowser import AsyncHyperbrowser from hyperbrowser.models import StartCuaTaskParams from dotenv import load_dotenv import os load_dotenv() client = AsyncHyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) async def main(): try: # Start the task task = await client.agents.cua.start( params=StartCuaTaskParams( task="What is the title of the first post on Hacker News today?", llm="gpt-5.4", use_computer_action=True, max_steps=25, ) ) print(f"Task started: {task.job_id}") print(f"Watch live: {task.live_url}") # Poll for completion while True: result = await client.agents.cua.get_status(task.job_id) print(f"Status: {result.status}") if result.status in ["completed", "failed"]: break await asyncio.sleep(5) # Wait 5s full_result = await client.agents.cua.get(task.job_id) if full_result.status == "completed": print("Result:", full_result.data.final_result) print( "Steps taken:", len(full_result.data.steps) if full_result.data.steps else 0, ) else: print("Task failed:", full_result.error) except Exception as e: print(f"Error: {e}") if __name__ == "__main__": asyncio.run(main()) ``` ``` -------------------------------- ### Get Top Story with Puppeteer Source: https://hyperbrowser.ai/docs/quickstart This example demonstrates how to use the Hyperbrowser SDK with Puppeteer to navigate to Hacker News and extract the title of the top story. ```APIDOC ## GET /sessions/create ### Description Creates a new cloud browser session. ### Method POST ### Endpoint /sessions/create ### Parameters #### Request Body - **defaultViewport** (object) - Optional - The default viewport for the browser context. ### Response #### Success Response (200) - **id** (string) - The ID of the created session. - **ws_endpoint** (string) - The WebSocket endpoint to connect to the browser. ### Request Example ```json { "defaultViewport": null } ``` ### Response Example ```json { "id": "session-123", "ws_endpoint": "wss://browser.hyperbrowser.ai/session-123" } ``` ## GET /sessions/{sessionId}/stop ### Description Stops and cleans up a cloud browser session. ### Method DELETE ### Endpoint /sessions/{sessionId}/stop ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to stop. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ### Response Example ```json { "message": "Session session-123 stopped successfully." } ``` ``` -------------------------------- ### Async Pattern for LLM Tasks Source: https://hyperbrowser.ai/docs/agents/browser-use This section explains how to use the asynchronous pattern to start an LLM task and poll for its results. It includes examples in Node.js and Python. ```APIDOC ## Async Pattern When you need more control, use the async pattern to start a task and poll for results: ### Node.js Example ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); async function main() { try { // Start the task const task = await client.agents.browserUse.start({ task: "What is the title of the first post on Hacker News today?", llm: "gemini-2.5-flash", maxSteps: 20, }); console.log(`Task started: ${task.jobId}`); console.log(`Watch live: ${task.liveUrl}`); // Poll for completion let result; while (true) { result = await client.agents.browserUse.getStatus(task.jobId); console.log(`Status: ${result.status}`); if (result.status === "completed" || result.status === "failed") { break; } await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5s } const fullResult = await client.agents.browserUse.get(task.jobId); if (fullResult.status === "completed") { console.log("Result:", fullResult.data?.finalResult); console.log("Steps taken:", fullResult.data?.steps?.length); } else { console.error("Task failed:", fullResult.error); } } catch (err) { console.error(`Error: ${err.message}`); } } main(); ``` ### Python Example ```python import asyncio from hyperbrowser import AsyncHyperbrowser from hyperbrowser.models import StartBrowserUseTaskParams from dotenv import load_dotenv import os load_dotenv() client = AsyncHyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) async def main(): try: # Start the task task = await client.agents.browser_use.start( params=StartBrowserUseTaskParams( task="What is the title of the first post on Hacker News today?", llm="gemini-2.5-flash", max_steps=20, ) ) print(f"Task started: {task.job_id}") print(f"Watch live: {task.live_url}") # Poll for completion while True: result = await client.agents.browser_use.get_status(task.job_id) print(f"Status: {result.status}") if result.status in ["completed", "failed"]: break await asyncio.sleep(5) # Wait 5s full_result = await client.agents.browser_use.get(task.job_id) if full_result.status == "completed": print("Result:", full_result.data.final_result) print( "Steps taken:", len(full_result.data.steps) if full_result.data.steps else 0, ) else: print("Task failed:", full_result.error) except Exception as e: print(f"Error: {e}") if __name__ == "__main__": asyncio.run(main()) ``` ``` -------------------------------- ### Configuring and Handling Downloads in a Session Source: https://hyperbrowser.ai/docs/sessions/downloads This example demonstrates how to create a session with download saving enabled, configure browser download behavior using CDP, handle download events, and retrieve download status. ```APIDOC ## Python Example: Session Download Configuration and Handling ### Description This code snippet shows how to set up a Playwright session to save downloads, configure the browser's download behavior using the Chrome DevTools Protocol (CDP), and handle download events to confirm completion. ### Method Asynchronous Python script using `asyncio` and a browser automation library. ### Endpoint N/A (Client-side script) ### Parameters None directly for this script, but session creation parameters are relevant. ### Request Body N/A ### Request Example ```python import asyncio from playwright.async_api import async_playwright, Playwright from playwright.sync_api import BrowserContext, sync_playwright # Assuming 'client' is an initialized SDK client # from your_sdk import Client, CreateSessionParams async def waitForDownload(session_id: str, timeout: int = 1000): # Placeholder for the actual implementation to poll for download status # This function would typically call an API endpoint to check the status # and return the downloadsResponse when ready. print(f"Waiting for download for session: {session_id}") # Simulate waiting for download completion await asyncio.sleep(5) # Simulate network delay return {"status": "completed", "downloadsUrl": "http://example.com/download.zip"} async def main(): # Replace with your actual SDK client initialization # async with Client() as client: # session = await client.sessions.create(CreateSessionParams(save_downloads=True)) # Mocking the client and session for demonstration class MockSession: def __init__(self, id): self.id = id self.ws_endpoint = "mock_ws_endpoint" class MockClientSessions: async def create(self, params): print("Creating session...") return MockSession(id="mock_session_id_123") async def stop(self, session_id): print(f"Stopping session: {session_id}") class MockClient: def __init__(self): self.sessions = MockClientSessions() client = MockClient() session = await client.sessions.create(None) # save_downloads=True is implied by usage print(f"Session created: {session.id}") try: # Mocking browser connection and page interaction async with async_playwright() as p: browser = await p.chromium.connect(ws_endpoint=session.ws_endpoint, defaultViewport=None) defaultContext = browser._defaultContext page = await defaultContext.newPage() cdp_client = page._client await cdp_client.send( "Browser.setDownloadBehavior", { "behavior": "allow", "downloadPath": "/tmp/downloads", "eventsEnabled": True, }, ) await page.goto("https://browser-tests-alpha.vercel.app/api/download-test") download_completed = asyncio.Event() def on_download_begin(event): print(f"Download started: {event.get('suggestedFilename', 'unknown')}") def on_download_progress(event): if event.get("state") in ["completed", "canceled"]: download_completed.set() cdp_client.on("Browser.downloadWillBegin", on_download_begin) cdp_client.on("Browser.downloadProgress", on_download_progress) download_task = asyncio.create_task(download_completed.wait()) await page.click("#download") try: await asyncio.wait_for(download_task, timeout=30) print("Download completed") except asyncio.TimeoutError: print("Download timed out after 30 seconds") await client.sessions.stop(session.id) await asyncio.sleep(3) downloads_response = await waitForDownload(session.id) print("downloadsResponse", downloads_response) except Exception as err: print(f"Encountered error: {err}") finally: await client.sessions.stop(session.id) if __name__ == "__main__": asyncio.run(main()) ``` ### Response #### Success Response (200) N/A (This is a client-side script example) #### Response Example ```json { "status": "completed", "downloadsUrl": "http://example.com/download.zip" } ``` ``` -------------------------------- ### Get Crawl Job Status Source: https://hyperbrowser.ai/docs/web-scraping/crawl Retrieves the current status of a previously started crawl job using its jobId. The status indicates whether the job is pending, running, completed, or failed. ```APIDOC ## GET /api/crawl/{jobId}/status ### Description Retrieves the status of a specific crawl job. ### Method GET ### Endpoint /api/crawl/{jobId}/status ### Parameters #### Path Parameters - **jobId** (string) - Required - The unique identifier of the crawl job. ### Response #### Success Response (200) - **status** (string) - The current status of the crawl job (e.g., 'pending', 'running', 'completed', 'failed'). #### Response Example ```json { "status": "completed" } ``` ``` -------------------------------- ### Start a BrowserUse Task Source: https://hyperbrowser.ai/docs/api-reference/start-a-browser-use-task Demonstrates how to initiate a browser automation task using the Hyperbrowser SDK. The task requires an API key and a task description, with optional parameters for LLM selection and step limits. ```javascript import { Hyperbrowser } from '@hyperbrowser/sdk'; const client = new Hyperbrowser({ apiKey: 'your-api-key' }); await client.agents.browserUse.start({ task: 'Find the price of the product', llm: 'gemini-2.0-flash', maxSteps: 20 }); ``` ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartBrowserUseTaskParams client = Hyperbrowser(api_key='your-api-key') client.agents.browser_use.start(StartBrowserUseTaskParams( task='Find the price of the product', llm='gemini-2.0-flash', max_steps=20 )) ``` -------------------------------- ### Start Data Extraction Job Source: https://hyperbrowser.ai/docs/web-scraping/extract Initiate an AI-powered data extraction job from specified URLs using a defined prompt and schema. This example demonstrates usage with Node.js (TypeScript), Python, and cURL. ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); const main = async () => { const extractResult = await client.extract.startAndWait({ urls: ["https://example.com"], prompt: "Extract the main heading and description from the page", schema: { type: "object", properties: { heading: { type: "string" }, description: { type: "string" }, }, required: ["heading", "description"], }, }); console.log("Extract result:", extractResult); }; main(); ``` ```python import os from dotenv import load_dotenv from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartExtractJobParams # Load environment variables from .env file load_dotenv() # Initialize Hyperbrowser client client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) def main(): # Start extraction and wait for completion extract_result = client.extract.start_and_wait( StartExtractJobParams( urls=["https://example.com"], prompt="Extract the main heading and description from the page", schema={ "type": "object", "properties": { "heading": {"type": "string"}, "description": {"type": "string"} }, "required": ["heading", "description"] } ) ) print("Extract result:\n", extract_result.model_dump_json(indent=2)) ``` ```bash # Start Extract Job curl -X POST https://api.hyperbrowser.ai/api/extract \ -H 'Content-Type: application/json' \ -H 'x-api-key: ' \ -d '{ "urls": ["https://example.com"], "prompt": "Extract the main heading and description from the page", "schema": { "type": "object", "properties": { "heading": {"type": "string"}, "description": {"type": "string"} }, "required": ["heading", "description"] } }' # Get Extract Job Status curl https://api.hyperbrowser.ai/api/extract/{jobId}/status \ -H 'x-api-key: ' # Get Extract Job Status and Data curl https://api.hyperbrowser.ai/api/extract/{jobId} \ -H 'x-api-key: ' ``` -------------------------------- ### Complete Lifecycle Example Source: https://hyperbrowser.ai/docs/sessions/lifecycle Demonstrates a complete session lifecycle, from creation to usage with Playwright, and proper session termination. ```APIDOC ## Complete Lifecycle Example ### Description This example demonstrates best practices for session management, including creating a session, connecting with Playwright, using the session for navigation, and ensuring the session is stopped. ### Method POST (Implicit for session creation) ### Endpoint /api/session (Implicit) ### Parameters #### Request Body (for session creation) - **acceptCookies** (boolean) - Optional - Whether to accept cookies automatically. ### Request Example (Node.js) ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { chromium } from "playwright-core"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); async function runAutomation() { console.log("Creating session..."); const session = await client.sessions.create({ acceptCookies: true, }); console.log(`Session created: ${session.id}`); console.log(`Watch live: ${session.liveUrl}`); try { const browser = await chromium.connectOverCDP(session.wsEndpoint); const context = browser.contexts()[0]; const page = context.pages()[0]; console.log("Waiting 5 seconds before navigating to example.com"); await sleep(5000); await page.goto("https://example.com"); const title = await page.title(); console.log(`Page title: ${title}`); console.log("Waiting 5 seconds before stopping the session"); await sleep(5000); } catch (error) { console.error("Automation failed:", error); } finally { console.log("Stopping session..."); await client.sessions.stop(session.id); console.log("Session stopped"); } } runAutomation().catch(console.error); ``` ### Request Example (Python) ```python from hyperbrowser import Hyperbrowser from hyperbrowser.models import CreateSessionParams from playwright.sync_api import sync_playwright from dotenv import load_dotenv import os import time load_dotenv() client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) def run_automation(): print("Creating session...") session = client.sessions.create( params=CreateSessionParams( accept_cookies=True, ) ) print(f"Session created: {session.id}") print(f"Watch live: {session.live_url}") try: with sync_playwright() as p: browser = p.chromium.connect_over_cdp(session.ws_endpoint) context = browser.contexts[0] page = context.pages[0] print("Waiting 5 seconds before navigating to example.com") time.sleep(5) page.goto("https://example.com") title = page.title() print(f"Page title: {title}") print("Waiting 5 seconds before stopping the session") time.sleep(5) except Exception as error: print(f"Automation failed: {error}") finally: print("Stopping session...") client.sessions.stop(session.id) print("Session stopped") if __name__ == "__main__": run_automation() ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the session. - **wsEndpoint** (string) - The WebSocket endpoint for connecting with Playwright. - **liveUrl** (string) - A URL to watch the session live. #### Response Example ```json { "id": "sess_abc123", "wsEndpoint": "wss://example.com/ws", "liveUrl": "https://app.hyperbrowser.ai/sessions/sess_abc123" } ``` ``` -------------------------------- ### Start and Poll Hyper Agent Task (Python) Source: https://hyperbrowser.ai/docs/agents/hyperagent Shows how to initiate an AI task with the Hyper Agent and continuously check its status until completion. This Python example handles results and errors. It depends on the hyperbrowser library and python-dotenv. ```python import asyncio from hyperbrowser import AsyncHyperbrowser from hyperbrowser.models import StartHyperAgentTaskParams from dotenv import load_dotenv import os load_dotenv() client = AsyncHyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) async def main(): try: # Start the task task = await client.agents.hyper_agent.start( params=StartHyperAgentTaskParams( version="1.1.0", task="What is the title of the first post on Hacker News today?", llm="gemini-2.5-flash", max_steps=20, ) ) print(f"Task started: {task.job_id}") print(f"Watch live: {task.live_url}") # Poll for completion while True: result = await client.agents.hyper_agent.get_status(task.job_id) print(f"Status: {result.status}") if result.status in ["completed", "failed"]: break await asyncio.sleep(5) # Wait 5s full_result = await client.agents.hyper_agent.get(task.job_id) if full_result.status == "completed": print("Result:", full_result.data.final_result) print( "Steps taken:", len(full_result.data.steps) if full_result.data.steps else 0, ) else: print("Task failed:", full_result.error) except Exception as e: print(f"Error: {e}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure Basic Crawl Job Options Source: https://hyperbrowser.ai/docs/web-scraping/crawl Demonstrates how to start a crawl job with basic parameters like maxPages, followLinks, and ignoreSitemap. This is the standard way to initiate a crawl operation. ```typescript import { Hyperbrowser } from "@hyperbrowser/sdk"; import { config } from "dotenv"; config(); const client = new Hyperbrowser({ apiKey: process.env.HYPERBROWSER_API_KEY, }); const main = async () => { const crawlResult = await client.crawl.startAndWait({ url: "https://example.com", maxPages: 50, followLinks: true, ignoreSitemap: false, }); console.log("Crawl result:", crawlResult); }; main(); ``` ```python import os from dotenv import load_dotenv from hyperbrowser import Hyperbrowser from hyperbrowser.models import StartCrawlJobParams load_dotenv() client = Hyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY")) crawl_result = client.crawl.start_and_wait( StartCrawlJobParams( url="https://example.com", max_pages=50, follow_links=True, ignore_sitemap=False ) ) print("Crawl result:\n", crawl_result.model_dump_json(indent=2)) ```