# For AI agents

> Instructions for AI coding agents (Claude Code, Cursor, Codex and others) that integrate NoptCHA - use the v1 API, start in the keyless sandbox, wait for the result in one request, handle errors, put the token back in the page and keep the key secret.

Source: https://noptcha.com/docs/for-ai-agents/

This page is written for AI coding agents that add NoptCHA to someone’s code, and for developers who want to give their agent the rules in one place. Each rule links to the page with the details. The same content is available as Markdown at [/docs/for-ai-agents.md](https://noptcha.com/docs/for-ai-agents.md), and the whole site is indexed in [/llms.txt](https://noptcha.com/llms.txt).

## The rules in short

1.  Use the **native API (v1)**: `POST https://api.noptcha.com/v1/tasks`, key in `Authorization: Bearer …`.
2.  Get it working in the **keyless sandbox** first (`/v1/sandbox/tasks`, no key, no account), then with a **test key** (`nop_test_…`), and only then with a **live key** (`nop_live_…`). The code does not change between them.
3.  Send `Prefer: wait=60` and an `Idempotency-Key`: one request usually returns the finished task.
4.  Retry only `429`, `5xx` and network errors, honouring `Retry-After`; fix everything else. A task with `status: "failed"` is not charged.
5.  Put the token back where the page reads it (hidden field, callback), then submit. See [Browser automation](https://noptcha.com/docs/integrations.md).
6.  Read the key from the environment. Never put it in front-end code, never commit it.
7.  Do not install packages named `noptcha` from PyPI or npm: the [SDKs](https://noptcha.com/docs/sdks.md) are not published yet. Use plain HTTP (examples below) or the [helper modules](https://noptcha.com/docs/integrations.md#the-helper-modules).

## Use the native API (v1)

NoptCHA has three APIs that share keys, prices and tasks. For new code, use the [native API (v1)](https://noptcha.com/docs/native-api.md): one request can wait for the result, retries are safe with idempotency keys, and errors are [RFC 9457 problem details](https://noptcha.com/docs/errors.md) with a stable `code`. Use the [createTask API](https://noptcha.com/docs/createtask-api.md) or the [in.php API](https://noptcha.com/docs/in-php-api.md) only when the code already speaks one of those protocols (for example, it was written for anti-captcha or 2captcha) and you are only changing its base URL.

A request names a task type and its parameters:

```json
{ "type": "turnstile", "params": { "website_url": "https://example.com/signup", "website_key": "0x4AAAAAAA…" } }
```

The type names and parameters are on the [task type pages](https://noptcha.com/docs/task-types.md); each has a JSON Schema at `https://noptcha.com/schemas/<type>.params.json`, and [`/openapi.json`](https://noptcha.com/openapi.json) describes every endpoint. Read the parameters from the page that shows the captcha: [where the parameters are](https://noptcha.com/docs/integrations.md#where-the-parameters-are).

## Start without a key, then switch keys

| Stage | Endpoint | Key | Answers |
| --- | --- | --- | --- |
| Keyless sandbox | `POST /v1/sandbox/tasks`, `GET /v1/sandbox/tasks/{id}` | none | fixed test answers, limited per IP |
| Test key | `POST /v1/tasks`, `GET /v1/tasks/{id}` | `nop_test_…` | the same fixed test answers, never charged |
| Live key | `POST /v1/tasks`, `GET /v1/tasks/{id}` | `nop_live_…` | real solutions, charged only when solved |

The request bodies, responses, validation and [error codes](https://noptcha.com/docs/errors.md) are the same in all three. In the sandbox a token is `NOPTCHA_TEST_TOKEN_<task id>`, and [magic values](https://noptcha.com/docs/sandbox.md#simulating-outcomes) such as `website_key: "test-unsolvable"` or `"test-slow-5"` simulate failures and slow tasks, so you can test the error and polling paths before spending anything. A site will not accept a sandbox token: the sandbox checks your code, not the site.

The keyless sandbox runs without an account, so you can run this as is:

**curl**

```bash
# no key needed: the keyless sandbox returns fixed answers (limited per IP)
# waits up to 60 s; 200 = finished (solved or failed), 202 = still processing
curl -s -X POST "https://api.noptcha.com/v1/sandbox/tasks?wait=60" \
  -H 'Content-Type: application/json' \
  -d @- <<EOF
{
  "type": "turnstile",
  "params": {
    "website_url": "https://example.com/signup",
    "website_key": "1x00000000000000000000AA",
    "action": "signup"
  }
}
EOF

# on 202: long-poll with the "id" from the response
TASK_ID=sbx_...
curl -s "https://api.noptcha.com/v1/sandbox/tasks/$TASK_ID?wait=60"
```


**Python**

```python
import time

import requests

API = "https://api.noptcha.com/v1/sandbox/tasks"  # no key needed; with a key use /v1/tasks and an Authorization header

r = requests.post(
    API,
    params={"wait": 60},
    json={
        "type": "turnstile",
        "params": {
            "website_url": "https://example.com/signup",
            "website_key": "1x00000000000000000000AA",
            "action": "signup",
        },
    },
    timeout=100,
)
task = r.json()
if r.status_code >= 400:
    raise RuntimeError(f"{task['code']}: {task.get('detail', '')}")
while task["status"] == "processing":  # 202: not finished within the wait
    time.sleep(1)
    r = requests.get(f"{API}/{task['id']}", params={"wait": 60}, timeout=100)
    task = r.json()
    if r.status_code >= 400:
        raise RuntimeError(f"{task['code']}: {task.get('detail', '')}")

if task["status"] == "solved":
    print(task["solution"])
else:
    print("failed:", task["error"]["code"], task["error"]["message"])
```


**Node.js**

```js
const API = 'https://api.noptcha.com/v1/sandbox/tasks'; // no key needed; with a key use /v1/tasks and an Authorization header

async function call(url, init) {
  const res = await fetch(url, init);
  const data = await res.json();
  if (!res.ok) throw new Error(`${data.code}: ${data.detail ?? ''}`);
  return data;
}

let task = await call(`${API}?wait=60`, {
  method: 'POST',
  body: JSON.stringify({
    type: "turnstile",
    params: {
      website_url: "https://example.com/signup",
      website_key: "1x00000000000000000000AA",
      action: "signup",
    },
  }),
});
while (task.status === 'processing') {
  await new Promise((r) => setTimeout(r, 1000));
  task = await call(`${API}/${task.id}?wait=60`); // long poll
}
if (task.status === 'solved') console.log(task.solution);
else console.log('failed:', task.error.code, task.error.message);
```

This is the shortest working call: `?wait=60` is the same as `Prefer: wait=60` (the query form also works from a browser), and it does not retry. For real code, send `Prefer: wait=60` with an `Idempotency-Key` and retry as described below, or copy `solve()` from the [helper modules](https://noptcha.com/docs/integrations.md#the-helper-modules), which does both.

To move to a key, the user creates one in the console (**API keys → Create key**, mode **Test** first) and puts it in the `NOPTCHA_KEY` environment variable. Then use `/v1/tasks` instead of `/v1/sandbox/tasks` and add the `Authorization: Bearer <key>` header; nothing else changes. The keyless sandbox differs in a few details (no `callback_url`; `Idempotency-Key` is accepted but a retry creates another free sandbox task; smaller bodies; its own limits): see [Keyless sandbox](https://noptcha.com/docs/sandbox.md#keyless-sandbox). Write the code so that the endpoint and key come from configuration, as the [helper modules](https://noptcha.com/docs/integrations.md#the-helper-modules) do: with `NOPTCHA_KEY=keyless` they use the keyless sandbox, with a `nop_test_` or `nop_live_` key they use `/v1/tasks`.

## Get the result in one request

`POST /v1/tasks` with `Prefer: wait=60` waits up to 60 seconds (at most 90) and returns:

-   `200` with the finished task: `status` is `solved` (read `solution`) or `failed` (read `error.code`);
-   `202` with `status: "processing"` if the task was not finished in time: long-poll `GET /v1/tasks/{id}?wait=60` until the status is final.

Always handle `202`, even if your tasks are usually fast: when many requests are waiting, the server can answer `202` at once. Send an `Idempotency-Key` (a new UUID per task) and, if you retry the request after a network error, the same key with the byte-for-byte same body, so that a retry returns the same task instead of creating a second one ([Idempotency](https://noptcha.com/docs/native-api/tasks.md#idempotency)). A finished task can be read for 10 minutes. Details: [Synchronous waiting](https://noptcha.com/docs/native-api/tasks.md#synchronous-waiting).

## Handle errors

There are two kinds of failure, and both need handling:

-   **The request failed**: HTTP `4xx` or `5xx` with a problem details body. Branch on its `code`, not on the message.
-   **The task failed**: HTTP `200` with `status: "failed"` and `error.code`. Nothing is charged.

| Code | What to do |
| --- | --- |
| `rate_limited`, `concurrency_limited` (429) | Wait `Retry-After` seconds, then retry |
| `service_unavailable` (503) | Wait `Retry-After` seconds, then retry; nothing was created or charged |
| `internal` (500), other `5xx` | Retry with backoff, with the same `Idempotency-Key` and body |
| Network error or timeout | Retry the same request with the same `Idempotency-Key` and body |
| `idempotency_conflict` (409) | If the first request is still being admitted, retry shortly; if the body differs, use a new key |
| `invalid_params` (422), `invalid_request` (400), `unsupported_type` (400), `request_too_large` (413) | Fix the request; `errors[].pointer` names the field. Do not retry unchanged |
| `unauthorized` (401), `forbidden` (403) | Check the key, its scopes and restrictions. Do not retry in a loop: invalid keys get the IP blocked |
| `insufficient_balance`, `budget_exceeded` (402) | Stop and tell the user: the balance or the key’s budget needs topping up |
| Task `unsolvable`, `timeout`, `proxy_error` | Free; you may create a new task for the same captcha (with a new idempotency key) |
| Task `invalid_site`, `invalid_image` | Free; the parameters are wrong (site key, domain, image). Fix them before trying again |

Clients must accept codes they do not know: treat an unknown `4xx` as “fix first” and an unknown `5xx` as retryable. The full list: [Errors](https://noptcha.com/docs/errors.md), [What to retry](https://noptcha.com/docs/errors.md#retrying), [Rate limits](https://noptcha.com/docs/limits.md).

## Put the token back in the page

The API returns a token; the captcha is solved only when the page’s own code receives it. Where it goes depends on the captcha (a hidden `g-recaptcha-response`, `h-captcha-response` or `cf-turnstile-response` field, a callback named in `data-callback`, or `grecaptcha.execute()` for reCAPTCHA v3): see the table in [Putting the token back](https://noptcha.com/docs/integrations.md#putting-the-token-back). Solve right before you submit, because tokens expire after a couple of minutes.

The [helper modules](https://noptcha.com/docs/integrations.md#the-helper-modules) (one Python file, one Node.js file, no dependencies besides `requests`) find the captcha’s parameters in the page, solve it and put the token back. Copy the module next to the script and wire it up as the framework page shows:

| Framework | Page |
| --- | --- |
| Playwright for Python | [Playwright (Python)](https://noptcha.com/docs/integrations/playwright-python.md) |
| Playwright for Node.js | [Playwright (Node.js)](https://noptcha.com/docs/integrations/playwright-node.md) |
| Puppeteer | [Puppeteer](https://noptcha.com/docs/integrations/puppeteer.md) |
| Selenium for Python | [Selenium (Python)](https://noptcha.com/docs/integrations/selenium-python.md) |
| browser-use | [browser-use](https://noptcha.com/docs/integrations/browser-use.md) |
| Stagehand | [Stagehand](https://noptcha.com/docs/integrations/stagehand.md) |
| Crawl4AI | [Crawl4AI](https://noptcha.com/docs/integrations/crawl4ai.md) |

To run a framework example without an account, set `NOPTCHA_KEY=keyless`:

```sh
export NOPTCHA_KEY=keyless        # keyless sandbox; later nop_test_..., then nop_live_...
python signup.py                  # the Playwright (Python) example
```

## Keep the key secret

-   Read the key from an environment variable (`NOPTCHA_KEY`) or a secret manager. Do not hard-code it, and do not write it into files that are committed: keep it in an ignored `.env` file or the CI’s secrets.
-   Never send a `nop_test_` or `nop_live_` key to a browser: not in front-end JavaScript, not in a browser extension, not in the page you are automating (`page.evaluate` arguments end up in the page). Call the API from the server or the automation script; only the token goes into the page. (The keyless sandbox may be called from a browser; it needs no key.)
-   Prefer a key restricted to the task types you use, with a budget and, if the script runs from fixed addresses, an IP allowlist ([Restrictions](https://noptcha.com/docs/authentication.md#restrictions)).
-   Do not print the key in logs or error messages. If it leaks, revoke it in the console and create a new one.

## Give these rules to your agent

To make an agent follow these rules in a repository, add a short section to its instructions file (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules` or similar):

```md
## NoptCHA (captcha solving)
- Read https://noptcha.com/docs/for-ai-agents.md before changing captcha code.
- Use the v1 API (POST https://api.noptcha.com/v1/tasks, Prefer: wait=60, Idempotency-Key); handle 202 by long-polling.
- Develop and test against the sandbox (NOPTCHA_KEY=keyless or a nop_test_ key); never use a nop_live_ key in tests.
- The key comes from the NOPTCHA_KEY environment variable: never hard-code, commit, log or send it to a browser.
```

> **Using NoptCHA on sites:** Use it on sites you are allowed to automate: your own sites, testing, and data collection that the site permits.
