AI agents and automation
A LangChain agent that keeps hitting reCAPTCHA
When a LangChain agent browses a form protected by reCAPTCHA, the run stalls on the same step every time. This guide adds one tool that reads the widget, gets a token from the API at $0.56 per 1,000, and hands control back to the agent.
Why the agent stalls on the same step
The agent's browsing tool loads the page, the model reads the content, and it decides to fill the form and press submit. The site answers with the same page and an error near the checkbox, because the g-recaptcha-response field was empty. The model has no way to produce that value, so it tries again, rewords its plan, and eventually hits its iteration limit. The cure is to give it a tool that can produce the value.
This guide assumes your agent already controls a browser through Playwright, either directly or through a toolkit, and that the target is a site you are permitted to automate: your own product, a staging copy, or a public form whose terms allow it.
Detect the widget in code, not in the prompt
It is tempting to tell the model "if you see a CAPTCHA, call the tool". Models do notice an "I'm not a robot" box in a text snapshot, but they also miss invisible variants and sometimes hallucinate one. A small check after each navigation is cheaper and exact. It returns the site key when a widget exists and nothing otherwise.
FIND_RECAPTCHA = """
() => {
const holder = document.querySelector('[data-sitekey]');
if (holder) return { key: holder.dataset.sitekey,
invisible: holder.dataset.size === 'invisible' };
const frame = document.querySelector('iframe[src*="recaptcha/api2/anchor"]');
if (!frame) return null;
const k = new URL(frame.src).searchParams.get('k');
return k ? { key: k, invisible: frame.src.includes('size=invisible') } : null;
}
"""
def recaptcha_on(page):
return page.evaluate(FIND_RECAPTCHA)
You can run this inside your navigation tool and append a line such as "reCAPTCHA present, call solve_recaptcha before submitting" to the observation the model receives. The model then has a concrete instruction tied to a fact it did not have to infer.
Write the tool
LangChain's @tool decorator in langchain_core.tools turns a typed function with a docstring into a tool the model can call. The docstring becomes the description, so write it for the model: when to call it and what it returns. At the time of writing this decorator is stable across recent versions; check the current LangChain docs if your import path differs.
import os, time, requests
from langchain_core.tools import tool # the decorator
GS = "https://gatesolver.com"
browser_page = None # set to the Playwright page your agent drives
def _gs(path, body):
body["clientKey"] = os.environ["GATESOLVER_KEY"]
return requests.post(GS + path, json=body, timeout=30).json()
@tool
def solve_recaptcha() -> str:
"""Solve the reCAPTCHA on the current page and place the token.
Call this once before submitting a form that shows a reCAPTCHA."""
found = recaptcha_on(browser_page)
if not found:
return "No reCAPTCHA found on this page."
job = _gs("/createTask", {"task": {"type": "ReCaptchaV2TaskProxyLess",
"websiteURL": browser_page.url, "websiteKey": found["key"],
"isInvisible": found["invisible"]}})
if job.get("errorId"):
return f"Solver error {job.get('errorCode')}; do not retry this step."
for _ in range(42):
time.sleep(3)
res = _gs("/getTaskResult", {"taskId": job["taskId"]})
if res.get("status") == "ready": # token arrived
fill_token(browser_page, res["solution"]["gRecaptchaResponse"])
return "reCAPTCHA solved. You can submit the form now."
if res.get("status") == "failed" or res.get("errorId"):
return "The solve failed (no charge). Try the tool once more."
return "No answer within two minutes. Stop and report."
Two choices here are deliberate. The tool takes no arguments, so the model cannot pass a wrong URL or a made up key. And every return value is a short sentence telling the model what to do next, which keeps its reasoning on track.
Put the token where the page expects it
The checkbox stores its answer in a hidden textarea. Fill it, and if the site registered a callback (many enable the submit button from one), call it with the same token. The guide on how to find the reCAPTCHA callback explains how to locate that function name.
def fill_token(pg, token: str) -> None:
pg.evaluate("""(t) => {
document.querySelectorAll('textarea[name="g-recaptcha-response"]')
.forEach(el => { el.value = t; });
const cbName = document.querySelector('[data-callback]')?.getAttribute('data-callback');
if (cbName && typeof window[cbName] === 'function') window[cbName](t);
}""", token)
Note that LangChain tools that wrap Playwright are often synchronous. If your agent uses the async Playwright API, make the tool async def and await the page calls; the decorator supports coroutines too.
Register the tool and resume the run
Add solve_recaptcha to the same tool list as your browsing tools. How you build the agent depends on your LangChain or LangGraph version; whichever constructor you use, the tool list is the only change. A line in the system prompt helps: "If an observation says a reCAPTCHA is present, call solve_recaptcha once, then continue."
Because the token lands in the live page, the agent does not need to restart. Its next action is the submit it planned before, and the site now receives a filled field. Tokens expire after about two minutes, so the tool solves at the moment of need rather than at the start of the run.
Guard against loops
An agent that receives "failed" can call the tool forever. Count calls per page URL in a dictionary and refuse after two attempts with a message such as "Solving has failed twice here; stop and summarize". Pair that with the framework's own iteration cap. The article on breaking CAPTCHA loops in AI web agents covers budgets and timeouts in more depth.
Checking the v3 case
If the page has no checkbox but loads recaptcha/api.js?render=6L..., it uses reCAPTCHA v3. The same tool shape works with a ReCaptchaV3TaskProxyLess task and a pageAction value, at $0.70 per 1,000. The token then goes into whatever request the page sends, which you can read from the network tab once. Look at reCAPTCHA v3 for the fields.
Testing the tool outside the agent
Before you hand the tool to a model, call it directly from a short script. Open the page with Playwright, set browser_page, and invoke solve_recaptcha.invoke({}). You should see the success sentence, and the hidden textarea in the page should now hold a long string. Doing this first separates two kinds of failure: problems in your tool (a wrong selector, a missing environment variable, an expired key) and problems in the agent (it never calls the tool, or calls it at the wrong moment). Mixing them makes both harder to find.
A public demo page with a reCAPTCHA v2 checkbox is a convenient fixture while you build, since it changes rarely and has nothing to break. Switch to your real target once the tool works end to end.
What the trace should look like
With LangSmith or plain verbose logging on, a healthy run shows the browsing tool's observation with the "reCAPTCHA present" note, one call to solve_recaptcha a few seconds long, the success sentence, and then the submit action. If you see two solve calls back to back, the agent probably reloaded in between; tighten the prompt. If you see none, the note is not reaching the model, so print the observation text your browsing tool returns.
Common questions
Does LangChain include a built in CAPTCHA tool for this?
Not one that calls GateSolver. You write a short tool function like the one above and add it to the agent like any other tool.
Can the model call the tool with the site key itself?
It can, but reading the key in code is safer. A tool without arguments cannot receive a wrong or invented value.
Will this work with LangGraph instead of a classic agent?
Yes. LangGraph nodes call the same tool functions, so the tool code stays the same and only the graph wiring differs.
How long can the agent wait for an answer?
Token tasks usually return under 9 seconds. A task still unsolved after 120 seconds is marked failed and is not charged.
What if the page reloads after the token is filled?
The token is lost with the old page. Solve again on the new page; each token is single use anyway.
Keep reading
- LangChainA typed LangChain StructuredTool around createTask and getTaskResult, with schema limits, tool errors the model understands, and agent wiring.
- LangChainThe open source framework for building LLM applications from models, prompts and tools, including tools that call outside APIs.
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- Find the reCAPTCHA callback functionFrom data-callback to a walk through the ___grecaptcha_cfg clients object: how to reach the function that consumes the token.