NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Integration guide

LangChain integration: a CAPTCHA tool built on the HTTP API

This guide builds a general purpose LangChain tool that takes a task type, page URL and site key and returns a token. Any agent or chain in your project can then call it like any other tool.

What the tool is for

A LangChain tool is a typed function plus a description that a model can choose to call. The tool on this page wraps the two GateSolver calls, /createTask and /getTaskResult, behind one schema: the model fills in which widget it found, the page address and the site key, and receives a token string. It suits agents that work at the HTTP level (fetching pages and posting forms through tools) and agents with a browser alike, because the token is just a string either one can submit.

If your agent drives a browser and you would rather the tool find and fill the widget itself, see the browser bound variant in our post on a LangChain agent stuck on reCAPTCHA. That design takes no arguments; this one takes explicit, validated arguments, which makes it reusable across chains and easy to test.

Install

Install the core package and a model integration, for example pip install langchain-core langchain httpx pydantic plus the provider package you use. The tool itself depends only on langchain_core, which keeps it stable across LangChain releases; agent constructors change more often, so the wiring section notes which names to check. Put the key in GATESOLVER_KEY.

Schema first: limit what the model can ask for

The input schema is your main safety control. A Literal type for the task type means the model can only choose from token types you support, so it cannot invent a type name or ask for something the API does not offer. Field descriptions become part of the tool definition the model reads, so they double as instructions: say exactly where each value comes from.

import os, time
from typing import Literal, Optional
import httpx
from pydantic import BaseModel, Field
from langchain_core.tools import StructuredTool, ToolException, tool

LC_SOLVER = "https://gatesolver.com"

class CaptchaRequest(BaseModel):
    task_type: Literal["ReCaptchaV2TaskProxyLess", "ReCaptchaV3TaskProxyLess",
                       "AntiTurnstileTaskProxyLess"] = Field(description="Widget kind seen on the page")
    page_url: str = Field(description="Full URL of the page that shows the widget")
    site_key: str = Field(description="data-sitekey value, or the render= key for reCAPTCHA v3")
    page_action: Optional[str] = Field(None, description="reCAPTCHA v3 action name, only if known")

def get_captcha_token(task_type: str, page_url: str, site_key: str,
                      page_action: Optional[str] = None) -> str:
    task = {"type": task_type, "websiteURL": page_url, "websiteKey": site_key}
    if page_action:
        task["pageAction"] = page_action
    with httpx.Client(base_url=LC_SOLVER, timeout=30) as http:
        def send(path: str, extra: dict) -> dict:
            return http.post(path, json={"clientKey": os.environ["GATESOLVER_KEY"], **extra}).json()
        opened = send("/createTask", {"task": task})
        if opened.get("errorId") not in (None, 0):
            raise ToolException(f"Task refused ({opened.get('errorCode')}). Check the inputs before retrying.")
        for _ in range(40):
            time.sleep(3)
            polled = send("/getTaskResult", {"taskId": opened["taskId"]})
            if polled.get("status") == "ready":
                answer = polled["solution"]
                return answer.get("gRecaptchaResponse") or answer["token"]
            if polled.get("status") == "failed" or polled.get("errorId"):
                raise ToolException("The solve failed and was not charged. One more call is fine.")
    raise ToolException("No token after two minutes. Stop and tell the user.")

solve_captcha = StructuredTool.from_function(
    func=get_captcha_token, name="solve_captcha", args_schema=CaptchaRequest,
    description="Get a CAPTCHA token for a web page; the result is the token string your form post needs.",
    handle_tool_error=True)

ToolException together with handle_tool_error=True turns failures into tool output instead of crashing the run. The model receives the message text, so each message is written as an instruction: check the inputs, try once more, or stop. That wording is what keeps an agent from looping on a page that will not accept an answer.

Giving the model real page values

The model needs the site key from somewhere, and guessing is the worst option. Give it a second tool that reads the page and reports what it found, so the arguments of solve_captcha always come from real HTML.

import re  # same module as the solve tool above

@tool
def inspect_form_page(url: str) -> dict:
    """Download a page and report any CAPTCHA widget on it, with the values solve_captcha needs."""
    html = httpx.get(url, timeout=20, follow_redirects=True).text
    turnstile = re.search(r'class="cf-turnstile"[^>]*data-sitekey="(0x4[\w-]+)"', html)
    checkbox = re.search(r'class="g-recaptcha"[^>]*data-sitekey="([\w-]{30,})"', html)
    score = re.search(r"recaptcha/api\.js\?render=([\w-]{30,})", html)
    if turnstile:
        return {"task_type": "AntiTurnstileTaskProxyLess", "site_key": turnstile[1], "page_url": url}
    if checkbox:
        return {"task_type": "ReCaptchaV2TaskProxyLess", "site_key": checkbox[1], "page_url": url}
    if score:
        return {"task_type": "ReCaptchaV3TaskProxyLess", "site_key": score[1], "page_url": url,
                "note": "find the action name passed to grecaptcha.execute"}
    return {"widget": None}

print(solve_captcha.invoke({"task_type": "ReCaptchaV2TaskProxyLess",
      "page_url": "https://www.google.com/recaptcha/api2/demo",
      "site_key": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-"}))

The regular expressions assume the class attribute comes before data-sitekey, which is common but not universal; a parser such as Beautiful Soup removes that assumption. The last lines call the tool directly with Google's public demo widget, which is the quickest test that the key, network and schema work before any model is involved.

Adding more task types

Resist the urge to make one tool that accepts every type. Each type needs different inputs: v3 needs an action, Turnstile may need metadata, image tasks need a base64 picture instead of a URL. A schema with many optional fields invites the model to fill the wrong ones. Two or three focused tools, each with a short schema and a precise description, are easier for a model to use correctly and easier for you to test. An image tool, for example, takes only image_b64, sends an ImageToTextTask polled every second, and returns the text.

Wiring it into an agent

Pass both tools in the agent's tool list. At the time of writing, LangChain 1.x offers create_agent in langchain.agents, and LangGraph offers create_react_agent in langgraph.prebuilt; older code used AgentExecutor. The tools work with all of them because they follow the standard tool interface, so check the docs for your version and change only the constructor. A system prompt line such as "Call inspect_form_page before solve_captcha, and submit the token immediately" fixes the order. For lower level control, model.bind_tools([solve_captcha, inspect_form_page]) gives you tool calls you execute yourself.

Using the token

The token is single use and short lived, about two minutes for reCAPTCHA. Your submit tool should accept it as an argument and post the form right away, with g-recaptcha-response or cf-turnstile-response as the field name. Long tokens copied through a model can occasionally come back altered, so for production agents consider storing the token in Python state and passing a short reference instead; the OpenAI Agents SDK guide shows that pattern with a run context, and it transfers directly to LangGraph state.

Errors, retries and cost

The tool already separates refusals (inputs or account problems) from failed tasks (free, worth one more try). Add a per run counter if your agent might call it in a loop, and cap the agent's iterations. Tasks are charged only when a token is delivered: $0.56 per 1,000 for the checkbox, $0.70 for v3 and $0.84 for Turnstile. Set the poll interval to three seconds as shown; faster polling does not return answers sooner, it only spends more of the 600 requests per minute your key allows.

Scaling and async

For async agents, pass an async function as coroutine= to StructuredTool.from_function alongside the sync one, using httpx.AsyncClient and asyncio.sleep, so many agents can wait on solves in one event loop. Concurrent tasks are unlimited on our side. Tracing tools such as LangSmith will record tool inputs and outputs, so keep the API key in the environment and never in a tool argument. Use agents like these for permitted automation: testing your own forms, public data collection, accessibility tooling. See LangChain in our glossary for the basic concepts and how models call external APIs for the mechanics behind tool calls.

Common questions

Do I need to install anything from GateSolver for LangChain?

No. The tool on this page uses the public HTTP API directly, so it needs nothing beyond langchain_core, httpx and pydantic.

Why restrict task_type with a Literal?

The model can then only pick from types you listed, which prevents invented type names and requests for unsupported challenges.

Will the tool work with LangGraph?

Yes. LangGraph agents accept standard LangChain tools, so the same object goes into the tools list of a LangGraph agent or ToolNode.

What does handle_tool_error=True change?

A ToolException raised in the function becomes the tool result text, so the model reads the instruction instead of the run stopping with an error.

Can the tool solve image CAPTCHAs too?

Yes, with a second schema that takes a base64 image and returns the text from an ImageToTextTask; keep it separate so each tool stays simple.

Keep reading