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

AI agents and automation

CrewAI agents and login CAPTCHAs

A CrewAI crew that reports on your own dashboards often has to sign in first, and that sign in page may carry a CAPTCHA. This guide builds one tool that handles the widget so the rest of the crew can work with a logged in session.

The scenario this guide covers

Picture a crew with a researcher agent and a writer agent. The researcher signs in to your company's analytics portal, collects last week's numbers and passes them on; the writer turns them into a summary. The portal's login form has a reCAPTCHA or Turnstile widget. Nothing about the task is unusual: it is your account, on a service you pay for, doing what you would do by hand each Monday. The CAPTCHA is the one step the agents cannot finish themselves.

Keep that boundary clear. The tool below is for your own credentials on services that allow automated access, or for test accounts in a staging system. It is not for trying passwords or signing in to accounts you do not own, which is account takeover and against our terms.

Separate the login from the reasoning

A login is a fixed sequence: open the page, type the username, type the password, solve the widget, submit, confirm. There is nothing for a language model to decide. Putting the whole sequence inside one deterministic tool has three benefits. Credentials never pass through the model's context. The flow behaves the same way every run. And the agent spends its steps on the part that needs judgment, reading the dashboard.

So the design is one tool, portal_login, which takes no secrets as arguments, reads them from the environment, and returns a short status. The browser session it opens stays alive for the other tools.

A small solver client

This client is synchronous because CrewAI tools implement a synchronous _run method by default. It covers both widget types a login form tends to use.

import os, time
import requests

class WidgetSolver:
    base = "https://gatesolver.com"

    def __init__(self) -> None:
        self.key = os.environ["GATESOLVER_KEY"]
        self.http = requests.Session()

    def _send(self, route: str, payload: dict) -> dict:
        payload = {"clientKey": self.key, **payload}
        return self.http.post(f"{self.base}/{route}", json=payload, timeout=30).json()

    def answer(self, kind: str, url: str, sitekey: str) -> str:
        task_type = {"recaptcha": "ReCaptchaV2TaskProxyLess",
                     "turnstile": "AntiTurnstileTaskProxyLess"}[kind]
        made = self._send("createTask", {"task": {"type": task_type,
                          "websiteURL": url, "websiteKey": sitekey}})
        if made.get("errorId"):
            raise RuntimeError(made.get("errorCode"))
        deadline = time.time() + 125
        while time.time() < deadline:
            time.sleep(3)
            out = self._send("getTaskResult", {"taskId": made["taskId"]})
            if out.get("status") == "ready":  # solved
                s = out["solution"]
                return s.get("gRecaptchaResponse") or s["token"]
            if out.get("status") == "failed" or out.get("errorId"):
                raise RuntimeError(out.get("errorCode") or "task failed")
        raise TimeoutError("no answer in time")

The CrewAI tool

CrewAI tools can subclass BaseTool from crewai.tools, setting a name, a description and a _run method. At the time of writing that is the documented way to build a custom tool; check the CrewAI docs if your version moved it. The tool below uses Playwright's synchronous API and keeps the page in a module level dictionary so a second tool can read from it.

from crewai.tools import BaseTool
from playwright.sync_api import sync_playwright  # pip install playwright

LIVE = {}  # shared with other tools: LIVE["page"]

class PortalLogin(BaseTool):
    name: str = "portal_login"
    description: str = "Sign in to the analytics portal. Call once before reading reports."

    def _run(self) -> str:
        pw = sync_playwright().start()
        pg = LIVE["page"] = pw.chromium.launch().new_page()
        pg.goto(os.environ["PORTAL_LOGIN_URL"])
        pg.fill("#username", os.environ["PORTAL_USER"])
        pg.fill("#password", os.environ["PORTAL_PASS"])
        widget = pg.evaluate("""() => {
            const t = document.querySelector('.cf-turnstile[data-sitekey]');
            if (t) return ['turnstile', t.dataset.sitekey];
            const r = document.querySelector('.g-recaptcha[data-sitekey]');
            return r ? ['recaptcha', r.dataset.sitekey] : null; }""")
        if widget:
            kind, sitekey = widget
            try:
                tok = WidgetSolver().answer(kind, pg.url, sitekey)
            except Exception as exc:
                return f"Login stopped: CAPTCHA not solved ({exc})."
            box = "cf-turnstile-response" if kind == "turnstile" else "g-recaptcha-response"
            pg.evaluate("([n, v]) => { document.getElementsByName(n)"
                        ".forEach(e => e.value = v); }", [box, tok])
        pg.click("button[type=submit]")
        pg.wait_for_load_state("networkidle")
        return "Signed in." if "/login" not in pg.url else "Login failed; check credentials."

The selectors #username, #password and the submit button are placeholders; read the real ones from your login form once. If the site calls a JavaScript callback when the widget is completed, call it after filling the field, as described in the guide to finding the reCAPTCHA callback.

Wire the tool into the crew

Give the tool to the agent that needs a signed in session, and order the tasks so login comes first. A task description such as "Sign in with portal_login, then open the weekly report and list the five largest changes" is enough. The writer agent needs no tool at all; it receives the researcher's output.

If another tool reads report pages, let it read the same Playwright page object from the shared LIVE dictionary. Opening a second browser would lose the cookies the login just earned.

Keep secrets and costs under control

  • Credentials and the API key live in environment variables. The model never sees them, and they do not show up in CrewAI's verbose logs.
  • A solved login widget costs $0.56 per 1,000 for reCAPTCHA v2 or $0.84 for Turnstile. One login per run is a fraction of a cent.
  • Failed and expired tasks are free, so an occasional retry costs only time. Still cap it: the tool above tries once and reports, and the agent should not call it in a loop.
  • Save the browser's storage state after a successful login and reload it next run. If the session cookie is still valid, you skip the login and the CAPTCHA entirely.

When the login still fails

If the token is placed but the server rejects the login, check three things in order. The token may have expired because the form took too long after the solve; solve last, right before submit. The page may use invisible reCAPTCHA, which needs isInvisible: true in the task. Or the site checks the score of reCAPTCHA v3, which needs a different task type and the right page action. The page on reCAPTCHA v2 lists the task fields for each variant.

Running the tool by itself first

Instantiate PortalLogin() in a plain script and call its _run() method before any agent is involved. You should see "Signed in." and, if you launch the browser headed for this test, a dashboard page. If you see "Login failed", compare the selectors with the real form and check that the environment variables are set in the shell that runs the script. Fixing these here costs nothing; finding them inside a crew run costs model calls and time.

Once the tool works alone, add it to the agent and run the crew with verbose output. The log should show one call to portal_login at the start of the researcher's task, a short pause for the solve, and then the reading tools. If the agent calls the login tool again later, tighten the task description so it signs in only once.

Two factor and other extra steps

Many portals add a second factor after the password. A CAPTCHA solve does not help with that, and it should not: a one time code belongs to the account owner. For scheduled crews, prefer a service account or API token that the portal issues for automation, and keep the CAPTCHA tool for portals that offer nothing better.

Common questions

Should the CrewAI agent see my portal password?

No. Read credentials from the environment inside the tool so they never enter the prompt, the model context or the logs.

Can I use the tool decorator instead of subclassing BaseTool?

Yes. CrewAI also offers a decorator for simple function tools; a class is just tidier when the tool carries its own name and description fields.

What if my login page uses reCAPTCHA v3?

Switch the task type to ReCaptchaV3TaskProxyLess and send the pageAction the site uses, then add the token to the login request.

Is a solve charged if the login itself fails?

Yes, if the token was returned. Charging happens when the task is solved, independent of what the site does with the token afterwards.

Can this sign in to accounts I do not own?

No. The pattern is for your own accounts and test accounts on services that allow automation; anything else is outside our terms.

Keep reading