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

Integration guide

OpenAI Agents SDK integration: a function tool for CAPTCHA answers

The Agents SDK turns a typed Python function into a tool with one decorator. This guide uses that to give an agent a solve tool, and a run context so the token never has to pass through the model.

The design in brief

Two function tools share one run context. solve_captcha sends a task to the GateSolver API, waits for the answer, and stores the token in the context under a short reference such as t1. submit_form receives that reference from the model, looks up the token in the context, and posts the form. The model coordinates the steps but never copies a 500 character token, which saves context and removes the risk of a token being altered on the way through.

Everything that talks to the API is plain HTTP. GateSolver does not publish an SDK, so the tool code below is the whole integration.

Install and check the SDK version

Install with pip install openai-agents httpx and set OPENAI_API_KEY for the model and GATESOLVER_KEY for solving. At the time of writing the package is imported as agents and exposes Agent, Runner, function_tool and RunContextWrapper. The SDK is young and evolving, so confirm these names in its documentation for the version you install.

The @function_tool decorator reads the function's type hints and docstring to build the tool's JSON schema. Arguments documented in the docstring get those descriptions in the schema, and a first parameter typed as RunContextWrapper is filled in by the SDK and hidden from the model.

The tools

import asyncio, os, httpx
from dataclasses import field, dataclass
from typing import Literal
from agents import RunContextWrapper, function_tool

@dataclass
class SolveState:
    tokens: dict[str, str] = field(default_factory=dict)
    tries: int = 0
    budget: int = 3

async def _ask(client: httpx.AsyncClient, route: str, body: dict) -> dict:
    body = {**body, "clientKey": os.environ["GATESOLVER_KEY"]}
    return (await client.post(f"https://gatesolver.com/{route}", json=body)).json()
@function_tool
async def solve_captcha(ctx: RunContextWrapper[SolveState],
                        kind: Literal["recaptcha_v2", "turnstile"], page_url: str, site_key: str) -> str:
    """Solve the CAPTCHA widget on a page and store the token.

    Args:
        kind: recaptcha_v2 for a Google checkbox, turnstile for a Cloudflare box.
        page_url: Full address of the page showing the widget.
        site_key: The widget's data-sitekey value.
    """
    state = ctx.context
    if state.tries >= state.budget:
        return "Solve budget used up for this run. Stop and report."
    state.tries += 1
    task_type = "AntiTurnstileTaskProxyLess" if kind == "turnstile" else "ReCaptchaV2TaskProxyLess"
    async with httpx.AsyncClient(timeout=30) as client:
        made = await _ask(client, "createTask", {"task": {"type": task_type,
                          "websiteURL": page_url, "websiteKey": site_key}})
        if made.get("errorId"):
            return f"Task not accepted: {made.get('errorCode')}. Check page_url and site_key."
        for _ in range(40):
            await asyncio.sleep(3)
            status_reply = await _ask(client, "getTaskResult", {"taskId": made["taskId"]})
            if status_reply.get("status") == "ready":
                ref, sol = f"t{len(state.tokens) + 1}", status_reply["solution"]
                state.tokens[ref] = sol.get("token") or sol["gRecaptchaResponse"]
                return f"Solved. Token stored as {ref}; pass {ref} to submit_form now."
            if status_reply.get("errorId") or status_reply.get("status") == "failed":
                return "Solve failed (not charged). You may call solve_captcha once more."
    return "Still unsolved after two minutes. Stop and report."

The kind argument uses friendly names instead of API type names, and a Literal keeps the model inside the two supported choices. Every return string is an instruction. The budget in the context caps solves per run, independent of how the model reasons.

Submitting with a token reference

from agents import Agent, Runner

@function_tool
async def submit_form(ctx: RunContextWrapper[SolveState], form_url: str,
                      fields: dict[str, str], token_ref: str, token_field: str) -> str:
    """Post a form with a stored CAPTCHA token.

    Args:
        form_url: The form's action URL.
        fields: Other form fields and their values.
        token_ref: Reference returned by solve_captcha, like t1.
        token_field: g-recaptcha-response or cf-turnstile-response.
    """
    token = ctx.context.tokens.pop(token_ref, None)
    if token is None:
        return "Unknown or already used token reference. Solve again first."
    async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
        sent = await client.post(form_url, data={**fields, token_field: token})
    return f"Form posted, HTTP {sent.status_code}, {len(sent.text)} bytes returned."

form_agent = Agent(
    name="Form tester",
    instructions=("You test forms on our staging site. When a page has a CAPTCHA, call solve_captcha, "
                  "then submit_form with the returned reference. Never invent site keys."),
    tools=[solve_captcha, submit_form],
)

result = Runner.run_sync(form_agent, "Submit the contact form at https://staging.example.com/contact "
                         "with email qa@example.com. Its reCAPTCHA site key is 6Lc_EXAMPLE_KEY.",
                         context=SolveState(), max_turns=8)
print(result.final_output)

pop removes the token as it is used, mirroring the single use rule on the site's side: a second submit with the same reference is refused locally instead of failing remotely. A dict[str, str] argument is accepted by the schema builder in current versions; if yours rejects it, use a JSON string argument and parse it.

Extending the kinds

To support reCAPTCHA v3, add "recaptcha_v3" to the Literal, an optional page_action argument documented as "the action name passed to grecaptcha.execute", and map the kind to ReCaptchaV3TaskProxyLess. v3 tokens cost $0.70 per 1,000 and only score well when the action matches the site. Because a v3 token is sent in the page's own request rather than a form field, its submit tool usually differs per site, so write it for the endpoint you are testing instead of reusing submit_form. Each new kind should come with a sentence in the agent instructions that says when to choose it.

Testing the tools without a model

Keep the HTTP logic testable on its own. The simplest way is to move the body of solve_captcha into a plain async function that takes a SolveState and the three arguments, and let the decorated tool call it. A short script can then run that function with asyncio.run against Google's public demo widget and print the stored reference, which confirms the key, the network and the task fields before any model turns are spent. The same split lets unit tests replace the API call with a fake that returns a fixed solution, so you can check budgets and token references quickly and offline.

Handing work between agents

The SDK supports handoffs between agents, and a common layout is a planning agent that delegates form work to a specialist. Give the solve and submit tools only to the specialist. That keeps the planner's tool list short, and it means only one agent's instructions need to explain when solving is appropriate. The run context is shared across the whole run, so a token solved by one agent is still available by reference if another agent submits the form, though in practice keeping both steps in one agent is simpler to reason about.

Where the site key comes from

In the example, the site key is given in the prompt, which suits a test suite that knows its own staging pages. For unknown pages, add a third function tool that downloads the page and returns the widget kind and key, as the LangChain guide does with its inspector. Never let the model guess a key from memory: a wrong key produces a token the site rejects, and that solve was still a completed, billed task.

Errors, retries and tracing

Errors are returned as text, not raised, so the model reads them and the run continues in a controlled way. The SDK also catches exceptions raised inside a tool and reports them to the model by default; returning explicit text keeps the wording under your control. max_turns on the runner ends a run that keeps calling tools. The SDK traces runs by default at the time of writing, and traces include tool arguments and outputs; because the token stays in context and the key stays in the environment, neither appears there. Pricing follows the task type, $0.56 per 1,000 for the checkbox and $0.84 for Turnstile, charged only when an answer is delivered.

Scaling

Use await Runner.run(...) in async code to run many agents in one event loop, each with its own SolveState, so budgets and tokens never leak between runs. The API accepts unlimited concurrent tasks; the shared ceiling is 600 requests per minute per key, which three second polling leaves plenty of room under. Keep such agents on permitted work: testing your own forms, collecting public data, assisting users who cannot complete a visual challenge. Background on agents and challenges is in giving an agent a CAPTCHA tool and why agents meet CAPTCHAs.

Common questions

Does this need an OpenAI model specifically?

The SDK is built around OpenAI models, and its docs describe options for other providers; the GateSolver tools work with whichever model the agent uses.

Why store the token in the run context?

Tokens are long, single use strings. Keeping them in Python state avoids spending context on them and removes the chance of a model altering one while copying.

Can the tools be synchronous functions?

Yes. function_tool accepts plain functions too; async ones are better when many runs share an event loop.

What does max_turns protect against?

It ends a run after a set number of model turns, so an agent that keeps retrying a tool cannot run indefinitely.

Will traces expose my GateSolver key?

Not with this design. The key is read from the environment inside the tool and never appears in tool arguments or outputs.

Keep reading