> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rehydra.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# createAnonymizer

> Create a reusable anonymizer instance

Creates and configures an anonymizer instance for PII detection and replacement.

## Signature

```typescript theme={null}
function createAnonymizer(config?: AnonymizerConfig): Anonymizer
```

## Parameters

### config (optional)

<ParamField path="mode" type="string" default="'pseudonymize'">
  Anonymization mode:

  * `'pseudonymize'` — Reversible. Returns an encrypted `piiMap` for later rehydration.
  * `'anonymize'` — Irreversible. No `piiMap` is returned; PII is permanently removed.
</ParamField>

<ParamField path="ner" type="NERConfig">
  NER model configuration

  <Expandable title="NERConfig properties">
    <ParamField path="mode" type="string" required>
      Model mode: `'disabled'` | `'quantized'` | `'standard'` | `'custom'`
    </ParamField>

    <ParamField path="modelPath" type="string">
      Custom model path (required when mode is `'custom'`)
    </ParamField>

    <ParamField path="vocabPath" type="string">
      Custom vocab path (required when mode is `'custom'`)
    </ParamField>

    <ParamField path="autoDownload" type="boolean" default="true">
      Auto-download model if not present
    </ParamField>

    <ParamField path="thresholds" type="Record<PIIType, number>">
      Confidence thresholds per PII type (0.0-1.0)
    </ParamField>

    <ParamField path="onStatus" type="(status: string) => void">
      Status message callback
    </ParamField>

    <ParamField path="onDownloadProgress" type="DownloadProgressCallback">
      Download progress callback
    </ParamField>

    <ParamField path="caseFallback" type="boolean" default="false">
      Enable case-insensitive fallback for detecting lowercase names. Runs a second NER pass on title-cased text and merges new detections. Doubles NER inference time but catches names like `"tom"` that the case-sensitive model would otherwise miss.
    </ParamField>

    <ParamField path="caseFallbackPenalty" type="number" default="0.85">
      Confidence penalty multiplier for case-fallback detections (0.0–1.0). Applied as `confidence * caseFallbackPenalty`. Lower values are stricter.
    </ParamField>

    <ParamField path="backend" type="string" default="'local'">
      Inference backend: `'local'` (ONNX on device) or `'inference-server'` (remote GPU server)
    </ParamField>

    <ParamField path="inferenceServerUrl" type="string">
      URL of the inference server (required when backend is `'inference-server'`)
    </ParamField>

    <ParamField path="inferenceServerTimeout" type="number" default="30000">
      Inference server request timeout in milliseconds
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="semantic" type="SemanticConfig">
  Semantic enrichment configuration

  <Expandable title="SemanticConfig properties">
    <ParamField path="enabled" type="boolean" default="false">
      Enable semantic enrichment (gender/scope attributes)
    </ParamField>

    <ParamField path="autoDownload" type="boolean" default="true">
      Auto-download semantic data if not present
    </ParamField>

    <ParamField path="onStatus" type="(status: string) => void">
      Status message callback
    </ParamField>

    <ParamField path="onDownloadProgress" type="DownloadProgressCallback">
      Download progress callback
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="keyProvider" type="KeyProvider">
  Encryption key provider. If not provided, generates a random key.
</ParamField>

<ParamField path="piiStorageProvider" type="PIIStorageProvider">
  Storage provider for session-based PII map persistence
</ParamField>

<ParamField path="defaultPolicy" type="AnonymizationPolicy">
  Default anonymization policy
</ParamField>

<ParamField path="secrets" type="SecretsConfig">
  Secrets/credentials detection configuration

  <Expandable title="SecretsConfig properties">
    <ParamField path="enabled" type="boolean" default="false">
      Enable secrets detection (API keys, tokens, connection strings, etc.)
    </ParamField>

    <ParamField path="envFiles" type="string[]">
      Paths to `.env` files for literal value redaction
    </ParamField>

    <ParamField path="redactValues" type="boolean">
      Redact secret values found in `.env` files
    </ParamField>

    <ParamField path="secretKeyPatterns" type="RegExp[]">
      Additional patterns to match secret key names
    </ParamField>

    <ParamField path="minValueLength" type="number" default="4">
      Minimum value length to consider a secret
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="tagFormat" type="TagFormat">
  Tag format for PII placeholder tags. Controls the delimiters and keyword.

  <Expandable title="TagFormat properties">
    <ParamField path="open" type="string" default="'<'">
      Opening delimiter (e.g., `"<"` for XML, `"[["` for bracket style)
    </ParamField>

    <ParamField path="close" type="string" default="'/>'">
      Closing delimiter (e.g., `"/>"` for XML self-closing, `"]]"` for bracket style)
    </ParamField>

    <ParamField path="keyword" type="string" default="'PII'">
      Tag keyword. Allows using e.g., `"REDACTED"` instead of `"PII"`
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="onValidationWarning" type="(warnings: Array<{ code: string; message: string }>) => void">
  Callback for validation warnings. When not provided, warnings are silently ignored — check `stats.leakScanPassed` in the result instead.
</ParamField>

<ParamField path="registry" type="RecognizerRegistry">
  Custom recognizer registry (uses default if not provided)
</ParamField>

## Returns

An `Anonymizer` instance with these methods:

| Method                              | Description                              |
| ----------------------------------- | ---------------------------------------- |
| `initialize()`                      | Initialize the anonymizer (loads models) |
| `anonymize(text, locale?, policy?)` | Anonymize text                           |
| `session(sessionId)`                | Create a session for persistent storage  |
| `dispose()`                         | Release resources                        |
| `getRegistry()`                     | Get the recognizer registry              |
| `getNERModel()`                     | Get the NER model instance               |
| `isInitialized`                     | Check if initialized                     |

## Examples

### Basic (Regex Only)

```typescript theme={null}
import { createAnonymizer } from 'rehydra';

const anonymizer = createAnonymizer();
await anonymizer.initialize();

const result = await anonymizer.anonymize('Contact: test@example.com');
console.log(result.anonymizedText);
// "Contact: <PII type="EMAIL" id="1"/>"

await anonymizer.dispose();
```

### With NER

```typescript theme={null}
const anonymizer = createAnonymizer({
  ner: { 
    mode: 'quantized',
    onStatus: (status) => console.log(status)
  }
});

await anonymizer.initialize();

const result = await anonymizer.anonymize('Hello John Smith!');
// "Hello <PII type="PERSON" id="1"/>!"
```

### With Semantic Enrichment

```typescript theme={null}
const anonymizer = createAnonymizer({
  ner: { mode: 'quantized' },
  semantic: { enabled: true }
});

await anonymizer.initialize();

const result = await anonymizer.anonymize('Contact Maria in Berlin');
// "Contact <PII type="PERSON" gender="female" id="1"/> in <PII type="LOCATION" scope="city" id="2"/>"
```

### With Storage

```typescript theme={null}
import { 
  createAnonymizer,
  InMemoryKeyProvider,
  SQLitePIIStorageProvider 
} from 'rehydra';

const storage = new SQLitePIIStorageProvider('./pii.db');
await storage.initialize();

const anonymizer = createAnonymizer({
  ner: { mode: 'quantized' },
  keyProvider: new InMemoryKeyProvider(),
  piiStorageProvider: storage,
});

await anonymizer.initialize();

// Use sessions for automatic persistence
const session = anonymizer.session('chat-123');
await session.anonymize('Hello John!');
```

### Irreversible Anonymization

```typescript theme={null}
const anonymizer = createAnonymizer({
  mode: 'anonymize',  // No piiMap returned, PII permanently removed
  ner: { mode: 'quantized' },
});

await anonymizer.initialize();

const result = await anonymizer.anonymize('Contact John Smith at john@acme.com');
console.log(result.anonymizedText);
// "Contact <PII type="PERSON" id="1"/> at <PII type="EMAIL" id="1"/>"
console.log(result.piiMap);  // undefined
```

### With Inference Server

```typescript theme={null}
const anonymizer = createAnonymizer({
  ner: {
    mode: 'quantized',
    backend: 'inference-server',
    inferenceServerUrl: 'http://gpu-server:8000/predict',
  }
});
```

### With Custom Tag Format

```typescript theme={null}
const anonymizer = createAnonymizer({
  tagFormat: { open: '[[', close: ']]' }
});

await anonymizer.initialize();

const result = await anonymizer.anonymize('Contact: test@example.com');
console.log(result.anonymizedText);
// "Contact: [[PII type="EMAIL" id="1"]]"
```

### With Custom Thresholds

```typescript theme={null}
import { createAnonymizer, PIIType } from 'rehydra';

const anonymizer = createAnonymizer({
  ner: { 
    mode: 'quantized',
    thresholds: {
      [PIIType.PERSON]: 0.8,
      [PIIType.ORG]: 0.7,
    }
  }
});
```

### With Custom Policy

```typescript theme={null}
import { createAnonymizer, PIIType, createDefaultPolicy } from 'rehydra';

const policy = createDefaultPolicy();
policy.enabledTypes = new Set([PIIType.EMAIL, PIIType.PHONE, PIIType.PERSON]);
policy.allowlistTerms = new Set(['Support Team', 'Help Desk']);
policy.enableLeakScan = true;

const anonymizer = createAnonymizer({
  ner: { mode: 'quantized' },
  defaultPolicy: policy,
});
```

### Excluding Countries and Regions

```typescript theme={null}
const anonymizer = createAnonymizer({
  ner: { mode: 'quantized' },
  semantic: { enabled: true },
  defaultPolicy: {
    excludeLocationScopes: new Set(['country', 'region']),
  },
});

await anonymizer.initialize();

const result = await anonymizer.anonymize('Meeting in Berlin, Germany.');
// "Meeting in <PII type="LOCATION" scope="city" id="1"/>, Germany."
```

## Related

* [anonymize](/api-reference/anonymize) - The anonymize method
* [Sessions](/api-reference/sessions) - Session-based persistence
* [Storage Providers](/api-reference/storage-providers) - Available storage options
