Connect Browserbase to AI Agents: Run functions and fetch web content
Learn how to connect Browserbase to AI agents using Truto's /tools endpoint. Fetch web content, run headless sessions, and build automated workflows safely.
You want to connect Browserbase to an AI agent so your system can independently spin up headless browser sessions, run web automation functions, extract DOM data, and debug Chrome DevTools Protocol (CDP) logs based on historical context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to manage massive stateful websockets or complex session lifecycles manually.
Giving a Large Language Model (LLM) read and write access to your cloud browser infrastructure is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector to handle asynchronous browser states, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Browserbase to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Browserbase to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.
This guide breaks down exactly how to fetch AI-ready tools for Browserbase, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex web automation workflows. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.
The Engineering Reality of Custom Browserbase Connectors
Building AI agents is easy. Connecting them to external infrastructure APIs is hard. Giving an LLM access to a headless browser fleet sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production, this approach collapses entirely, especially with an ecosystem as stateful and asynchronous as Browserbase.
If you decide to build the integration yourself, you own the entire API lifecycle. Browserbase's API introduces several highly specific integration challenges that break standard LLM assumptions.
The Zombie Session Trap
Browserbase sessions cost money by the minute. When an AI agent spins up a session, it needs to explicitly tear it down when finished, or let it timeout. However, LLMs are notoriously bad at remembering to call cleanup functions if a workflow errors out midway. If you expose raw session creation to an agent without a strict wrapper, you will accumulate zombie sessions. The API requires sending a specific REQUEST_RELEASE status update to gracefully terminate a session early and save proxy bytes, but prompting an LLM to remember this exact enum value across long contexts is unreliable.
Asynchronous Media and Polling
Agents often need visual proof of a web interaction, such as downloading an MP4 recording of a session or an HLS VOD playlist. The Browserbase API does not return these synchronously. You must first POST to enqueue a recording download, and then poll a separate list endpoint to retrieve the short-lived signed URLs once the rendering is complete. If you hand this raw polling loop to an LLM, it will either loop infinitely, consuming thousands of tokens, or hallucinate a success state before the video is actually ready.
CDP Log Firehoses
Chrome DevTools Protocol (CDP) logs are massive. If an agent requests the logs for a session that ran for three minutes, the resulting JSON array of frame lifecycles, network requests, and DOM events can easily exceed 100,000 tokens. Pumping this raw payload back into the LLM context window will instantly crash the agent or cause severe context degradation. The integration layer must truncate, filter, or paginate this data before it ever touches the agent's memory.
Why a Unified Tool Layer Matters for Agent Safety
Before writing a line of integration code, decide what layer your agent talks to. This choice determines how safe your production system will be.
A unified tool layer collapses complex infrastructure quirks behind one schema. Your agent sees create_a_browserbase_session, update_a_browserbase_session_by_id, and browserbase_fetch_fetch_page with standardized JSON schemas. That gives you concrete safety wins:
- Smaller attack surface for hallucination. The LLM only ever chooses from a stable list of function names. It never invents arbitrary browser flags or invalid region codes.
- Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments (like requesting a timeout outside the 60-second minimum bounds) are rejected before they hit Browserbase.
- Abstracted auth. Your agent never sees the API key or project ID. The execution environment handles the credentials.
Here is how the architecture handles tool execution securely:
sequenceDiagram
participant Agent as AI Agent
participant Framework as LangChain / LangGraph
participant SDK as Truto SDK
participant API as Truto Proxy API
participant Upstream as Browserbase API
Agent->>Framework: "Navigate to site and get logs"
Framework->>SDK: bindTools() lookup
SDK->>API: GET /integrated-account/{id}/tools
API-->>SDK: Returns strict JSON schemas
SDK-->>Framework: Registers Browserbase tools
Framework->>Agent: Injects tool descriptions
Agent->>Framework: Call create_a_browserbase_session({keepAlive: false})
Framework->>SDK: executeTool(sessionId, args)
SDK->>API: POST proxy request
API->>Upstream: Authenticated API call
Upstream-->>API: 200 OK (Session ID)
API-->>SDK: Normalized response
SDK-->>Framework: Return tool output
Framework-->>Agent: Context updatedHero Tools for Browserbase Workflows
Truto exposes the entirety of the Browserbase API as LLM-ready tools. Instead of building endpoints one by one, your agent can instantly access the most critical infrastructure operations. Here are the highest-leverage tools available.
Create a Browserbase Session
create_a_browserbase_session
Spins up a new headless browser session. You can pass optional browser settings, proxy configurations, routing regions, and metadata. This is the foundation of any long-running web automation task.
"Initialize a new Browserbase session in the US-West region with a timeout of 120 seconds. Ensure keepAlive is set to false so it terminates automatically if I drop the connection."
Fetch Web Page Content
browserbase_fetch_fetch_page
Executes a fast proxy fetch through Browserbase's infrastructure to retrieve raw HTML, JSON, or markdown. This is highly efficient for data extraction tasks where spinning up a full CDP websocket session is overkill.
"Fetch the pricing page from example.com using Browserbase infrastructure and return the response content in markdown format."
Retrieve CDP Logs
browserbase_sessions_get_logs
Retrieves the Chrome DevTools Protocol logs for a specific session. This returns critical debugging data like network requests, frame lifecycle events, and console errors, allowing the agent to self-correct if a UI interaction failed.
"Pull the CDP logs for session ID 12345-abcde. Look for any network requests that returned a 403 Forbidden status during the login flow."
Update or Release a Session
update_a_browserbase_session_by_id
Modifies an active session. Most importantly, sending the status REQUEST_RELEASE ends the session immediately, preventing unnecessary usage charges. Agents should always be instructed to call this when a workflow succeeds or fatally errors.
"My scraping task is complete. Update the session ID 12345-abcde with the status REQUEST_RELEASE to tear down the browser and stop billing."
Enqueue Recording Download
create_a_browserbase_session_recording_download
Triggers the backend process to generate an MP4 video recording of everything that happened in the browser session. This is vital for visual QA and compliance auditing.
"The visual QA test for the checkout flow just finished. Enqueue a recording download for the session so the engineering team can review the video."
Run an Autonomous Agent Task
create_a_browserbase_agent_run
Delegates a natural language task directly to Browserbase's internal agent execution engine. Instead of orchestrating the DOM clicks yourself, you can hand a complex instruction to Browserbase and wait for the result.
"Create a Browserbase agent run with the task: 'Navigate to the dashboard, click the export button, and wait for the CSV to download'."
For the complete schema definitions and the full list of available operations, view the Browserbase integration page.
Workflows in Action
When you equip an agent with these tools, it stops being a simple chatbot and becomes an autonomous infrastructure operator. Here are concrete examples of how an agent sequences Browserbase tools to solve real engineering problems.
1. Autonomous Visual QA and Bug Reporting
A DevOps engineer asks the agent to run a visual smoke test on a staging environment and capture evidence if the test fails.
"Run a test session against staging.example.com. If the page throws any console errors, pull the logs, request a video recording, and tear down the session immediately to save resources."
Step-by-step execution:
- The agent calls
create_a_browserbase_sessionto spin up the headless environment. - The agent executes its testing logic (often via a custom script or by triggering
create_a_browserbase_agent_run). - The agent calls
browserbase_sessions_get_logsto audit the CDP events for 4xx/5xx network errors. - Upon finding an error, the agent calls
create_a_browserbase_session_recording_downloadto enqueue the MP4 generation. - Finally, the agent calls
update_a_browserbase_session_by_idwithREQUEST_RELEASEto terminate the zombie process.
Result: The engineer gets a summarized report of the specific CDP failure, alongside a pending video recording, with zero wasted compute time.
2. High-Speed Competitor Pricing Extraction
A data analyst needs clean, readable text from a heavily bot-protected website without writing custom Puppeteer code.
"Use Browserbase to fetch the current pricing tiers from competitor.com. Return the data to me strictly as formatted markdown."
Step-by-step execution:
- The agent evaluates that a full interactive session is not needed.
- The agent calls
browserbase_fetch_fetch_pagewith the target URL, requesting thetext/markdownformat to bypass raw HTML parsing. - The agent receives the proxied markdown payload, avoiding standard WAF blocks due to Browserbase's proxy infrastructure.
Result: The analyst receives a clean markdown table of pricing data in seconds, bypassing the overhead of managing Selenium or Playwright.
Building Multi-Step Workflows
To build these agentic workflows reliably, you need to connect the tools to your framework. Truto's SDK makes this framework-agnostic. Whether you use LangChain, LangGraph, CrewAI, or the Vercel AI SDK, the pattern remains the same: fetch the tools, bind them to the LLM, and execute the loop.
Here is how you initialize the tool manager and bind it to a LangChain agent in TypeScript:
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { TrutoToolManager } from "truto-langchainjs-toolset";
async function runBrowserbaseAgent() {
// 1. Initialize the Truto Tool Manager with your Integrated Account ID
const toolManager = new TrutoToolManager({
trutoApiKey: process.env.TRUTO_API_KEY,
integratedAccountId: "YOUR_BROWSERBASE_ACCOUNT_ID",
});
// 2. Fetch all Browserbase tools dynamically
const tools = await toolManager.getTools();
// 3. Initialize your LLM and bind the tools
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0,
}).bindTools(tools);
// 4. Create the system prompt enforcing lifecycle rules
const prompt = ChatPromptTemplate.fromMessages([
["system", `You are a DevOps automation agent managing Browserbase infrastructure.
CRITICAL RULES:
1. Always store the session ID when you create a session.
2. Always call update_a_browserbase_session_by_id with status REQUEST_RELEASE when your task is complete or if an unrecoverable error occurs.
3. Do not attempt to process more than 50 log entries at a time.`],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
// 5. Build and execute the agent loop
const agent = createToolCallingAgent({
llm,
tools,
prompt,
});
const agentExecutor = new AgentExecutor({
agent,
tools,
maxIterations: 10,
});
const result = await agentExecutor.invoke({
input: "Spin up a session, fetch example.com logs, and tear the session down.",
});
console.log(result.output);
}Handling Rate Limits in Agent Loops
When your agent is aggressively polling for recording downloads or fetching dozens of pages, it will eventually hit Browserbase's API rate limits.
It is crucial to understand how Truto handles this: Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Browserbase API returns an HTTP 429 Too Many Requests, Truto passes that exact error directly back to the caller.
However, Truto normalizes the upstream rate limit information into standardized headers per the IETF specification (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your execution layer is responsible for reading these headers and pausing the agent.
Here is a conceptual example of how your tool-calling execution loop should handle a 429:
try {
const response = await executeBrowserbaseTool(toolName, args);
return response;
} catch (error) {
if (error.status === 429) {
// Extract the normalized headers provided by Truto
const resetTime = error.headers['ratelimit-reset'];
const delayMs = (parseInt(resetTime) * 1000) - Date.now();
console.warn(`Rate limit hit. Pausing agent execution for ${delayMs}ms...`);
// Implement your backoff strategy before allowing the agent to retry
await sleep(delayMs > 0 ? delayMs : 5000);
// Instruct the agent to retry the exact same tool call
return "System paused due to rate limits. Please retry your last tool call immediately.";
}
throw error;
}By feeding the rate limit context back into the agent's scratchpad, the LLM understands exactly why the execution halted and knows to try again without hallucinating a failure state.
Moving from Scripts to Autonomous Infrastructure
Managing headless browsers has historically required dedicated infrastructure teams maintaining complex fleets of containers. By exposing Browserbase's robust API as a unified set of LLM tools, you bypass the infrastructure overhead entirely. Your AI agents can now spin up isolated browsers, execute complex UI interactions, dump CDP logs for debugging, and render video compliance evidence - all through natural language reasoning.
Stop writing custom API wrappers and managing zombie websocket connections. Give your agents safe, standardized, and strictly typed access to Browserbase today.
FAQ
- How do I prevent AI agents from leaving Browserbase sessions running?
- You must instruct the agent in its system prompt to always call the `update_a_browserbase_session_by_id` tool with the status `REQUEST_RELEASE` upon task completion or failure. This immediately terminates the session and prevents runaway usage.
- Does Truto automatically handle Browserbase rate limits?
- No. Truto does not retry, throttle, or apply backoff on rate limit errors. When Browserbase returns an HTTP 429, Truto passes that error to the caller along with standardized headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`). You must implement retry logic in your agent loop.
- Can I use these Browserbase tools with LangGraph or CrewAI?
- Yes. Truto's proxy methods and tool schemas are framework-agnostic. You can bind them to any agent framework that supports standard LLM function calling, including LangChain, LangGraph, CrewAI, and the Vercel AI SDK.
- How does the agent handle large CDP logs from Browserbase?
- CDP logs can be massive and will quickly blow out an LLM's context window. When using the `browserbase_sessions_get_logs` tool, ensure you implement a truncation layer in your execution loop before returning the payload to the agent's memory.