# WriteHuman API documentation

The WriteHuman API rewrites AI-generated text so that it reads as human-written, scores text for AI authorship, and reports your word balance. It is a JSON REST API at https://api.writehuman.ai with three endpoints and Bearer key authentication.

---

Source: https://writehuman.ai/api/docs

## WriteHuman AI Humanizer API Documentation

The WriteHuman API rewrites AI-generated text so that it reads as human-written, scores text for AI authorship, and reports your word balance. It is a JSON API over HTTPS with Bearer key authentication and three endpoints.

Base URL: `https://api.writehuman.ai`

- [Humanize text](https://writehuman.ai/api/docs/humanize) (`POST /v1/humanize`): Rewrites text and returns one result, or three scored results on Premium plans.
- [Detect AI text](https://writehuman.ai/api/docs/detect) (`POST /v1/detect`): Scores text from 0 to 1 for AI authorship, per document and per sentence.
- [Get usage](https://writehuman.ai/api/docs/usage) (`GET /v1/usage`): Returns your plan, the words used in the current cycle and your top-up balance. Not billed.
- [Errors](https://writehuman.ai/api/docs/errors) (`4xx and 5xx`): The error format, every error `code`, and which errors are safe to retry.

### Quickstart

#### 1. Create an API key

Subscribe to an [API plan](https://writehuman.ai/api#pricing), then create a key on the API Keys tab of the [API dashboard](https://writehuman.ai/api/dashboard). The full key is displayed only once, at creation. Copy it before closing the dialog.

Store the key in an environment variable. All code samples in this documentation read the key from it:

```bash
export WRITEHUMAN_API_KEY="wh_live_..."
```

#### 2. Send a request

Send the text to `/v1/humanize` using cURL, an [official SDK](https://writehuman.ai/api/docs/sdks) (`npm install @writehuman/sdk` or `pip install writehuman`), or any HTTP client.

cURL:

```bash
curl https://api.writehuman.ai/v1/humanize \
  -H "Authorization: Bearer $WRITEHUMAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Artificial intelligence has revolutionized the way we approach content creation and digital communication."
  }'
```

TypeScript:

```typescript
import { WriteHuman } from "@writehuman/sdk";

const wh = new WriteHuman({ apiKey: process.env.WRITEHUMAN_API_KEY! });

const out = await wh.humanize(
  "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
);

console.log(out.results[0]);
console.log(out.words_remaining.total, "words left");
```

Python:

```python
import os
from writehuman import WriteHuman

wh = WriteHuman(os.environ["WRITEHUMAN_API_KEY"])

out = wh.humanize(
    "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
)

print(out["results"][0])
print(out["words_remaining"]["total"], "words left")
```

fetch:

```javascript
const resp = await fetch("https://api.writehuman.ai/v1/humanize", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.WRITEHUMAN_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    text: "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
  }),
});

const out = await resp.json();
if (!resp.ok) throw new Error(`${out.code}: ${out.error}`);

console.log(out.results[0]);
```

requests:

```python
import os
import requests

resp = requests.post(
    "https://api.writehuman.ai/v1/humanize",
    headers={"Authorization": f"Bearer {os.environ['WRITEHUMAN_API_KEY']}"},
    json={
        "text": "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
    },
    timeout=180,
)
out = resp.json()
if not resp.ok:
    raise RuntimeError(f"{out['code']}: {out['error']}")

print(out["results"][0])
```

#### 3. Read the response

The rewritten text is returned in `results`. Standard plans receive one result. Premium plans receive three, ordered best first, each with a score from 0 to 1, where a higher score indicates more human-like text.

Standard plan:

```json
{
  "id": "hum_a1b2c3d4-e5f",
  "created": 1778533901580,
  "results": [
    "AI has changed how we create content and communicate online."
  ],
  "scores": null,
  "input_words": 14,
  "words_remaining": {
    "included": 124986,
    "topup": 0,
    "total": 124986
  },
  "model": "standard"
}
```

Premium plan:

```json
{
  "id": "hum_a1b2c3d4-e5f",
  "created": 1778533901580,
  "results": [
    "Artificial intelligence has changed the game in content creation and communication.",
    "The role of artificial intelligence in transforming content creation and online communication is unprecedented.",
    "The use of artificial intelligence has changed the way we think about content creation and online communication."
  ],
  "scores": [0.82, 0.81, 0.79],
  "input_words": 14,
  "words_remaining": {
    "included": 399986,
    "topup": 0,
    "total": 399986
  },
  "model": "standard"
}
```

`input_words` is the number of words charged for the request, and `words_remaining` is the balance after it. Failed requests are not charged, with [one exception](https://writehuman.ai/api/docs/errors#charges).

### Next steps

- [Humanize reference](https://writehuman.ai/api/docs/humanize): All request fields, response fields and errors for the humanize endpoint.
- [Errors](https://writehuman.ai/api/docs/errors): The error format, all error codes, retry guidance and billing behavior on failure.
- [Plans and limits](https://writehuman.ai/api/docs/limits): Per-plan limits on words per request, requests per minute and API keys.
- [Production best practices](https://writehuman.ai/api/docs/production): Timeouts, retries, long documents, rate limits and balance monitoring.

### Video walkthrough

A seven-minute walkthrough of authentication and setup, followed by three example integrations: a Python script, a Lovable app and Claude.

Video: How to Integrate the WriteHuman AI Humanizer API (https://www.youtube.com/watch?v=AUAI5kWrKIk)

### Using this documentation with an AI assistant

- Each page has a **Copy for LLM** button that copies the page as Markdown. On this page, the button copies every page. The copied Markdown can be pasted into Claude Code, Cursor or another assistant.
- [llms-full.txt](https://writehuman.ai/api/docs/llms-full.txt) contains every page in a single Markdown file, and [llms.txt](https://writehuman.ai/api/docs/llms.txt) is an index of the pages.
- The [OpenAPI document](https://api.writehuman.ai/openapi.json) describes the three endpoints in machine-readable form.

To use WriteHuman from within Claude or another AI assistant without writing code, connect the [MCP server](https://writehuman.ai/mcp).

---

Source: https://writehuman.ai/api/docs/authentication

## Authentication

Every request must include an API key as a Bearer token. Keys are created in the API dashboard and belong to an API account.

```http
Authorization: Bearer wh_live_your_api_key_here
```

A key consists of the prefix `wh_live_` followed by 64 hexadecimal characters. The same key is valid for all three endpoints. Keys have no scopes and no expiry date, and remain valid until revoked.

### Creating and revoking keys

Keys are managed on the API Keys tab of the [API dashboard](https://writehuman.ai/api/dashboard). Creating a key requires an active API plan.

- **The full key is displayed only once**, at creation. Only a hash of the key is stored, so a lost key cannot be recovered and must be replaced with a new one.
- **Name each key** for the environment it is used in, such as "production" or "staging". The dashboard identifies keys by name and by their first 12 characters.
- **An account can have up to 5 active keys**, or 10 on Premium and Enterprise plans, where keys are shared with the [team](https://writehuman.ai/api/docs/teams).
- **Revocation is permanent.** A revoked key cannot be re-enabled. Revocation can take up to 5 minutes to take effect.

#### Rotating a key without downtime

1. Create a second key.
2. Deploy the new key to your application.
3. Confirm that requests succeed with the new key.
4. Revoke the old key.

### Store keys server-side

An API key grants access to the full word balance of the account and must be treated as a secret. Load it from an environment variable or a secrets manager, and do not commit it to source control, write it to logs or include it in client-side code.

```bash
export WRITEHUMAN_API_KEY="wh_live_..."
```

The API does not send CORS headers and cannot be called directly from a browser. For web and mobile applications, route requests through your own backend, which calls the WriteHuman API.

### Authentication errors

| Status | `code` | Cause |
| --- | --- | --- |
| 401 | `missing_api_key` | The `Authorization: Bearer` header is missing or malformed. |
| 401 | `invalid_api_key` | The key is unknown or has been revoked. |
| 402 | `no_subscription` | The key is valid, but the account has no active plan. A plan with a failed payment is treated as inactive until the payment succeeds. |
| 403 | `reverify_required` | The account owner must re-verify their email address. See [Re-verification](https://writehuman.ai/api/docs/authentication#reverify). |
| 429 | `auth_locked_out` | Too many failed authentication attempts. Wait for the number of seconds given in the `Retry-After` header. |

Repeated failed attempts from the same address result in a lockout of up to 15 minutes. The `Retry-After` header of the 429 response gives the remaining lockout time in seconds.

#### Re-verification

WriteHuman may require an account owner to re-verify their email address. While re-verification is pending, all endpoints return 403 `reverify_required` and no words are charged.

1. The account owner signs in at writehuman.ai and follows the link in the verification email.
2. Create a new key in the dashboard. The most recent key created after re-verification began becomes active within approximately one minute.
3. Keys created earlier remain disabled until re-verification ends. Update your application to use the new key.

Do not automatically retry a `reverify_required` response. The error persists until the account owner completes re-verification.

---

Source: https://writehuman.ai/api/docs/sdks

## SDKs

Official client libraries for TypeScript and Python. Each provides one method per endpoint, typed errors, and a retry policy that never resends a request that may have been charged.

| Language | Package | Install | Requirements |
| --- | --- | --- | --- |
| TypeScript and JavaScript | [`@writehuman/sdk`](https://www.npmjs.com/package/@writehuman/sdk) 0.2.0 | `npm install @writehuman/sdk` | Node 18 or later, or any runtime with a global `fetch`. No dependencies. |
| Python | [`writehuman`](https://pypi.org/project/writehuman/) 0.2.0 | `pip install writehuman` | Python 3.9 or later. `AsyncWriteHuman` has the same methods for asyncio. |

> **Note:** Version 0.2.0 of both packages supports all API features except [freezing](https://writehuman.ai/api/docs/freezing). To send `freeze_citations`, call the REST API directly. `<freeze>` tags are part of `text` and are supported by the SDKs.

### Calling the API

Create a single client instance and reuse it. Both clients take the API key as an argument. The samples read it from an environment variable.

TypeScript:

```typescript
import { WriteHuman } from "@writehuman/sdk";

const wh = new WriteHuman({ apiKey: process.env.WRITEHUMAN_API_KEY! });

// Humanize text. All options are optional.
const out = await wh.humanize(text, { tone: "professional", language: "English" });
console.log(out.results[0]);

// Score text for AI authorship.
const scan = await wh.detect(text, { includeSentences: true });
console.log(scan.ai_probability, scan.predicted_class);

// Retrieve usage. This call is not billed.
const usage = await wh.usage();
console.log(usage.topup_balance);
```

Python:

```python
import os
from writehuman import WriteHuman

wh = WriteHuman(os.environ["WRITEHUMAN_API_KEY"])

# Humanize text. All options are optional.
out = wh.humanize(text, tone="professional", language="English")
print(out["results"][0])

# Score text for AI authorship.
scan = wh.detect(text, include_sentences=True)
print(scan["ai_probability"], scan["predicted_class"])

# Retrieve usage. This call is not billed.
usage = wh.usage()
print(usage["topup_balance"])
```

Responses contain the same fields as the REST API: see [humanize](https://writehuman.ai/api/docs/humanize#response), [detect](https://writehuman.ai/api/docs/detect#response) and [usage](https://writehuman.ai/api/docs/usage#response). In TypeScript, responses are typed objects. In Python, responses are dictionaries, and the package exports type definitions for static type checkers.

| Method | TypeScript | Python |
| --- | --- | --- |
| Humanize | `wh.humanize(text, { tone, language, enhanced, timeoutMs })` | `wh.humanize(text, tone=None, language=None, enhanced=False, timeout=None)` |
| Detect | `wh.detect(text, { language, includeSentences, timeoutMs })` | `wh.detect(text, language=None, include_sentences=False, timeout=None)` |
| Usage | `wh.usage({ timeoutMs })` | `wh.usage(timeout=None)` |

#### Async Python

`AsyncWriteHuman` provides the same three methods as coroutines.

```python
import os
from writehuman import AsyncWriteHuman

async with AsyncWriteHuman(os.environ["WRITEHUMAN_API_KEY"]) as wh:
    out = await wh.humanize(text)
```

### Errors

In the official SDKs every failure is a subclass of `WriteHumanError` carrying `code`, `status` and the last `Retry-After` (`retry_after` in Python, `retryAfter` in TypeScript). `InsufficientBalanceError` adds `words_remaining` / `wordsRemaining`, and `PlanRequiredError` adds `upgrade_url` / `upgradeUrl`. A code the installed SDK version does not know becomes `APIError` with `code` preserved. A response that is not the API's JSON, no response within the client timeout, or a failed connection becomes `ProtocolError`, `ClientTimeoutError` or `ConnectionError`, with no `code`.

TypeScript:

```typescript
import { InsufficientBalanceError, RateLimitError } from "@writehuman/sdk";

try {
  await wh.humanize(text);
} catch (e) {
  if (e instanceof InsufficientBalanceError) {
    console.log("out of words:", e.wordsRemaining);
  } else if (e instanceof RateLimitError) {
    console.log("retry in", e.retryAfter, "seconds");
  } else {
    throw e;
  }
}
```

Python:

```python
from writehuman import InsufficientBalanceError, RateLimitError

try:
    wh.humanize(text)
except InsufficientBalanceError as e:
    print("out of words:", e.words_remaining)
except RateLimitError as e:
    print("retry in", e.retry_after, "seconds")
```

The [Errors](https://writehuman.ai/api/docs/errors#codes) page lists the error class for each `code`.

### Retries

A 429, 503 or 504 response that includes the API's error body is retried after the interval given in `Retry-After`, up to a maximum of 2 retries. If `Retry-After` exceeds 60 s, as with an authentication lockout, the SDK does not wait and raises the error immediately, with the interval available as `retry_after` (Python) or `retryAfter` (TypeScript). A humanize or detect request that may have been charged is never resent.

No other failures are retried. On humanize and detect, a client timeout or a dropped connection raises an error immediately, because the request may have completed and been charged. `usage` is read-only and not billed, so it is also retried in these cases.

| Setting | TypeScript | Python | Default |
| --- | --- | --- | --- |
| Retries per request | `maxRetries` | `max_retries` | 2 |
| Maximum `Retry-After` honored | `maxRetryAfterMs` | `max_retry_after` | 60 seconds |
| Wait time when no `Retry-After` is sent | `fallbackRetryAfterMs` | `fallback_retry_after` | 2 seconds |

### Timeouts

A timeout is a deadline for the entire response, not a per-read limit. The defaults are 120 seconds for humanize, 30 for detect and 15 for usage. Timeouts can be set for the client, per operation or per call.

TypeScript:

```typescript
const wh = new WriteHuman({
  apiKey: process.env.WRITEHUMAN_API_KEY!,
  timeoutMs: { humanize: 180_000 },
  maxRetries: 3,
});

// Or for one call:
await wh.detect(text, { timeoutMs: 10_000 });
```

Python:

```python
wh = WriteHuman(
    os.environ["WRITEHUMAN_API_KEY"],
    timeout={"humanize": 180},
    max_retries=3,
)

# Or for one call:
wh.detect(text, timeout=10)
```

The API responds to every humanize request within 170 seconds. With the default 120-second timeout, a slow request can complete, and be charged, after the client has timed out. For long documents, increase the timeout to 180 seconds. See [Production best practices](https://writehuman.ai/api/docs/production#timeouts).

---

Source: https://writehuman.ai/api/docs/humanize

## Humanize text

Rewrites text so that it reads as human-written. Requests are charged by the number of words submitted, and only when the request succeeds.

```http
POST https://api.writehuman.ai/v1/humanize
```

cURL:

```bash
curl https://api.writehuman.ai/v1/humanize \
  -H "Authorization: Bearer $WRITEHUMAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Artificial intelligence has revolutionized the way we approach content creation and digital communication."
  }'
```

TypeScript:

```typescript
import { WriteHuman } from "@writehuman/sdk";

const wh = new WriteHuman({ apiKey: process.env.WRITEHUMAN_API_KEY! });

const out = await wh.humanize(
  "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
);

console.log(out.results[0]);
console.log(out.words_remaining.total, "words left");
```

Python:

```python
import os
from writehuman import WriteHuman

wh = WriteHuman(os.environ["WRITEHUMAN_API_KEY"])

out = wh.humanize(
    "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
)

print(out["results"][0])
print(out["words_remaining"]["total"], "words left")
```

fetch:

```javascript
const resp = await fetch("https://api.writehuman.ai/v1/humanize", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.WRITEHUMAN_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    text: "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
  }),
});

const out = await resp.json();
if (!resp.ok) throw new Error(`${out.code}: ${out.error}`);

console.log(out.results[0]);
```

requests:

```python
import os
import requests

resp = requests.post(
    "https://api.writehuman.ai/v1/humanize",
    headers={"Authorization": f"Bearer {os.environ['WRITEHUMAN_API_KEY']}"},
    json={
        "text": "Artificial intelligence has revolutionized the way we approach content creation and digital communication.",
    },
    timeout=180,
)
out = resp.json()
if not resp.ok:
    raise RuntimeError(f"{out['code']}: {out['error']}")

print(out["results"][0])
```

Standard plan:

```json
{
  "id": "hum_a1b2c3d4-e5f",
  "created": 1778533901580,
  "results": [
    "AI has changed how we create content and communicate online."
  ],
  "scores": null,
  "input_words": 14,
  "words_remaining": {
    "included": 124986,
    "topup": 0,
    "total": 124986
  },
  "model": "standard"
}
```

Premium plan:

```json
{
  "id": "hum_a1b2c3d4-e5f",
  "created": 1778533901580,
  "results": [
    "Artificial intelligence has changed the game in content creation and communication.",
    "The role of artificial intelligence in transforming content creation and online communication is unprecedented.",
    "The use of artificial intelligence has changed the way we think about content creation and online communication."
  ],
  "scores": [0.82, 0.81, 0.79],
  "input_words": 14,
  "words_remaining": {
    "included": 399986,
    "topup": 0,
    "total": 399986
  },
  "model": "standard"
}
```

### Request body

A JSON object. Only `text` is required.

- `text` (string, required): The text to rewrite. 30 to 100,000 characters. The plan also limits the number of words per request: see [Plans and limits](https://writehuman.ai/api/docs/limits).
- `tone` (string, optional): The writing style of the result. One of `professional`, `academic`, `blog`, `casual`, `creative`, `scientific`, `technical`. Values are lowercase and case-sensitive. Omit the field to use the default style. Any other value is ignored without an error.
- `language` (string, optional): The language of `text`, by its English name, such as `Spanish`. The result is returned in the same language. Detected from the text if omitted. See [Tone and language](https://writehuman.ai/api/docs/tone-and-language) for the supported languages.
- `enhanced` (boolean, optional): Uses the enhanced model for this request, at the same per-word rate. Default: false. Premium plans only. Must be a JSON boolean. See [Enhanced model](https://writehuman.ai/api/docs/enhanced-model).
- `freeze_citations` (boolean, optional): Preserves citations, URLs and DOIs exactly as written. Default: false. Applies only to accounts with freezing enabled and is ignored otherwise. See [Freezing text](https://writehuman.ai/api/docs/freezing).

Unrecognized fields are ignored, with three exceptions: `model`, `num_outputs` and `sequence_id` are rejected with 422 `forbidden_param`. The number of results is determined by the plan, and the model by `enhanced`.

### Response

A 200 response indicates that the text was rewritten and the words were charged.

- `id` (string): Identifier of this request, such as `hum_a1b2c3d4-e5f`.
- `created` (integer): When the request arrived, as a Unix timestamp in milliseconds.
- `results` (string[]): The rewritten text. One entry on Standard plans and three on Premium plans, ordered best first.
- `scores` ((number | null)[] | null): On Premium plans, one score per entry of `results`, from 0 to 1, where a higher score indicates more human-like text. `null` on Standard plans. An individual entry is `null` if that result could not be scored. A score equals 1 minus the `ai_probability` that [/v1/detect](https://writehuman.ai/api/docs/detect) returns for the same text, so a separate detect request is unnecessary.
- `input_words` (integer): The number of words charged for this request.
- `words_remaining` (object): The account balance after this request.
  - `included` (integer): Words remaining in the plan allowance for the current cycle.
  - `topup` (integer): Words remaining from top-ups.
  - `total` (integer): The sum of `included` and `topup`.
- `model` (string): `enhanced` when the request set `enhanced: true`, otherwise `standard`.
- `frozen_items` (object[][]): Present only for requests that used [freezing](https://writehuman.ai/api/docs/freezing). One list per entry of `results`, in the same order, containing every frozen item in the order it appeared in the input.
  - `text` (string): The frozen text exactly as submitted, without the tags.
  - `start` (integer | null): The start offset of the item in that result, in Unicode code points. `null` if the item could not be preserved.
  - `end` (integer | null): The end offset of the item, exclusive. `null` if the item could not be preserved.

### Behavior

- **Length and structure.** Results are generated to preserve the paragraph structure of the input and to remain close to it in length.
- **Result order on Premium.** `results[0]` is the result ranked best overall. It usually, but not always, has the highest score. To rank by score alone, sort the results by `scores`.
- **Response time.** Short inputs typically return within a few seconds. Requests near the plan's word limit can take up to a minute. The API always responds within 170 seconds. See [Timeouts](https://writehuman.ai/api/docs/production#timeouts) for recommended client settings.
- **Other languages.** Non-English text takes longer to process than English text of the same length.
- **Blocked content.** Text that fails content moderation is rejected with 422 `moderation_blocked` and is not charged.
- **No idempotency.** The API does not support idempotency keys. Submitting the same text twice results in two rewrites and two charges.

### Errors

Every error response contains a `code` and an `error` message. The [Errors](https://writehuman.ai/api/docs/errors) page describes each code and indicates which errors can be retried.

- **401**: Missing or invalid API key.
  - Invalid API key:
    ```json
    {
      "error": "Invalid API key",
      "code": "invalid_api_key"
    }
    ```
  - Missing Authorization header:
    ```json
    {
      "error": "Missing or invalid Authorization header. Use: Bearer <api_key>",
      "code": "missing_api_key"
    }
    ```
- **402**: No active subscription or insufficient word balance.
  - No active subscription:
    ```json
    {
      "error": "No active subscription",
      "code": "no_subscription"
    }
    ```
  - Insufficient word balance:
    ```json
    {
      "error": "Insufficient word balance",
      "code": "insufficient_balance",
      "words_remaining": {
        "included": 12,
        "topup": 0,
        "total": 12
      }
    }
    ```
- **403**: The request was rejected before processing, and no words were charged. The `code` identifies the reason.
  - `enhanced` on a Standard plan:
    ```json
    {
      "error": "The enhanced parameter requires a Premium plan or above",
      "code": "enhanced_requires_premium",
      "upgrade_url": "https://writehuman.ai/api#pricing"
    }
    ```
  - The enhanced model is switched off:
    ```json
    {
      "error": "The enhanced model is not available right now",
      "code": "enhanced_unavailable"
    }
    ```
  - Account must be re-verified:
    ```json
    {
      "error": "This account must be re-verified by email. The account owner should sign in at writehuman.ai to continue.",
      "code": "reverify_required"
    }
    ```
- **422**: Invalid input, forbidden parameters, malformed `<freeze>` tags, over word limit, or content blocked by moderation.
  - Invalid request body:
    ```json
    {
      "error": "Invalid request: ...",
      "code": "invalid_request"
    }
    ```
  - `model` is not available on the public API:
    ```json
    {
      "error": "The model parameter is not available",
      "code": "forbidden_param"
    }
    ```
  - `num_outputs` is not available on the public API:
    ```json
    {
      "error": "The num_outputs parameter is not available",
      "code": "forbidden_param"
    }
    ```
  - `sequence_id` is not available on the public API:
    ```json
    {
      "error": "The sequence_id parameter is not available",
      "code": "forbidden_param"
    }
    ```
  - Over word limit:
    ```json
    {
      "error": "Input exceeds per-request limit of 2000 words for your plan. Received ~2500 words.",
      "code": "word_limit"
    }
    ```
  - Content blocked:
    ```json
    {
      "error": "Content blocked: sexual",
      "code": "moderation_blocked"
    }
    ```
  - A `<freeze>` tag is never closed:
    ```json
    {
      "error": "A <freeze> tag is never closed. Add the matching </freeze>.",
      "code": "freeze_tag_not_closed"
    }
    ```
  - A `</freeze>` tag has no opening tag:
    ```json
    {
      "error": "A </freeze> tag has no <freeze> before it.",
      "code": "freeze_tag_not_opened"
    }
    ```
  - `<freeze>` tags nest or overlap:
    ```json
    {
      "error": "A <freeze> tag starts inside another one. Tags cannot nest or overlap.",
      "code": "freeze_tags_nested"
    }
    ```
  - A `<freeze>` tag wraps no text:
    ```json
    {
      "error": "A <freeze> tag wraps no text.",
      "code": "freeze_tag_empty"
    }
    ```
  - Almost all of the text is frozen:
    ```json
    {
      "error": "Almost all of the text is frozen, so there is nothing left to humanize.",
      "code": "nothing_to_rewrite"
    }
    ```
- **429**: Rate limit, queue capacity, or too many failed auth attempts.
  - Rate limited:
    ```json
    {
      "error": "Rate limit exceeded for your plan (api_standard -> 40/min). api_standard: 40/min | api_premium: 120/min | api_premium 800K+: 160/min",
      "code": "rate_limited"
    }
    ```
  - Too many failed auth attempts:
    ```json
    {
      "error": "Too many failed authentication attempts",
      "code": "auth_locked_out"
    }
    ```
  - Request queue full:
    ```json
    {
      "error": "Too many queued requests. Please retry shortly.",
      "code": "queue_full"
    }
    ```
  - Queue wait timeout:
    ```json
    {
      "error": "Request waited too long for capacity. Please retry.",
      "code": "queue_timeout"
    }
    ```
- **500**: Processing failure. No words charged, except that `billing_failed` may have charged some of the request's words (included and/or top-up) before the usage write failed.
  - Generation failed:
    ```json
    {
      "error": "Processing failed",
      "code": "processing_failed"
    }
    ```
  - Generation returned nothing usable:
    ```json
    {
      "error": "Processing returned no results",
      "code": "no_results"
    }
    ```
  - Output exceeded the safety limit:
    ```json
    {
      "error": "Output exceeded safety limit",
      "code": "safety_limit"
    }
    ```
  - Billing update failed after generation:
    ```json
    {
      "error": "Billing update failed",
      "code": "billing_failed"
    }
    ```
- **503**: Service at capacity, or billing temporarily unavailable. No words charged.
  - Service at capacity:
    ```json
    {
      "error": "Service is at capacity. Please retry shortly.",
      "code": "at_capacity"
    }
    ```
  - Billing temporarily unavailable:
    ```json
    {
      "error": "Service temporarily unavailable, please retry shortly.",
      "code": "billing_unavailable"
    }
    ```
- **504**: The request did not finish within 170 seconds. No words were charged, and the request is safe to retry.
  - Example:
    ```json
    {
      "error": "Processing did not finish within 160 seconds. Nothing was charged; please retry.",
      "code": "timeout"
    }
    ```

---

Source: https://writehuman.ai/api/docs/detect

## Detect AI text

Scores text for AI authorship using the WriteHuman detector, for the document as a whole and optionally for each sentence. Requests are charged by the number of words submitted, as with humanize.

```http
POST https://api.writehuman.ai/v1/detect
```

cURL:

```bash
curl https://api.writehuman.ai/v1/detect \
  -H "Authorization: Bearer $WRITEHUMAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Artificial intelligence has rapidly transformed modern business. Many teams now depend on it every single day.",
    "include_sentences": true
  }'
```

TypeScript:

```typescript
import { WriteHuman } from "@writehuman/sdk";

const wh = new WriteHuman({ apiKey: process.env.WRITEHUMAN_API_KEY! });

const scan = await wh.detect(
  "Artificial intelligence has rapidly transformed modern business. Many teams now depend on it every single day.",
  { includeSentences: true },
);

console.log(scan.predicted_class, scan.ai_probability);
```

Python:

```python
import os
from writehuman import WriteHuman

wh = WriteHuman(os.environ["WRITEHUMAN_API_KEY"])

scan = wh.detect(
    "Artificial intelligence has rapidly transformed modern business. Many teams now depend on it every single day.",
    include_sentences=True,
)

print(scan["predicted_class"], scan["ai_probability"])
```

fetch:

```javascript
const resp = await fetch("https://api.writehuman.ai/v1/detect", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.WRITEHUMAN_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    text: "Artificial intelligence has rapidly transformed modern business. Many teams now depend on it every single day.",
    include_sentences: true,
  }),
});

const scan = await resp.json();
if (!resp.ok) throw new Error(`${scan.code}: ${scan.error}`);

console.log(scan.predicted_class, scan.ai_probability);
```

requests:

```python
import os
import requests

resp = requests.post(
    "https://api.writehuman.ai/v1/detect",
    headers={"Authorization": f"Bearer {os.environ['WRITEHUMAN_API_KEY']}"},
    json={
        "text": "Artificial intelligence has rapidly transformed modern business. Many teams now depend on it every single day.",
        "include_sentences": True,
    },
    timeout=60,
)
scan = resp.json()
if not resp.ok:
    raise RuntimeError(f"{scan['code']}: {scan['error']}")

print(scan["predicted_class"], scan["ai_probability"])
```

With sentences:

```json
{
  "scanId": "20260609OMIOISUZ",
  "version": "txtdetect-2026-05-14",
  "versionID": "V1.1.1",
  "ai_probability": 0.94,
  "predicted_class": "ai",
  "class_probabilities": { "ai": 0.94, "human": 0.04, "mixed": 0.02 },
  "request_meta": { "doc_length": { "chars": 110, "tokens": 19 } },
  "language": "English",
  "sentences": [
    { "text": "Artificial intelligence has rapidly transformed modern business.", "ai_prob": 0.97 },
    { "text": "Many teams now depend on it every single day.", "ai_prob": 0.61 }
  ]
}
```

> **Warning:** `ai_probability` ranges from 0 to 1, where **1 indicates AI-generated text**. The `scores` returned by [/v1/humanize](https://writehuman.ai/api/docs/humanize) use the inverse scale, where a higher value indicates more human-like text.

### Request body

A JSON object. Only `text` is required.

- `text` (string, required): The text to score. 10 to 100,000 characters, and subject to the same words-per-request limit as humanize.
- `language` (string, optional): The language of `text`, by its English name, such as `Spanish`. Detected from the text if omitted. Non-English text is translated to English before it is scored.
- `include_sentences` (boolean, optional): Also returns a score for each sentence. Default: false.

### Response

A 200 response indicates that the text was scored and the words were charged.

- `scanId` (string | null): Identifier of this scan.
- `version` (string | null): Version of the detection model.
- `versionID` (string | null): Build of the detection model.
- `ai_probability` (number | null): The probability that the text is AI-generated, from 0 to 1, where 1 indicates AI-generated text. This scale is the inverse of `scores` on [/v1/humanize](https://writehuman.ai/api/docs/humanize), where a higher value indicates more human-like text.
- `predicted_class` (string | null): The overall classification: `ai`, `human` or `mixed`.
- `class_probabilities` (object): The probability of each classification.
  - `ai` (number | null): The probability that the text is AI-generated.
  - `human` (number | null): The probability that the text is human-written.
  - `mixed` (number | null): The probability that the text is a mix of both.
- `request_meta` (object): The length of the scored text.
  - `doc_length.chars` (integer | null): Characters scored.
  - `doc_length.tokens` (integer | null): Tokens scored.
- `language` (string): The language specified in the request, or the detected language.
- `sentences` (object[]): Present only when the request set `include_sentences: true`. One entry per sentence, in order.
  - `text` (string | null): The sentence.
  - `ai_prob` (number | null): The probability that the sentence is AI-generated, from 0 to 1.

### Behavior

- **Shared limits.** Detect requests count toward the same words-per-request limit and requests-per-minute limit as humanize requests. See [Plans and limits](https://writehuman.ai/api/docs/limits).
- **Other languages.** Non-English text is translated to English, and the translation is scored. The charge is based on the words submitted. In this case, `sentences` and `request_meta` describe the English translation, not the original text.
- **No content moderation.** Detect is a read-only operation, so content that humanize would block can still be scored.
- **Humanize results are already scored.** On Premium plans, each humanize result includes a score from the same detector. A separate detect request on that result is charged and returns equivalent information.
- **Detector unavailable.** A 503 `detector_unavailable` response is not charged. Wait for the number of seconds given in `Retry-After`, then retry the request.

### Errors

The [Errors](https://writehuman.ai/api/docs/errors) page describes each code and indicates which errors can be retried.

- **401**: Missing or invalid API key.
  - Invalid API key:
    ```json
    {
      "error": "Invalid API key",
      "code": "invalid_api_key"
    }
    ```
  - Missing Authorization header:
    ```json
    {
      "error": "Missing or invalid Authorization header",
      "code": "missing_api_key"
    }
    ```
- **402**: No active subscription or insufficient word balance.
  - No active subscription:
    ```json
    {
      "error": "No active subscription",
      "code": "no_subscription"
    }
    ```
  - Insufficient word balance:
    ```json
    {
      "error": "Insufficient word balance",
      "code": "insufficient_balance",
      "words_remaining": {
        "included": 12,
        "topup": 0,
        "total": 12
      }
    }
    ```
- **403**: The account owner must re-verify the account by email. No words are charged.
  - Example:
    ```json
    {
      "error": "This account must be re-verified by email. The account owner should sign in at writehuman.ai to continue.",
      "code": "reverify_required"
    }
    ```
- **422**: Invalid input or over the per-request word limit.
  - Invalid request body:
    ```json
    {
      "error": "Invalid request: ...",
      "code": "invalid_request"
    }
    ```
  - Over word limit:
    ```json
    {
      "error": "Input exceeds per-request limit of 2000 words for your plan. Received ~2500 words.",
      "code": "word_limit"
    }
    ```
- **429**: Rate limit or too many failed auth attempts.
  - Rate limited:
    ```json
    {
      "error": "Rate limit exceeded for your plan (api_standard -> 40/min). api_standard: 40/min | api_premium: 120/min | api_premium 800K+: 160/min",
      "code": "rate_limited"
    }
    ```
  - Too many failed auth attempts:
    ```json
    {
      "error": "Too many failed authentication attempts",
      "code": "auth_locked_out"
    }
    ```
- **500**: Billing update failure after a successful scan. Some of the request's words (included and/or top-up) may already have been charged before the write failed.
  - Example:
    ```json
    {
      "error": "Billing update failed",
      "code": "billing_failed"
    }
    ```
- **503**: Detector unavailable or at capacity, translation failed, or billing temporarily unavailable. No words charged.
  - Detector unavailable, at capacity, or translation failed:
    ```json
    {
      "error": "Detection service unavailable. Please retry.",
      "code": "detector_unavailable"
    }
    ```
  - Billing temporarily unavailable:
    ```json
    {
      "error": "Service temporarily unavailable, please retry shortly.",
      "code": "billing_unavailable"
    }
    ```

---

Source: https://writehuman.ai/api/docs/usage

## Get usage

Returns your plan, the words used in the current billing cycle and your top-up balance. This endpoint is not billed and does not count toward the rate limit.

```http
GET https://api.writehuman.ai/v1/usage
```

cURL:

```bash
curl https://api.writehuman.ai/v1/usage \
  -H "Authorization: Bearer $WRITEHUMAN_API_KEY"
```

TypeScript:

```typescript
import { WriteHuman } from "@writehuman/sdk";

const wh = new WriteHuman({ apiKey: process.env.WRITEHUMAN_API_KEY! });

const usage = await wh.usage();
const left = usage.included_words - usage.words_used_this_cycle + usage.topup_balance;

console.log(left, "words left");
```

Python:

```python
import os
from writehuman import WriteHuman

wh = WriteHuman(os.environ["WRITEHUMAN_API_KEY"])

usage = wh.usage()
left = usage["included_words"] - usage["words_used_this_cycle"] + usage["topup_balance"]

print(left, "words left")
```

fetch:

```javascript
const resp = await fetch("https://api.writehuman.ai/v1/usage", {
  headers: { "Authorization": `Bearer ${process.env.WRITEHUMAN_API_KEY}` },
});

const usage = await resp.json();
if (!resp.ok) throw new Error(`${usage.code}: ${usage.error}`);
const left = usage.included_words - usage.words_used_this_cycle + usage.topup_balance;

console.log(left, "words left");
```

requests:

```python
import os
import requests

resp = requests.get(
    "https://api.writehuman.ai/v1/usage",
    headers={"Authorization": f"Bearer {os.environ['WRITEHUMAN_API_KEY']}"},
    timeout=30,
)
usage = resp.json()
if not resp.ok:
    raise RuntimeError(f"{usage['code']}: {usage['error']}")
left = usage["included_words"] - usage["words_used_this_cycle"] + usage["topup_balance"]

print(left, "words left")
```

200:

```json
{
  "included_words": 400000,
  "words_used_this_cycle": 18311,
  "topup_balance": 100000,
  "tier": "api_premium",
  "version": "v1.3"
}
```

This endpoint takes no parameters. The account is identified by the API key.

### Response

- `included_words` (integer): The number of words the plan includes per billing cycle.
- `words_used_this_cycle` (integer): Plan words used so far in the current cycle.
- `topup_balance` (integer): Words remaining from top-ups. Top-up words do not expire.
- `tier` (string): The plan tier: `api_standard` or `api_premium`. All Premium sizes report `api_premium`.
- `version` (string): The API version, such as `v1.3`.

### Calculating the remaining balance

```
remaining = included_words - words_used_this_cycle + topup_balance
```

For the example response, the remaining balance is 400,000 - 18,311 + 100,000 = 481,689 words.

- Plan words are consumed before top-up words. `words_used_this_cycle` resets to zero when the plan renews. Top-up words carry over.
- Values returned by this endpoint can lag actual usage by up to two minutes. For the exact balance immediately after a request, use `words_remaining` in the [humanize response](https://writehuman.ai/api/docs/humanize#response-words_remaining).
- Calling this endpoint before each request is unnecessary. A request that exceeds the balance is rejected with 402 `insufficient_balance`, which is not charged and includes the current balance.

### Errors

- **401**: Missing or invalid API key.
  - Invalid API key:
    ```json
    {
      "error": "Invalid API key",
      "code": "invalid_api_key"
    }
    ```
  - Missing Authorization header:
    ```json
    {
      "error": "Missing or invalid Authorization header",
      "code": "missing_api_key"
    }
    ```
- **402**: No active subscription.
  - Example:
    ```json
    {
      "error": "No active subscription",
      "code": "no_subscription"
    }
    ```
- **403**: The account owner must re-verify the account by email.
  - Example:
    ```json
    {
      "error": "This account must be re-verified by email. The account owner should sign in at writehuman.ai to continue.",
      "code": "reverify_required"
    }
    ```
- **429**: Too many failed auth attempts.
  - Example:
    ```json
    {
      "error": "Too many failed authentication attempts",
      "code": "auth_locked_out"
    }
    ```

---

Source: https://writehuman.ai/api/docs/errors

## Errors

Every failed request returns a JSON body with a stable `code`. This page describes the error format, which errors are safe to retry, and when a failed request can still be charged.

### Error format

Every non-2xx response has the following format:

```json
{
  "error": "Insufficient word balance",
  "code": "insufficient_balance",
  "words_remaining": { "included": 12, "topup": 0, "total": 12 }
}
```

- `code` identifies the cause and is stable. Base error handling on this field.
- `error` is a human-readable message. Its wording may change and must not be used for matching.
- Two codes include an additional field: `insufficient_balance` includes `words_remaining`, and `enhanced_requires_premium` includes `upgrade_url`.

A request for a path or method that does not exist returns `{"detail": "Not Found"}` with no `code`.

### Retry behavior

| Status | Retry | Charged |
| --- | --- | --- |
| 401, 402, 403, 422 | No. Correct the request or the account first. | No |
| 429, 503, 504 | Yes, after the interval given in `Retry-After`. | No |
| 500 | Not automatically. The request may have been processed. | Only on `billing_failed` |
| Client timeout or dropped connection | Not automatically. The request may have been processed. | Possibly |

Every 429, 503 and 504 response from the API includes a `Retry-After` header, in whole seconds. The value is typically 2 to 10 seconds for capacity errors, up to 60 seconds for a rate limit, and up to 15 minutes for an authentication lockout.

> **Warning:** A 429, 503 or 504 response **without** the JSON body and `code` was not generated by the API. It was returned by a load balancer or proxy, and the request may still be in progress. Handle it as a client timeout: check [/v1/usage](https://writehuman.ai/api/docs/usage) before resending a billable request.

[Production best practices](https://writehuman.ai/api/docs/production#retries) includes a reference retry implementation.

### Charges on failed requests

Words are charged only on a 200 response, with one exception. A 500 `billing_failed` response indicates that the result was produced but the usage record failed partway, so some of the words for the request may already have been deducted. Call [/v1/usage](https://writehuman.ai/api/docs/usage) to check the balance, and contact support if it is incorrect.

### Order of checks

When a request fails more than one check, the API returns the first failure in the following order:

1. The body is not valid JSON, or a field has the wrong type or length (422 `invalid_request`). This check runs before authentication, so it can be returned even when no key is sent.
2. The key (401), then re-verification (403), then the plan (402 `no_subscription`).
3. Disallowed parameters (422 `forbidden_param`), `enhanced` (403), `<freeze>` tags (422) and the words-per-request limit (422 `word_limit`).
4. The account balance (402 `insufficient_balance`), then the rate limit (429 `rate_limited`).
5. Capacity (429 or 503), then content moderation (422 `moderation_blocked`), then processing.

### Error codes

Each code has its own anchor and can be linked to directly.

#### 401: authentication failed

Correct the `Authorization` header. Retrying the same request returns the same error.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `missing_api_key` | 401 | No usable `Authorization: Bearer` header. | `AuthenticationError` |
| `invalid_api_key` | 401 | The key is unknown or revoked. | `AuthenticationError` |

#### 402: no plan or insufficient balance

No words are charged. The request succeeds once the account has an active plan and a sufficient balance.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `no_subscription` | 402 | The key is valid but the account has no active API subscription. | `NoSubscriptionError` |
| `insufficient_balance` | 402 | Not enough words left for this request; `words_remaining` is included. | `InsufficientBalanceError` |

#### 403: request not permitted

The request is rejected before processing, and no words are charged. Do not retry automatically.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `enhanced_requires_premium` | 403 | `enhanced: true` was sent on a Standard plan. `upgrade_url` links to the plans. Nothing charged. | `PlanRequiredError` |
| `enhanced_unavailable` | 403 | `enhanced: true` was sent while the enhanced model is switched off. Send the request without `enhanced`. Nothing charged. | `FeatureUnavailableError` |
| `reverify_required` | 403 | The account must be re-verified by email. The account owner signs in at writehuman.ai to continue; then the account's newest key created after the check began works within about a minute; every other key stays disabled until the check ends, so create a new key. | `ReverifyRequiredError` |

#### 422: invalid request

No words are charged. Correct the request before resending it.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `invalid_request` | 422 | The body failed validation (missing `text`, too short or too long). | `InvalidRequestError` |
| `forbidden_param` | 422 | A parameter that is not available on the public API was sent. | `InvalidRequestError` |
| `word_limit` | 422 | The input is over the per-request word cap for your plan. | `InvalidRequestError` |
| `moderation_blocked` | 422 | Content moderation refused the input (`/v1/humanize` only). | `ModerationError` |
| `freeze_tag_not_closed` | 422 | The `<freeze>` tags in `text` are malformed (accounts with freezing only; see `/v1/humanize`). Nothing charged. | `APIError` |
| `freeze_tag_not_opened` | 422 | The `<freeze>` tags in `text` are malformed (accounts with freezing only; see `/v1/humanize`). Nothing charged. | `APIError` |
| `freeze_tags_nested` | 422 | The `<freeze>` tags in `text` are malformed (accounts with freezing only; see `/v1/humanize`). Nothing charged. | `APIError` |
| `freeze_tag_empty` | 422 | The `<freeze>` tags in `text` are malformed (accounts with freezing only; see `/v1/humanize`). Nothing charged. | `APIError` |
| `nothing_to_rewrite` | 422 | Almost all of the text is frozen, so there is nothing left to humanize (accounts with freezing only). Nothing charged. | `APIError` |

#### 429: rate limited

No words are charged. Wait for the number of seconds given in `Retry-After`, then resend the same request.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `rate_limited` | 429 | Over your plan's requests per minute. `Retry-After` is the time to the next window. | `RateLimitError` |
| `auth_locked_out` | 429 | Too many failed authentications from this address. `Retry-After` is the remaining lockout. | `RateLimitError` |
| `queue_full` | 429 | The admission queue is full. Retry after `Retry-After`. | `RateLimitError` |
| `queue_timeout` | 429 | The request waited in the admission queue past its deadline. Retry after `Retry-After`. | `RateLimitError` |

#### 500: server error

The SDKs do not retry these errors, because the request may have been processed. Only `billing_failed` can result in a charge.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `processing_failed` | 500 | Generation raised an error. | `ProcessingError` |
| `no_results` | 500 | Generation finished without a usable result. | `ProcessingError` |
| `safety_limit` | 500 | Generation produced far more text than the input; discarded. | `ProcessingError` |
| `billing_failed` | 500 | The result was produced but the usage write failed part-way; included and/or top-up words may already have been charged. Check `/v1/usage`. | `BillingError` |

#### 503 and 504: temporarily unavailable

No words are charged. Wait for the number of seconds given in `Retry-After`, then resend the same request.

| `code` | Status | Meaning | SDK error |
| --- | --- | --- | --- |
| `at_capacity` | 503 | Cluster-wide capacity shed. Retry after `Retry-After`. | `ServiceUnavailableError` |
| `billing_unavailable` | 503 | The billing store is unreachable; the request was refused rather than served unmetered. Retry after `Retry-After`. | `ServiceUnavailableError` |
| `detector_unavailable` | 503 | The detector, or the translation step before it, is unavailable (`/v1/detect` only). Retry after `Retry-After`. | `ServiceUnavailableError` |
| `timeout` | 504 | Generation did not finish within the server deadline (`/v1/humanize` only). Nothing charged; retry after `Retry-After`. | `ServerTimeoutError` |

### Errors in the SDKs

In the official SDKs every failure is a subclass of `WriteHumanError` carrying `code`, `status` and the last `Retry-After` (`retry_after` in Python, `retryAfter` in TypeScript). `InsufficientBalanceError` adds `words_remaining` / `wordsRemaining`, and `PlanRequiredError` adds `upgrade_url` / `upgradeUrl`. A code the installed SDK version does not know becomes `APIError` with `code` preserved. A response that is not the API's JSON, no response within the client timeout, or a failed connection becomes `ProtocolError`, `ClientTimeoutError` or `ConnectionError`, with no `code`.

See [SDKs](https://writehuman.ai/api/docs/sdks#errors) for an example.

---

Source: https://writehuman.ai/api/docs/tone-and-language

## Tone and language

Two optional fields control a humanize request: `tone` sets the writing style of the result, and `language` specifies the language of the text.

### Tone

`tone` accepts one of 7 values: `professional`, `academic`, `blog`, `casual`, `creative`, `scientific`, `technical`. Omit `tone` to use the default style.

```bash
curl https://api.writehuman.ai/v1/humanize \
  -H "Authorization: Bearer $WRITEHUMAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "The company reported strong quarterly earnings driven by increased demand.",
    "tone": "professional"
  }'
```

> **Note:** An unrecognized `tone` value is ignored, not rejected, and matching is case-sensitive. For example, `"Professional"` with an uppercase P results in the default style and no error. If a tone has no effect, verify the spelling and case of the value.

### Language

`language` specifies the language of the input text, by its English name: `"language": "Spanish"`. The result is returned in the same language.

- If `language` is omitted, the language is detected from the text. If the language is known, specify it explicitly.
- An unrecognized language name is treated as if the field were omitted.
- The language also determines how words are counted for billing. See [Words and billing](https://writehuman.ai/api/docs/billing#counting).
- On [/v1/detect](https://writehuman.ai/api/docs/detect), text in any language other than English is translated to English before it is scored.

#### Supported languages

The API supports 44 languages: `English`, `Chinese (Mandarin)`, `Chinese (Taiwan)`, `French`, `Spanish`, `Vietnamese`, `Portuguese`, `Japanese`, `Ukrainian`, `Swedish`, `German`, `Russian`, `Italian`, `Arabic`, `Hindi`, `Bengali`, `Korean`, `Turkish`, `Dutch`, `Polish`, `Thai`, `Indonesian`, `Malay`, `Persian`, `Hebrew`, `Greek`, `Czech`, `Danish`, `Finnish`, `Norwegian`, `Romanian`, `Hungarian`, `Slovak`, `Bulgarian`, `Croatian`, `Serbian`, `Slovenian`, `Lithuanian`, `Latvian`, `Estonian`, `Urdu`, `Swahili`, `Tagalog`, `Afrikaans`.

[Freezing](https://writehuman.ai/api/docs/freezing) is supported for English text only.

---

Source: https://writehuman.ai/api/docs/enhanced-model

## Enhanced model

Premium plans can select the enhanced model for any humanize request. The enhanced model applies a more extensive rewrite, intended for the strictest AI detectors, at the same per-word rate.

### Usage

Set `enhanced: true` in the request. No other changes are required.

cURL:

```bash
curl https://api.writehuman.ai/v1/humanize \
  -H "Authorization: Bearer $WRITEHUMAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "The company reported strong quarterly earnings driven by increased demand.",
    "enhanced": true
  }'
```

TypeScript:

```typescript
const out = await wh.humanize(text, { enhanced: true });
console.log(out.model); // "enhanced"
```

Python:

```python
out = wh.humanize(text, enhanced=True)
print(out["model"])  # "enhanced"
```

The `model` field of the response is `enhanced` for these requests and `standard` for all others. `enhanced` must be a JSON boolean. The string `"true"` is rejected with a 422.

### Choosing a model

Standard is the default and the flagship model. The enhanced model rewrites text more extensively. Both are charged at the same per-word rate. To choose between them, process representative samples of your own text with each model and compare the results and their `scores`.

### Errors

| Status | `code` | Cause | Resolution |
| --- | --- | --- | --- |
| 403 | `enhanced_requires_premium` | The account is on a Standard plan. | Upgrade at the `upgrade_url` in the response, or send the request without `enhanced`. |
| 403 | `enhanced_unavailable` | The enhanced model is temporarily disabled for all accounts. | Send the request without `enhanced`. |

Neither response is charged. Because neither condition resolves on its own, do not retry the request unchanged. To continue processing while the enhanced model is disabled, fall back to the standard model:

TypeScript:

```typescript
import { FeatureUnavailableError } from "@writehuman/sdk";

async function humanize(text: string) {
  try {
    return await wh.humanize(text, { enhanced: true });
  } catch (e) {
    if (e instanceof FeatureUnavailableError) return wh.humanize(text);
    throw e;
  }
}
```

Python:

```python
from writehuman import FeatureUnavailableError

def humanize(text):
    try:
        return wh.humanize(text, enhanced=True)
    except FeatureUnavailableError:
        return wh.humanize(text)
```

---

Source: https://writehuman.ai/api/docs/freezing

## Freezing text

Freezing preserves selected parts of the text exactly as written while the surrounding text is rewritten. Use it for quotations, names, figures and citations.

> **Warning:** Freezing is enabled per account and is supported for English text. Contact support to request it. On accounts without freezing, `freeze_citations` is ignored and `<freeze>` tags are treated as ordinary characters in the text. Confirm that responses contain `frozen_items` before relying on this feature.

### Freeze a passage

Enclose the passage in `<freeze>` and `</freeze>` tags within `text`.

```json
{
  "text": "Our study found a clear effect. <freeze>Results may vary by role.</freeze> Managers should weigh these findings carefully."
}
```

- Tags are removed before any other processing. They are not returned, not counted toward the word limit and not charged.
- Tags cannot be nested and cannot overlap.
- A tagged passage that spans multiple lines is preserved line by line, so line breaks are retained. Each line is a separate entry in `frozen_items`.

### Freeze citations

When `freeze_citations` is `true`, the API detects and preserves the following:

- Numbered references such as `[1]`, `[1, 3]` and `[2–4]`.
- Bracketed citation keys such as `[ref_3]` and `[Smith2020]`.
- Author-year references such as `(Smith et al., 2020)`, including page numbers and multiple sources within one set of parentheses.
- URLs and DOIs.

A reference list at the end of the text is also preserved as written. It is preserved as a single block and is not listed in `frozen_items`. `freeze_citations` can be combined with `<freeze>` tags in the same request.

### Example

The following request freezes one citation with `freeze_citations` and one sentence with `<freeze>` tags:

Request body:

```json
{
  "text": "Remote work raised reported productivity by 13% in one large trial (Bloom et al., 2015). <freeze>Results may vary by role.</freeze> Managers should weigh these findings carefully.",
  "freeze_citations": true
}
```

Both items preserved:

```json
{
  "id": "hum_a1b2c3d4-e5f",
  "created": 1778533901580,
  "results": [
    "In one large trial, remote work lifted reported productivity by 13% (Bloom et al., 2015). Results may vary by role. Managers would do well to think these findings through."
  ],
  "scores": null,
  "input_words": 26,
  "words_remaining": {
    "included": 124974,
    "topup": 0,
    "total": 124974
  },
  "model": "standard",
  "frozen_items": [
    [
      { "text": "(Bloom et al., 2015)", "start": 68, "end": 88 },
      { "text": "Results may vary by role.", "start": 90, "end": 115 }
    ]
  ]
}
```

One item not preserved:

```json
{
  "id": "hum_a1b2c3d4-e5f",
  "created": 1778533901580,
  "results": [
    "One large trial found remote work raised reported productivity by 13% (Bloom et al., 2015). Results can differ by role. Managers should weigh this carefully."
  ],
  "scores": null,
  "input_words": 26,
  "words_remaining": {
    "included": 124974,
    "topup": 0,
    "total": 124974
  },
  "model": "standard",
  "frozen_items": [
    [
      { "text": "(Bloom et al., 2015)", "start": 70, "end": 90 },
      { "text": "Results may vary by role.", "start": null, "end": null }
    ]
  ]
}
```

### Reading `frozen_items`

`frozen_items` contains one list for each entry of `results`, in the same order. Each list contains every frozen item in the order it appeared in the input, with its position in that result.

- `start` and `end` are offsets in Unicode code points, and `end` is exclusive. In Python, `result[start:end]` returns the item. JavaScript strings are indexed in UTF-16 code units, so use `Array.from(result).slice(start, end).join("")`.
- Frozen text is preserved in nearly all cases. If an item could not be preserved in a result, its `start` and `end` are `null`, and that part of the result was rewritten with the rest of the text.
- If `freeze_citations` is `true` and the text contains no citations, `frozen_items` is still present and contains empty lists.

If every frozen item must be preserved, check for `null` before using a result:

JavaScript:

```javascript
const allKept = out.frozen_items[0].every((item) => item.start !== null);
if (!allKept) {
  // On Premium, check out.results[1] against out.frozen_items[1], or resend the request.
}
```

Python:

```python
all_kept = all(item["start"] is not None for item in out["frozen_items"][0])
if not all_kept:
    # On Premium, check out["results"][1] against out["frozen_items"][1], or resend the request.
    ...
```

### Errors

The following errors are returned with status 422. None is charged.

| `code` | Cause |
| --- | --- |
| `freeze_tag_not_closed` | A `<freeze>` has no `</freeze>` after it. |
| `freeze_tag_not_opened` | A `</freeze>` has no `<freeze>` before it. |
| `freeze_tags_nested` | One tag starts inside another, or two tags overlap. |
| `freeze_tag_empty` | A pair of tags encloses only whitespace. |
| `nothing_to_rewrite` | Fewer than 5 words remain outside the frozen parts, leaving nothing to rewrite. |

### Limits

- **English only.** Text in another language is still rewritten and the tags are still removed, but frozen items are unlikely to be preserved.
- **SDKs.** `<freeze>` tags are supported by the [SDKs](https://writehuman.ai/api/docs/sdks), because they are part of `text`. The published SDK versions do not accept `freeze_citations`. Send that field through the REST API.

---

Source: https://writehuman.ai/api/docs/production

## Production best practices

Recommended configuration before sending production traffic: timeouts, retries, long documents, rate limits and balance monitoring.

### Timeouts

The response time of a humanize request increases with the length of the text. The API always responds within 170 seconds, either with a result or with a 504 `timeout` error, which is not charged.

| Words submitted | Typical | 99th percentile |
| --- | --- | --- |
| Under 250 | 3 seconds | 13 seconds |
| 250 to 1,000 | 6 to 7 seconds | 20 to 35 seconds |
| 1,000 to 2,000 | 9 seconds | 40 seconds |
| 2,000 to 4,000 | 12 seconds | 55 seconds |

These figures are measured response times for English text on the standard model. Other languages take longer. Detect requests typically complete in under one second.

- **Set a client timeout of 180 seconds for humanize**, 60 seconds for detect and 30 seconds for usage. With a shorter humanize timeout, a request that the client has abandoned can still complete and be charged. The SDK defaults are 120, 30 and 15 seconds and are [configurable](https://writehuman.ai/api/docs/sdks#timeouts).
- **Check platform limits.** Serverless functions and proxies commonly terminate requests after 10 to 60 seconds. If your platform enforces such a limit, submit shorter text per request or make the call from a background job.

### Retries

The API indicates when a retry is safe. A 429, 503 or 504 response with a JSON `code` was not charged, and its `Retry-After` header gives the number of seconds to wait. All other failures require a change to the request or the account and should not be retried automatically. The SDKs [implement this policy](https://writehuman.ai/api/docs/sdks#retries).

JavaScript:

```javascript
async function humanize(text, attempt = 0) {
  const resp = await fetch("https://api.writehuman.ai/v1/humanize", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.WRITEHUMAN_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ text }),
    signal: AbortSignal.timeout(180_000),
  });

  const body = await resp.json().catch(() => null);
  if (resp.ok) return body;

  // Safe to retry: the API rejected the request, charged nothing, and specified a wait time.
  const wait = Number(resp.headers.get("Retry-After"));
  const retryable = [429, 503, 504].includes(resp.status) && body?.code;
  if (retryable && attempt < 2 && wait <= 60) {
    await new Promise((r) => setTimeout(r, wait * 1000));
    return humanize(text, attempt + 1);
  }

  throw new Error(`${resp.status} ${body?.code ?? "no_code"}: ${body?.error ?? ""}`);
}
```

Python:

```python
import os
import time
import requests

def humanize(text, attempt=0):
    resp = requests.post(
        "https://api.writehuman.ai/v1/humanize",
        headers={"Authorization": f"Bearer {os.environ['WRITEHUMAN_API_KEY']}"},
        json={"text": text},
        timeout=180,
    )
    try:
        body = resp.json()
    except ValueError:
        body = {}
    if resp.ok:
        return body

    # Safe to retry: the API rejected the request, charged nothing, and specified a wait time.
    wait = int(resp.headers.get("Retry-After", 0))
    retryable = resp.status_code in (429, 503, 504) and "code" in body
    if retryable and attempt < 2 and wait <= 60:
        time.sleep(wait)
        return humanize(text, attempt + 1)

    raise RuntimeError(f"{resp.status_code} {body.get('code', 'no_code')}: {body.get('error', '')}")
```

> **Warning:** Do not automatically resend a humanize or detect request after a client timeout or a dropped connection. The API does not support idempotency keys, so if the first request completed, the resent request is charged again. To determine whether the first request was charged, call [/v1/usage](https://writehuman.ai/api/docs/usage) after approximately two minutes.

### Long documents

A request that exceeds the plan's [words-per-request limit](https://writehuman.ai/api/docs/limits#words-per-request) is rejected with 422 `word_limit`. The API does not split text automatically. Split long documents on the client side as follows:

- Split at paragraph boundaries, not within a sentence. Each segment is rewritten independently.
- Keep each segment below approximately 90% of the limit. The API word count can differ from a whitespace-based count, particularly for some languages.
- Send the segments sequentially, or in parallel within the requests-per-minute limit, and join the results using the original paragraph breaks.

JavaScript:

```javascript
// Groups paragraphs into segments of at most maxWords words.
function splitText(text, maxWords = 1800) {
  const pieces = [];
  let current = [];
  let count = 0;
  for (const paragraph of text.split(/\n\s*\n/)) {
    const words = paragraph.trim().split(/\s+/).length;
    if (count + words > maxWords && current.length) {
      pieces.push(current.join("\n\n"));
      current = [];
      count = 0;
    }
    current.push(paragraph);
    count += words;
  }
  if (current.length) pieces.push(current.join("\n\n"));
  return pieces;
}
```

Python:

```python
import re

def split_text(text, max_words=1800):
    """Groups paragraphs into segments of at most max_words words."""
    pieces, current, count = [], [], 0
    for paragraph in re.split(r"\n\s*\n", text):
        words = len(paragraph.split())
        if count + words > max_words and current:
            pieces.append("\n\n".join(current))
            current, count = [], 0
        current.append(paragraph)
        count += words
    if current:
        pieces.append("\n\n".join(current))
    return pieces
```

The example uses 1,800 words, which is appropriate for the Standard limit of 2,000. A single paragraph that exceeds the limit must be split further, at sentence boundaries.

### Rate limits

- The limit applies per account, not per key. It is shared by all keys and all teammates, and humanize and detect requests count toward the same limit.
- The limit resets at the start of each clock minute. A 429 `rate_limited` response includes a `Retry-After` value of 1 to 60 seconds, which is the time remaining until the next minute.
- Successful responses do not include rate-limit headers. To remain under the limit without relying on 429 responses, track the request count on the client side.
- There is no limit on concurrent requests. Under high load, a request can be queued briefly, and some requests return 429 `queue_full`, 429 `queue_timeout` or 503 `at_capacity`. These responses are not charged and are safe to retry.

### Balance monitoring

- Every humanize response includes `words_remaining`. Track `words_remaining.total` in your monitoring.
- A request that exceeds the balance is rejected with 402 `insufficient_balance`. The response is not charged and includes the current balance, which can be used to notify the user or to queue the request.
- WriteHuman emails the account owner when 20% of the monthly words remain, and again when the balance is exhausted.
- On Premium plans, [auto top-up](https://writehuman.ai/api/docs/billing#auto-top-up) can be enabled to purchase additional words automatically when the balance falls below a configured threshold.

### Checklist

- The API key is loaded from an environment variable or a secrets manager and is never exposed to a browser.
- Production and staging use separate keys, so each can be revoked independently.
- The humanize client timeout is 180 seconds, or the platform timeout is known and request size is limited accordingly.
- Only 429, 503 and 504 responses that include a `code` are retried, after the `Retry-After` interval.
- Text that exceeds the words-per-request limit is split at paragraph boundaries before submission.
- 402 `insufficient_balance` responses are handled, and the low-balance emails reach a monitored address.
- Error handling is based on `code`, not on the text of `error`.

---

Source: https://writehuman.ai/api/docs/limits

## Plans and limits

Per-plan limits: words per month, words per request, requests per minute, results per request and API keys.

|  | Standard | Premium 400K | Premium 800K, 1.5M and 3M |
| --- | --- | --- | --- |
| Words per month | 125,000 | 400,000 | 800,000 to 3,000,000 |
| Words per request | 2,000 | 4,000 | 6,000 |
| Requests per minute | 40 | 120 | 160 |
| Results per humanize request | 1 | 3 | 3 |
| Scores on results | No | Yes | Yes |
| [Enhanced model](https://writehuman.ai/api/docs/enhanced-model) | No | Yes | Yes |
| Active API keys | 5 | 10 | 10 |
| [Teammates](https://writehuman.ai/api/docs/teams) | None | Up to 10 | Up to 10 |

Prices are listed on the [pricing page](https://writehuman.ai/api#pricing). For more than 3,000,000 words per month or higher limits, contact support about an Enterprise plan.

### Words per request

- The limit applies to `text` on both [/v1/humanize](https://writehuman.ai/api/docs/humanize) and [/v1/detect](https://writehuman.ai/api/docs/detect). Words are counted in the same way as for [billing](https://writehuman.ai/api/docs/billing#counting).
- A request that exceeds the limit is rejected with 422 `word_limit` and is not charged. The error message states the number of words counted.
- Independently of the word limit, `text` cannot exceed 100,000 characters. On most plans, the word limit is reached first.
- To process a longer document, [split it at paragraph boundaries](https://writehuman.ai/api/docs/production#long-text).

### Requests per minute

- The limit applies per account and is shared by all keys and all teammates.
- Humanize and detect requests count toward the same limit. [/v1/usage](https://writehuman.ai/api/docs/usage) requests do not count.
- Requests rejected for an invalid key, a missing plan, an invalid body or an insufficient balance do not count.
- The count resets at the start of each clock minute. Requests over the limit return 429 `rate_limited` with a `Retry-After` header giving the seconds remaining until the next minute.
- There is no limit on concurrent requests. Successful responses do not include rate-limit headers.

### API keys

An account can have up to 5 active keys. On Premium and Enterprise plans, the limit is 10, shared between the owner and their [teammates](https://writehuman.ai/api/docs/teams). Revoked keys do not count toward the limit. See [Authentication](https://writehuman.ai/api/docs/authentication#keys).

### Plan changes

New limits take effect within approximately two minutes of an upgrade or downgrade. If the plan ends or a payment fails, requests return 402 `no_subscription` until the plan is active again.

---

Source: https://writehuman.ai/api/docs/billing

## Words and billing

The API is billed by word count. Requests are charged for the words submitted, and only when the request succeeds. Plan words are consumed first, followed by top-up words.

### Request cost

| Request | Cost |
| --- | --- |
| [`POST /v1/humanize`](https://writehuman.ai/api/docs/humanize) | The number of words in `text`. The charge is the same regardless of the number of results returned and of whether the [enhanced model](https://writehuman.ai/api/docs/enhanced-model) is used. |
| [`POST /v1/detect`](https://writehuman.ai/api/docs/detect) | The number of words in `text`. |
| [`GET /v1/usage`](https://writehuman.ai/api/docs/usage) | Not billed. |

Words are charged only on a 200 response. Errors, timeouts reported by the API and blocked content are not charged. The only exception is [500 `billing_failed`](https://writehuman.ai/api/docs/errors#charges).

### How words are counted

- Text is split on whitespace, and each resulting token counts as one word.
- For languages written without spaces between words, such as Chinese, Japanese, Korean and Thai, the count is estimated from the number of characters.
- The applicable rule is determined by the value of `language`, or by the detected language if `language` is omitted.
- On accounts with [freezing](https://writehuman.ai/api/docs/freezing) enabled, `<freeze>` tags are removed before counting.

The count does not need to be reproduced on the client side. `input_words` in every humanize response is the exact number of words charged, and the same count is used for the [words-per-request limit](https://writehuman.ai/api/docs/limits#words-per-request).

### Plan words and top-ups

- Each plan includes a fixed number of words per billing cycle. The allowance resets when the plan renews, and unused plan words do not carry over.
- Each top-up pack adds 100,000 words. Top-ups are purchased on the Billing tab of the [API dashboard](https://writehuman.ai/api/dashboard) and require an active plan.
- Top-up words do not expire and carry over between cycles. They are consumed only after the plan words for the cycle are exhausted.
- A top-up balance can hold up to 1,000,000 words.
- A top-up takes effect immediately and is available to the next request.

#### Auto top-up

On Premium plans, the account owner can enable auto top-up on the Billing tab. When the remaining balance falls below a configured threshold, the configured number of packs is purchased automatically, up to a configured spending limit per 30 days. Auto top-up is disabled by default.

### Checking the balance

- **In a response.** `words_remaining` in every humanize response is the balance after that request.
- **Through the API.** [/v1/usage](https://writehuman.ai/api/docs/usage) returns the plan allowance, the words used in the current cycle and the top-up balance. These values can lag by up to two minutes.
- **In the dashboard.** The Overview tab shows the remaining words, the days until the next reset, daily activity and a log of recent requests.

### Insufficient balance

- A request that exceeds the balance is rejected with 402 `insufficient_balance`. No words are charged, and the response includes `words_remaining`.
- WriteHuman emails the account owner when 20% of the monthly words remain, and again when the balance is exhausted or a request is rejected for insufficient balance. Each email is sent once per cycle.
- To continue, purchase a top-up, enable auto top-up, or upgrade to a larger plan.

---

Source: https://writehuman.ai/api/docs/teams

## Teams

On Premium and Enterprise plans, teammates sign in with their own WriteHuman accounts and work on the same API account, without sharing a password. Teammates are included at no additional cost.

### Owner and teammates

|  | Owner | Teammate |
| --- | --- | --- |
| View keys, usage, the request log and the word balance | Yes | Yes |
| Create keys | Yes | Yes |
| Rename or revoke a key | Any key | Keys they created |
| Change the plan, manage billing, buy top-ups | Yes | No |
| Invite or remove teammates | Yes | No |

Team access applies to the API dashboard only. It does not give a teammate access to the web humanizer, the browser extension or the mobile app through the owner account.

### Inviting a teammate

1. The owner opens the Team tab of the [API dashboard](https://writehuman.ai/api/dashboard) and enters the email address of the person to invite.
2. The invitee receives an email containing a link that is valid for 7 days.
3. The invitee signs in, or signs up, with the same email address, verifies it, and selects Join.

An account can have up to 10 teammates, including pending invitations. An expired invitation no longer counts toward the limit.

### Keys and usage

- Keys belong to the account, not to an individual. A key behaves identically regardless of who created it, and all requests draw on the same word balance and the same [rate limit](https://writehuman.ai/api/docs/limits#rate-limit).
- Each key records its creator, and the dashboard shows the number of words used in the current cycle by the keys of each person.
- An account with team access can have up to 10 active keys in total, shared by the owner and all teammates.

### Removing a teammate

The owner removes a teammate on the Team tab and selects which of the keys created by that person to revoke. All of those keys are selected by default, because the removed person has had access to them. A revoked key stops working within 5 minutes. A teammate can also leave a team voluntarily.

Keys that are not revoked remain active, so removing a teammate does not interrupt a running integration unless its key is revoked.

### Plan changes

- If the account is downgraded to Standard or the plan ends, teammates lose access to the dashboard until the account returns to Premium. No teammates are removed, and the team is restored unchanged.
- Existing keys remain active while a plan is active, and the owner can still revoke any key.
- A user can belong to more than one account and can also hold a plan of their own. The dashboard provides an account switcher.
