Integration guide
Browser Use integration: a custom solve action for your agent
A Browser Use agent can plan, click and type, but it cannot produce a CAPTCHA token. A custom action that calls the GateSolver API gives it that one missing ability.
What the action does for the agent
The agent gets one extra action, described in plain words, that it calls when a page shows a CAPTCHA widget. Inside the action, ordinary code does the work: it inspects the page, sends a task to the HTTP API, waits for the answer, writes it into the page, and returns a short sentence the model can act on. The model never sees the API key, never handles raw JSON, and never tries to click through image grids from screenshots, which is slow and often fails.
Our blog post on a Browser Use agent getting blocked explains how to tell a real widget from an IP block. This page is the integration reference: the solver code, the action, the prompts, and the limits that keep a run under control.
Installing, and a note on versions
Install the library with pip install browser-use and the browser it needs as its README describes, then pip install requests for the API calls. Set GATESOLVER_KEY in the environment beside your model provider's key.
Browser Use moves quickly. At the time of writing, custom actions are registered with a decorator on a registry object (named Tools in recent releases and Controller in earlier ones), and the action receives the browser session through a specially named parameter. How you run JavaScript in the current tab has also changed: earlier releases handed you a Playwright page, newer ones use their own browser layer. The code below keeps every version specific line in one small adapter so the rest stays stable. Check the custom actions page of the docs for your installed version and adjust only that adapter.
The solver, kept outside the agent
Write and test the API part without the agent at all. It is ordinary Python, and running it from a terminal against a known page tells you the key, the network and the task fields are right before any model tokens are spent.
# gs_agent_solver.py
import asyncio, os
import requests
AGENT_SOLVER = "https://gatesolver.com"
def _post(route: str, body: dict) -> dict:
body = {"clientKey": os.environ["GATESOLVER_KEY"], **body}
return requests.post(f"{AGENT_SOLVER}/{route}", json=body, timeout=30).json()
async def fetch_answer(task: dict, interval: float = 3.0) -> tuple[str | None, str]:
"""Returns (token, note). token is None when no answer was produced."""
made = await asyncio.to_thread(_post, "createTask", {"task": task})
if made.get("errorId"):
return None, made.get("errorCode", "create failed")
for _ in range(int(125 / interval)):
await asyncio.sleep(interval)
tick = await asyncio.to_thread(_post, "getTaskResult", {"taskId": made["taskId"]})
if tick.get("status") == "ready":
sol = tick["solution"]
return sol.get("token") or sol.get("gRecaptchaResponse"), "ready"
if tick.get("errorId") or tick.get("status") == "failed":
return None, tick.get("errorCode", "failed")
return None, "timeout"
if __name__ == "__main__": # quick check from a terminal
demo = {"type": "ReCaptchaV2TaskProxyLess", "websiteKey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
"websiteURL": "https://www.google.com/recaptcha/api2/demo", "isInvisible": False}
print(asyncio.run(fetch_answer(demo)))
asyncio.to_thread keeps the blocking requests calls off the event loop, so the agent's browser keeps responding while the task runs. The demo key in the self test is Google's public demo widget.
Registering the action
from browser_use import Tools # earlier releases: from browser_use import Controller
from gs_agent_solver import fetch_answer
tools = Tools()
attempts: dict[str, int] = {}
PROBE = """() => {
const el = document.querySelector('.cf-turnstile[data-sitekey], .g-recaptcha[data-sitekey]');
return el ? {turnstile: el.classList.contains('cf-turnstile'), key: el.dataset.sitekey, url: location.href,
hook: el.dataset.callback || null} : null; }"""
PLACE = """(a) => {
document.querySelectorAll(`[name="${a.field}"]`).forEach((f) => { f.value = a.value; });
if (a.hook && typeof window[a.hook] === 'function') window[a.hook](a.value); }"""
async def run_js(browser_session, script, arg=None):
# Version specific: older releases expose a Playwright page here,
# newer ones their own page helper. Adapt this function only.
page = await browser_session.get_current_page()
return await (page.evaluate(script, arg) if arg is not None else page.evaluate(script))
@tools.action("Solve the CAPTCHA checkbox or Turnstile box on the current page. Call once, then submit.")
async def solve_captcha_widget(browser_session) -> str:
found = await run_js(browser_session, PROBE)
if not found:
return "No supported CAPTCHA widget on this page. Continue without solving."
attempts[found["url"]] = attempts.get(found["url"], 0) + 1
if attempts[found["url"]] > 2:
return "Solving already failed twice on this page. Stop and report the problem."
kind = "AntiTurnstileTaskProxyLess" if found["turnstile"] else "ReCaptchaV2TaskProxyLess"
token, note = await fetch_answer({"type": kind, "websiteURL": found["url"], "websiteKey": found["key"]})
if not token:
return f"The solver returned no answer ({note}). Do not reload; try this action once more."
field = "cf-turnstile-response" if found["turnstile"] else "g-recaptcha-response"
await run_js(browser_session, PLACE, {"field": field, "value": token, "hook": found["hook"]})
return "CAPTCHA answered. Submit the form now without reloading the page."
Pass tools to the Agent constructor alongside the task and model (the keyword was controller= in earlier releases). The return strings matter as much as the code: each one tells the model exactly what to do next, which prevents the most common failure, an agent that reloads the page and throws away a valid token.
Why the probe runs in code
The action finds the widget with a DOM query instead of asking the model to describe what it sees. A text snapshot of the page may not mention an invisible reCAPTCHA at all, and a screenshot can suggest a widget that is not there. The probe returns a fact: either a container with a key, or nothing. It also reads data-callback, because many forms keep the submit button disabled until the widget calls that function, and an agent that clicks a disabled button will conclude, wrongly, that the token failed.
The probe covers the two widgets agents meet most on forms. To add reCAPTCHA v3, look for a script with render= in its URL and send a ReCaptchaV3TaskProxyLess task with the action name; there is no field to fill, so the token goes into the request the page sends, which usually means a dedicated action for that site.
Prompting and observing
Add one line to the task text: "If a page shows a CAPTCHA or security checkbox, call solve_captcha_widget once before submitting." Models follow a concrete instruction tied to a visible condition far better than a general rule about bots. Watch the first runs with the browser window visible and the agent's step history saved. A healthy run shows the form being filled, one call to the action lasting several seconds, then the submit. Recent releases also accept step hooks on agent.run(), which you can use to run the probe after every step and log when a widget appears, even when the model does not call the action.
Errors, limits and cost
Three limits keep an agent run from wandering. The per URL counter in the action stops repeated solves on one page. The agent's own maximum step setting ends a confused run. And the solver gives up after about two minutes, the same window after which an unsolved task is failed and free on our side. Each successful answer is billed at the type's rate, $0.56 per 1,000 for the checkbox and $0.84 for Turnstile. For full page challenges such as the Cloudflare check screen, solve before the agent starts and hand it the warmed up session, since that answer is a cookie bound to an IP, not a field. The article on CAPTCHA loops in agents covers budgets in more depth.
Scaling agent runs
Run one agent per browser profile and let each solve its own widgets; tokens are tied to the page that requested them. GateSolver has no limit on concurrent tasks, and the per key budget of 600 requests per minute covers dozens of agents polling at three second intervals. Keep the attempt counter per agent instance rather than global if runs share a process. Point agents at sites you own, test environments, or public pages that allow automation; signing in to accounts that are not yours is outside our terms. For a wider view of agents and challenges, read why AI agents get blocked.
Common questions
Does GateSolver ship a Browser Use plugin?
No. The integration is a custom action you add yourself, which calls the public HTTP API with your key.
Does the model driving the agent ever receive the GateSolver key?
No. The key stays in the environment and inside the action code; the model only sees the action description and the sentences it returns.
What if my Browser Use version has no get_current_page method?
Change only the run_js adapter to whatever your version uses to evaluate JavaScript in the active tab; the rest of the action stays the same.
Why does the action tell the model not to reload?
A reload renders a new widget, which makes the token already placed useless. Submitting right after the action keeps it valid.
Can the agent solve image grids by itself instead?
It can try from screenshots, but that takes many slow steps. A token from the API is faster and does not depend on how the model reads images.
Keep reading
- When a Browser Use agent gets blockedDiagnose why a Browser Use agent stops on a challenge, add a custom solve action and keep the browser session consistent afterwards.
- Breaking CAPTCHA loops in AI web agentsWhy language model agents retry the same blocked step indefinitely, and the guards, budgets and timeouts that end each run cleanly.
- How do I give an AI agent a CAPTCHA tool?Wrap createTask and getTaskResult in one function with a clear schema, register it as a tool, and let the agent call it.
- AI browser agentLanguage model driven programs that open pages, click and type in a real browser, and what happens when they reach a CAPTCHA.