# Mask personal data

Source: [Mask personal data](<https://docs.gptunnel.ru/en/api/pii-obfuscation/>)

<a id="_top"></a>
> **Note: Authentication**
>
> Set your [API key](<https://docs.gptunnel.ru/en/#get-an-api-key>) in the `GPTUNNEL_API_KEY` environment variable.

<a id="how-it-works"></a>
## How it works

Set `obfuscate: true` in your [Chat Completions request](<https://docs.gptunnel.ru/en/api/chat-completions/>). GPTunneL detects personal data in the text parts of messages and replaces it with placeholders. Within one request, repeated values share a placeholder.

GPTunneL restores the original values in response text, SSE events, and tool-call arguments. For example, if you ask the model to repeat the sample ID `DOCREF-27183` and provide a rule for it, the client receives `DOCREF-27183` in `choices[0].message.content`.

If you need the masked text and a map of placeholders to their original values, use the [standalone text masking endpoint](<https://docs.gptunnel.ru/en/api/obfuscate/>).

<a id="placeholder-format"></a>
### Placeholder format

A placeholder has a type and a number, such as `<<PHONE1>>`. The type identifies the category. The number is unique across types within the request. After `<<PER0>>`, the next placeholder is `<<PHONE1>>`.

| Type | Masked values |
| --- | --- |
| `PER` | Personal names |
| `ORG` | Organizations |
| `LOC` | Addresses and locations |
| `PHONE` | Phone numbers |
| `EMAIL` | Email addresses |
| `CARD` | Bank card numbers |
| `ID` | Other identifiers, such as documents, accounts, tokens, passwords, and IP addresses |
| `MSC` | Other data, such as dates of birth and confirmation codes |
| Your label | Values matched by your `obfuscate_patterns` |

> **Caution: Placeholder types can change**
>
> The list of types may grow, and custom labels may contain underscores. Support those labels in your processing. GPTunneL restores the original values for Chat Completions.

> **Caution: Placeholders without brackets in tool-call arguments**
>
> A model can omit the brackets around a placeholder in a tool call, as in `"body": "Здравствуйте, PER0!"`. GPTunneL restores a standalone token in tool-call arguments if the same placeholder was issued in that request. This can also replace a literal token such as `ID1`, `DATE2`, or `ORG3` in SQL or a product code. Placeholders in the response’s `content` field need their brackets for restoration.

> **Caution: When masking is unavailable**
>
> If the masking service is temporarily unavailable, the API returns `503`. Retry later with the same masking settings.

<a id="what-is-recognized"></a>
## What is recognized

The detector combines rules and checksum validation (Luhn for cards, INN and SNILS check digits, mod-97 for IBAN) with two machine learning models for named entities. Russian is the primary language. The detector recognizes Russian names across grammatical cases, including lowercase forms.

| Category | Examples |
| --- | --- |
| Names | Full names in different grammatical cases and letter cases, names with initials, and informal names |
| Organizations | Names of companies, banks, institutions and acronyms |
| Addresses and locations | Cities, street names and house numbers, full addresses, apartment numbers, and postal codes |
| Russian documents | Passport details in multiple formats, 10- or 12-digit INNs, SNILS, OGRN, OGRNIP, KPP, cadastral numbers, compulsory medical insurance policy numbers, issuing department codes, birth certificates, and driver’s licenses |
| Financial data | Card numbers of 13–19 digits validated with the Luhn algorithm, expiry dates and CVVs next to a card number, bank account numbers, IBANs, and BTC, ETH, or LTC wallet addresses |
| Contact details | Russian and international phone numbers, email addresses, @handles, and URLs |
| Secrets | Passwords, including in logs and stack traces, API keys for Stripe, OpenAI, Anthropic, GitHub, Google, Slack, and AWS, JWTs, bearer tokens, and IP addresses |
| Dates | Date of birth in numerical and verbal formats, year of birth by context |
| Codes | One-time codes of confirmation, CVV/CVC by context |

A URL is masked in full if it contains personal data, such as an email address, a phone number, or a token in a query parameter. Replacing only part of the URL could break it. Ordinary links to websites and documentation remain unchanged.

Before detection, GPTunneL normalizes full-width digits, invisible characters, and URL encoding.

<a id="custom-patterns-obfuscate_patterns"></a>
## Custom patterns (obfuscate\_patterns)

With `obfuscate: true`, use `obfuscate_patterns` to mask values specific to your system, such as internal IDs, contract numbers, or project codes.

To mask an identifier such as `DOCREF-27183`, pass `"obfuscate_patterns": [{"pattern": "DOCREF-[0-9]{5}", "label": "DOCREF"}]`. See the [example request](<https://docs.gptunnel.ru/en/api/pii-obfuscation/#example>).

- `pattern` is a Python/PCRE-style regular expression. If it contains a capture group, only the captured text is masked.
- `label` sets the placeholder type. Use up to 16 uppercase Latin letters, digits, and underscores. The default is `CUSTOM`.
- A request can contain up to 20 patterns of up to 500 characters each.
- A match for a custom pattern is always masked, whether or not a built-in detector recognizes it.

If a pattern fails to compile, exceeds a limit, or takes longer than one second to run, GPTunneL rejects the request with `400 invalid_obfuscate_patterns` and explains the reason. It does not silently skip the pattern.

 <a id="что-стоит-учитывать"></a>
 
<a id="processing-restrictions"></a>
## Processing restrictions

- Placeholders are scoped to a single request. Send the full conversation history with each request. GPTunneL processes it again, so placeholder numbering can change between requests.
- Images are forwarded unchanged. Personal data visible in an image is not masked.
- Detection adds latency. A short message may take tens of milliseconds to scan, while a long conversation can take considerably longer.
- The limit is 500,000 characters per request, summed across the text parts of all messages. Above this limit the API returns `400 obfuscation_input_too_large`. The model is not called and no fee is charged.
- A nearby word such as “ИНН”, “СНИЛС”, or “карта” (card) can trigger masking even when an identifier’s checksum is invalid.

<a id="example"></a>
## Example

The request uses its own rule for the test mark. Read the reset value from `choices[0].message.content`.

<a id="tab-panel-0-0"></a>
**Python**

```python
import json
import os
from urllib.request import Request, urlopen

body = {
    'model': 'gpt-6-luna',
    'obfuscate': True,
    'obfuscate_patterns': [{'pattern': 'DOCREF-[0-9]{5}', 'label': 'DOCREF'}],
    'messages': [{'role': 'user', 'content': 'Повтори только метку DOCREF-27183.'}],
}
request = Request(
    'https://gptunnel.ru/v1/chat/completions',
    method='POST',
    headers={
        'Authorization': os.environ['GPTUNNEL_API_KEY'],
        'Content-Type': 'application/json',
    },
    data=json.dumps(body).encode('utf-8'),
)
with urlopen(request, timeout=30) as response:
    print(json.load(response)['choices'][0]['message']['content'])
```

<a id="tab-panel-0-1"></a>
**cURL**

```bash
curl --fail-with-body --silent --show-error \
  --url 'https://gptunnel.ru/v1/chat/completions' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --json '{
  "model": "gpt-6-luna",
  "obfuscate": true,
  "obfuscate_patterns": [
    {
      "pattern": "DOCREF-[0-9]{5}",
      "label": "DOCREF"
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": "Повтори только метку DOCREF-27183."
    }
  ]
}'
```

<a id="tab-panel-0-2"></a>
**JavaScript (Node.js)**

```javascript
const response = await fetch('https://gptunnel.ru/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: process.env.GPTUNNEL_API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  "model": "gpt-6-luna",
  "obfuscate": true,
  "obfuscate_patterns": [
    {
      "pattern": "DOCREF-[0-9]{5}",
      "label": "DOCREF"
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": "Повтори только метку DOCREF-27183."
    }
  ]
}),
})
if (!response.ok) throw new Error(await response.text())
console.log((await response.json()).choices[0].message.content)
```

<a id="error-when-service-is-not-available"></a>
### Error when service is not available

```json
{
  "error": {
    "message": "PII obfuscation is currently unavailable. Retry the request without `obfuscate`.",
    "type": "obfuscation_unavailable",
    "param": null,
    "code": "obfuscation_unavailable"
  }
}
```

 <a id="value"></a>
 
<a id="pricing"></a>
## Pricing

Masking is billed by the number of input tokens scanned. This includes the text in `content` for messages of every role. Tool descriptions, images, and provider caching are excluded, so this count can be lower than `usage.prompt_tokens`. The [model’s own charges](<https://docs.gptunnel.ru/en/getting-started/pricing/>) are calculated separately.

Masking appears as a separate transaction labeled “Скрытие персональных данных”. It applies even to free models and even if the scan finds no personal data. If the provider returns an error, **no masking fee is charged**.

GPTunneL uses the length of the message text to estimate the masking cost before sending the request. If the balance or the API key’s spending limit cannot cover it, the request is rejected with HTTP `402`.

```json
{
  "error": {
    "message": "Wallet balance is too low to pay for PII obfuscation of this request (about 0.28 RUB). Top up the balance or retry without `obfuscate`.",
    "type": "insufficient_balance_error",
    "param": null,
    "code": "obfuscation_insufficient_balance"
  }
}
```

After the response, the final charge is calculated from the actual number of text tokens scanned.

<a id="dedicated-endpoint-post-v1obfuscate"></a>
## Dedicated endpoint: POST /v1/obfuscate

To mask a document without calling a model and receive the placeholder-to-value `mapping`, use the [standalone text masking endpoint](<https://docs.gptunnel.ru/en/api/obfuscate/>).
