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

# Examples

> Practical examples for integrating Blindfold with OpenAI, Anthropic Claude, Google Gemini, and more

Learn how to integrate Blindfold into real-world applications with these practical examples.

## AI Chat with OpenAI

Protect user data when building AI chatbots with OpenAI.

> [tab] Python
>
> ```python theme={null}
> import os
> from blindfold import Blindfold
> from openai import OpenAI
>
> # Initialize clients
> blindfold = Blindfold(api_key=os.environ["BLINDFOLD_API_KEY"])
> openai_client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
>
> def secure_chat(user_message: str) -> str:
>     """Process chat message with privacy protection"""
>
>     # Step 1: Tokenize sensitive data
>     protected = blindfold.tokenize(user_message)
>     print(f"Protected input: {protected.text}")
>     print(f"Detected {protected.entities_count} sensitive entities")
>
>     # Step 2: Send protected text to OpenAI
>     response = openai_client.chat.completions.create(
>         model="gpt-4",
>         messages=[
>             {"role": "system", "content": "You are a helpful assistant."},
>             {"role": "user", "content": protected.text}
>         ]
>     )
>
>     ai_response = response.choices[0].message.content
>
>     # Step 3: Restore original data in AI response
>     final = blindfold.detokenize(ai_response, protected.mapping)
>
>     return final.text
>
> # Usage
> user_input = "My name is John Doe, email john@example.com. Help me book a flight."
> response = secure_chat(user_input)
> print(f"Response: {response}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
> import OpenAI from 'openai';
>
> // Initialize clients
> const blindfold = new Blindfold({
>   apiKey: process.env.BLINDFOLD_API_KEY
> });
>
> const openai = new OpenAI({
>   apiKey: process.env.OPENAI_API_KEY
> });
>
> async function secureChat(userMessage) {
>   // Step 1: Tokenize sensitive data
>   const protected = await blindfold.tokenize(userMessage);
>   console.log(`Protected input: ${protected.text}`);
>   console.log(`Detected ${protected.entities_count} sensitive entities`);
>
>   // Step 2: Send protected text to OpenAI
>   const response = await openai.chat.completions.create({
>     model: 'gpt-4',
>     messages: [
>       { role: 'system', content: 'You are a helpful assistant.' },
>       { role: 'user', content: protected.text }
>     ]
>   });
>
>   const aiResponse = response.choices[0].message.content;
>
>   // Step 3: Restore original data in AI response
>   const final = await blindfold.detokenize(aiResponse, protected.mapping);
>
>   return final.text;
> }
>
> // Usage
> const userInput = "My name is John Doe, email john@example.com. Help me book a flight.";
> const response = await secureChat(userInput);
> console.log(`Response: ${response}`);
> ```

> [tab] Java
>
> ```java theme={null}
> import dev.blindfold.sdk.Blindfold;
> import com.openai.OpenAI;
>
> Blindfold blindfold = new Blindfold(System.getenv("BLINDFOLD_API_KEY"));
>
> String secureChat(String userMessage) {
>     // Step 1: Tokenize sensitive data
>     var protected_ = blindfold.tokenize(userMessage);
>     System.out.println("Protected input: " + protected_.getText());
>     System.out.println("Detected " + protected_.getEntitiesCount() + " sensitive entities");
>
>     // Step 2: Send protected text to OpenAI
>     // (use your preferred OpenAI Java client)
>     String aiResponse = callOpenAI(protected_.getText());
>
>     // Step 3: Restore original data in AI response
>     var final_ = blindfold.detokenize(aiResponse, protected_.getMapping());
>
>     return final_.getText();
> }
>
> // Usage
> String userInput = "My name is John Doe, email john@example.com. Help me book a flight.";
> String response = secureChat(userInput);
> System.out.println("Response: " + response);
> ```

**What's Protected:**

* Personal names (`John Doe` → `<PERSON_1>`)
* Email addresses (`john@example.com` → `<EMAIL_ADDRESS_1>`)
* Any other PII in user messages

**Benefits:**

* User data never reaches OpenAI in plain text
* Compliant with privacy regulations
* Transparent to end users

***

## AI Chat with Anthropic Claude

Protect user data when building AI chatbots with Anthropic Claude.

> [tab] Python
>
> ```python theme={null}
> import os
> from blindfold import Blindfold
> import anthropic
>
> # Initialize clients
> blindfold = Blindfold(api_key=os.environ["BLINDFOLD_API_KEY"])
> client = anthropic.Anthropic()
>
> def secure_chat(user_message: str) -> str:
>     """Process chat message with privacy protection"""
>
>     # Step 1: Tokenize sensitive data
>     protected = blindfold.tokenize(user_message)
>     print(f"Protected input: {protected.text}")
>     print(f"Detected {protected.entities_count} sensitive entities")
>
>     # Step 2: Send protected text to Claude
>     response = client.messages.create(
>         model="claude-sonnet-4-20250514",
>         max_tokens=1024,
>         messages=[
>             {"role": "user", "content": protected.text}
>         ]
>     )
>
>     ai_response = response.content[0].text
>
>     # Step 3: Restore original data in AI response
>     final = blindfold.detokenize(ai_response, protected.mapping)
>
>     return final.text
>
> # Usage
> user_input = "My name is John Doe, email john@example.com. Help me book a flight."
> response = secure_chat(user_input)
> print(f"Response: {response}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
> import Anthropic from '@anthropic-ai/sdk';
>
> // Initialize clients
> const blindfold = new Blindfold({
>   apiKey: process.env.BLINDFOLD_API_KEY
> });
>
> const anthropic = new Anthropic();
>
> async function secureChat(userMessage) {
>   // Step 1: Tokenize sensitive data
>   const protected = await blindfold.tokenize(userMessage);
>   console.log(`Protected input: ${protected.text}`);
>   console.log(`Detected ${protected.entities_count} sensitive entities`);
>
>   // Step 2: Send protected text to Claude
>   const response = await anthropic.messages.create({
>     model: 'claude-sonnet-4-20250514',
>     max_tokens: 1024,
>     messages: [
>       { role: 'user', content: protected.text }
>     ]
>   });
>
>   const aiResponse = response.content[0].text;
>
>   // Step 3: Restore original data in AI response
>   const final = await blindfold.detokenize(aiResponse, protected.mapping);
>
>   return final.text;
> }
>
> // Usage
> const userInput = "My name is John Doe, email john@example.com. Help me book a flight.";
> const response = await secureChat(userInput);
> console.log(`Response: ${response}`);
> ```

> [tab] Java
>
> ```java theme={null}
> import dev.blindfold.sdk.Blindfold;
>
> Blindfold blindfold = new Blindfold(System.getenv("BLINDFOLD_API_KEY"));
>
> String secureChat(String userMessage) {
>     // Step 1: Tokenize sensitive data
>     var protected_ = blindfold.tokenize(userMessage);
>     System.out.println("Protected input: " + protected_.getText());
>     System.out.println("Detected " + protected_.getEntitiesCount() + " sensitive entities");
>
>     // Step 2: Send protected text to Claude
>     // (use your preferred Anthropic Java client)
>     String aiResponse = callClaude(protected_.getText());
>
>     // Step 3: Restore original data in AI response
>     var final_ = blindfold.detokenize(aiResponse, protected_.getMapping());
>
>     return final_.getText();
> }
>
> // Usage
> String userInput = "My name is John Doe, email john@example.com. Help me book a flight.";
> String response = secureChat(userInput);
> System.out.println("Response: " + response);
> ```

**Benefits:**

* User data never reaches Anthropic in plain text
* Works with Claude Sonnet, Opus, and Haiku
* Same tokenize/detokenize pattern as other providers

***

## Customer Support Ticket Anonymization

Anonymize customer support tickets before storing in databases or sending to third-party analytics.

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
> import os
>
> client = Blindfold(api_key=os.environ["BLINDFOLD_API_KEY"])
>
> def process_support_ticket(ticket_text: str) -> dict:
>     """Anonymize and process support ticket"""
>
>     # Redact sensitive data permanently
>     result = client.redact(ticket_text)
>
>     # Store anonymized ticket
>     ticket_data = {
>         "text": result.text,
>         "pii_detected": result.entities_count,
>         "entity_types": [e.type for e in result.detected_entities]
>     }
>
>     return ticket_data
>
> # Example ticket
> ticket = """
> Customer: Jane Smith
> Email: jane.smith@email.com
> Phone: +1-555-9876
> Issue: Cannot access account after password reset.
> SSN for verification: 123-45-6789
> """
>
> processed = process_support_ticket(ticket)
> print(f"Anonymized ticket:\n{processed['text']}")
> print(f"PII types found: {processed['entity_types']}")
>
> # Output:
> # Anonymized ticket:
> # Customer: <PERSON>
> # Email: <EMAIL_ADDRESS>
> # Phone: <PHONE_NUMBER>
> # Issue: Cannot access account after password reset.
> # SSN for verification: <US_SSN>
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({
>   apiKey: process.env.BLINDFOLD_API_KEY
> });
>
> async function processSupportTicket(ticketText) {
>   // Redact sensitive data permanently
>   const result = await client.redact(ticketText);
>
>   // Store anonymized ticket
>   const ticketData = {
>     text: result.text,
>     pii_detected: result.entities_count,
>     entity_types: result.detected_entities.map(e => e.type)
>   };
>
>   return ticketData;
> }
>
> // Example ticket
> const ticket = `
> Customer: Jane Smith
> Email: jane.smith@email.com
> Phone: +1-555-9876
> Issue: Cannot access account after password reset.
> SSN for verification: 123-45-6789
> `;
>
> const processed = await processSupportTicket(ticket);
> console.log(`Anonymized ticket:\n${processed.text}`);
> console.log(`PII types found: ${processed.entity_types}`);
> ```

> [tab] Java
>
> ```java theme={null}
> import dev.blindfold.sdk.Blindfold;
>
> Blindfold client = new Blindfold(System.getenv("BLINDFOLD_API_KEY"));
>
> Map<String, Object> processSupportTicket(String ticketText) {
>     // Redact sensitive data permanently
>     var result = client.redact(ticketText);
>
>     return Map.of(
>         "text", result.getText(),
>         "pii_detected", result.getEntitiesCount(),
>         "entity_types", result.getDetectedEntities().stream()
>             .map(e -> e.getType()).toList()
>     );
> }
>
> // Example ticket
> String ticket = """
>     Customer: Jane Smith
>     Email: jane.smith@email.com
>     Phone: +1-555-9876
>     Issue: Cannot access account after password reset.
>     SSN for verification: 123-45-6789
>     """;
>
> var processed = processSupportTicket(ticket);
> System.out.println("Anonymized ticket:\n" + processed.get("text"));
> System.out.println("PII types found: " + processed.get("entity_types"));
> ```

**Use Cases:**

* Support ticket systems
* Customer feedback collection
* Quality assurance reviews
* Third-party analytics

***

## Displaying Masked Credit Cards

Show partial credit card numbers in user interfaces while protecting full details.

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
>
> client = Blindfold(api_key="your-api-key")
>
> def display_payment_info(payment_text: str) -> str:
>     """Mask payment information for display"""
>
>     result = client.mask(
>         text=payment_text,
>         masking_char="*",
>         chars_to_show=4,
>         from_end=True
>     )
>
>     return result.text
>
> # Examples
> card_info = "Card ending in 4532-7562-9102-3456"
> print(display_payment_info(card_info))
> # Output: "Card ending in ***************3456"
>
> multiple_cards = """
> Primary: 4532-7562-9102-3456
> Backup: 5425-2334-3010-9903
> """
> print(display_payment_info(multiple_cards))
> # Output:
> # Primary: ***************3456
> # Backup: ***************9903
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({ apiKey: 'your-api-key' });
>
> async function displayPaymentInfo(paymentText) {
>   const result = await client.mask(
>     paymentText,
>     {
>       masking_char: '*',
>       chars_to_show: 4,
>       from_end: true
>     }
>   );
>
>   return result.text;
> }
>
> // Examples
> const cardInfo = "Card ending in 4532-7562-9102-3456";
> console.log(await displayPaymentInfo(cardInfo));
> // Output: "Card ending in ***************3456"
>
> const multipleCards = `
> Primary: 4532-7562-9102-3456
> Backup: 5425-2334-3010-9903
> `;
> console.log(await displayPaymentInfo(multipleCards));
> // Output:
> // Primary: ***************3456
> // Backup: ***************9903
> ```

> [tab] Java
>
> ```java theme={null}
> import dev.blindfold.sdk.Blindfold;
>
> Blindfold client = new Blindfold("your-api-key");
>
> String displayPaymentInfo(String paymentText) {
>     var result = client.mask(paymentText, 4, true, "*", null);
>     return result.getText();
> }
>
> // Examples
> String cardInfo = "Card ending in 4532-7562-9102-3456";
> System.out.println(displayPaymentInfo(cardInfo));
> // Output: "Card ending in ***************3456"
>
> String multipleCards = """
>     Primary: 4532-7562-9102-3456
>     Backup: 5425-2334-3010-9903
>     """;
> System.out.println(displayPaymentInfo(multipleCards));
> // Output:
> // Primary: ***************3456
> // Backup: ***************9903
> ```

**Benefits:**

* Users can identify their cards
* Full numbers stay protected
* Compliant with PCI-DSS

***

## Analytics with Hashed Identifiers

Create consistent identifiers for analytics without storing actual PII.

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
> import json
>
> client = Blindfold(api_key="your-api-key")
>
> def track_user_event(user_email: str, event: str) -> dict:
>     """Track user events with hashed identifiers"""
>
>     # Hash email for consistent user ID
>     hashed = client.hash(
>         text=f"User: {user_email}",
>         hash_type="sha256",
>         hash_prefix="user_",
>         hash_length=16
>     )
>
>     # Extract hashed ID
>     user_id = hashed.text.replace("User: ", "")
>
>     # Create analytics event
>     analytics_event = {
>         "user_id": user_id,
>         "event": event,
>         "timestamp": "2024-01-20T10:00:00Z"
>     }
>
>     return analytics_event
>
> # Track events for same user
> events = [
>     track_user_event("john@example.com", "page_view"),
>     track_user_event("john@example.com", "button_click"),
>     track_user_event("john@example.com", "purchase")
> ]
>
> # All events have same hashed user_id (deterministic)
> for event in events:
>     print(json.dumps(event, indent=2))
>
> # Output (same user_id for all):
> # {
> #   "user_id": "user_a3f8b9c2d4e5f6g7",
> #   "event": "page_view",
> #   ...
> # }
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({ apiKey: 'your-api-key' });
>
> async function trackUserEvent(userEmail, event) {
>   // Hash email for consistent user ID
>   const hashed = await client.hash(
>     `User: ${userEmail}`,
>     {
>       hash_type: 'sha256',
>       hash_prefix: 'user_',
>       hash_length: 16
>     }
>   );
>
>   // Extract hashed ID
>   const userId = hashed.text.replace('User: ', '');
>
>   // Create analytics event
>   return {
>     user_id: userId,
>     event: event,
>     timestamp: new Date().toISOString()
>   };
> }
>
> // Track events for same user
> const events = await Promise.all([
>   trackUserEvent('john@example.com', 'page_view'),
>   trackUserEvent('john@example.com', 'button_click'),
>   trackUserEvent('john@example.com', 'purchase')
> ]);
>
> // All events have same hashed user_id (deterministic)
> events.forEach(event => {
>   console.log(JSON.stringify(event, null, 2));
> });
> ```

> [tab] Java
>
> ```java theme={null}
> import dev.blindfold.sdk.Blindfold;
>
> Blindfold client = new Blindfold("your-api-key");
>
> Map<String, Object> trackUserEvent(String userEmail, String event) {
>     // Hash email for consistent user ID
>     var hashed = client.hash(
>         "User: " + userEmail,
>         "sha256", "user_", 16, null
>     );
>
>     String userId = hashed.getText().replace("User: ", "");
>
>     return Map.of(
>         "user_id", userId,
>         "event", event,
>         "timestamp", Instant.now().toString()
>     );
> }
>
> // Track events for same user
> var event1 = trackUserEvent("john@example.com", "page_view");
> var event2 = trackUserEvent("john@example.com", "button_click");
> var event3 = trackUserEvent("john@example.com", "purchase");
> // All events have same hashed user_id (deterministic)
> ```

**Benefits:**

* Consistent user tracking
* No PII in analytics database
* GDPR-friendly approach

***

## Generating Test Data

Create realistic test data with synthetic PII for development and testing.

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
>
> client = Blindfold(api_key="your-api-key")
>
> def generate_test_data(template: str, language: str = "en") -> list[str]:
>     """Generate multiple test data samples"""
>
>     samples = []
>     for _ in range(5):
>         result = client.synthesize(
>             text=template,
>             language=language
>         )
>         samples.append(result.text)
>
>     return samples
>
> # Generate test user profiles
> template = """
> Name: John Doe
> Email: john.doe@company.com
> Phone: +1-555-1234
> Location: New York
> Company: TechCorp
> """
>
> test_profiles = generate_test_data(template)
>
> print("Generated Test Profiles:")
> for i, profile in enumerate(test_profiles, 1):
>     print(f"\n=== Profile {i} ===")
>     print(profile)
>
> # Output (synthetic data):
> # === Profile 1 ===
> # Name: Michael Smith
> # Email: michael.smith@company.com
> # Phone: +1-555-9876
> # Location: Boston
> # Company: DataSystems
> #
> # === Profile 2 ===
> # Name: Sarah Johnson
> # Email: sarah.johnson@company.com
> # ...
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({ apiKey: 'your-api-key' });
>
> async function generateTestData(template, language = 'en', count = 5) {
>   const samples = [];
>
>   for (let i = 0; i < count; i++) {
>     const result = await client.synthesize(template, { language });
>     samples.push(result.text);
>   }
>
>   return samples;
> }
>
> // Generate test user profiles
> const template = `
> Name: John Doe
> Email: john.doe@company.com
> Phone: +1-555-1234
> Location: New York
> Company: TechCorp
> `;
>
> const testProfiles = await generateTestData(template);
>
> console.log('Generated Test Profiles:');
> testProfiles.forEach((profile, i) => {
>   console.log(`\n=== Profile ${i + 1} ===`);
>   console.log(profile);
> });
> ```

**Use Cases:**

* Development environments
* Automated testing
* Demo environments
* Training datasets

***

## Encrypting Sensitive Configuration

Encrypt sensitive configuration values before storing in databases.

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
> import os
>
> client = Blindfold(api_key=os.environ["BLINDFOLD_API_KEY"])
>
> # Encryption key (store securely!)
> ENCRYPTION_KEY = os.environ["ENCRYPTION_KEY"]
>
> def encrypt_config(config_text: str) -> str:
>     """Encrypt sensitive configuration"""
>
>     result = client.encrypt(
>         text=config_text,
>         encryption_key=ENCRYPTION_KEY
>     )
>
>     return result.text
>
> def decrypt_config(encrypted_text: str) -> str:
>     """Decrypt configuration (use decrypt endpoint)"""
>     # Note: Implement decrypt endpoint call
>     pass
>
> # Example: Encrypt API keys before storing
> config = """
> database_url: postgresql://user:pass@host/db
> api_key: sk-1234567890abcdef
> secret_token: abc123xyz789
> """
>
> encrypted = encrypt_config(config)
> print("Encrypted configuration:")
> print(encrypted)
>
> # Store encrypted version in database
> # Later, decrypt when needed
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({
>   apiKey: process.env.BLINDFOLD_API_KEY
> });
>
> const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;
>
> async function encryptConfig(configText) {
>   const result = await client.encrypt(
>     configText,
>     { encryption_key: ENCRYPTION_KEY }
>   );
>
>   return result.text;
> }
>
> // Example: Encrypt API keys before storing
> const config = `
> database_url: postgresql://user:pass@host/db
> api_key: sk-1234567890abcdef
> secret_token: abc123xyz789
> `;
>
> const encrypted = await encryptConfig(config);
> console.log('Encrypted configuration:');
> console.log(encrypted);
>
> // Store encrypted version in database
> ```

**Benefits:**

* Protect secrets at rest
* Reversible encryption
* Centralized key management

***

## Multi-Language Support & Custom Entities

Blindfold automatically detects PII across 6+ languages and supports custom entity types for industry-specific data.

### Automatic Multilingual Detection

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
>
> client = Blindfold(api_key="your-api-key")
>
> # Automatic language detection - no configuration needed
> # Spanish example
> spanish_text = "Mi nombre es María García, email: maria@ejemplo.es, teléfono: +34 912 345 678"
> result_es = client.tokenize(spanish_text)
> print(f"Spanish: {result_es.text}")
> # Output: "Mi nombre es <PERSON_1>, email: <EMAIL_ADDRESS_1>, teléfono: <PHONE_NUMBER_1>"
>
> # German example
> german_text = "Ich heiße Hans Müller, E-Mail: hans@beispiel.de, wohne in Berlin"
> result_de = client.tokenize(german_text)
> print(f"German: {result_de.text}")
> # Output: "Ich heiße <PERSON_1>, E-Mail: <EMAIL_ADDRESS_1>, wohne in <LOCATION_1>"
>
> # French example
> french_text = "Je m'appelle Marie Dupont, email: marie@exemple.fr, tél: +33 1 42 86 82 00"
> result_fr = client.tokenize(french_text)
> print(f"French: {result_fr.text}")
> # Output: "Je m'appelle <PERSON_1>, email: <EMAIL_ADDRESS_1>, tél: <PHONE_NUMBER_1>"
>
> # Mixed languages in one request
> mixed_text = "Contact: John Doe (john@example.com), Client: María García (maria@ejemplo.es)"
> result_mixed = client.tokenize(mixed_text)
> print(f"Mixed: {result_mixed.text}")
> # Automatically detects entities in both English and Spanish
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({ apiKey: 'your-api-key' });
>
> // Automatic language detection - no configuration needed
> // Spanish example
> const spanishText = "Mi nombre es María García, email: maria@ejemplo.es, teléfono: +34 912 345 678";
> const resultEs = await client.tokenize(spanishText);
> console.log(`Spanish: ${resultEs.text}`);
>
> // German example
> const germanText = "Ich heiße Hans Müller, E-Mail: hans@beispiel.de, wohne in Berlin";
> const resultDe = await client.tokenize(germanText);
> console.log(`German: ${resultDe.text}`);
>
> // French example
> const frenchText = "Je m'appelle Marie Dupont, email: marie@exemple.fr, tél: +33 1 42 86 82 00";
> const resultFr = await client.tokenize(frenchText);
> console.log(`French: ${resultFr.text}`);
>
> // Mixed languages in one request
> const mixedText = "Contact: John Doe (john@example.com), Client: María García (maria@ejemplo.es)";
> const resultMixed = await client.tokenize(mixedText);
> console.log(`Mixed: ${resultMixed.text}`);
> ```

**Native Language Support (Tier 1 - Highest Accuracy):**

* 🇺🇸 English, 🇩🇪 German, 🇫🇷 French, 🇪🇸 Spanish, 🇮🇹 Italian, 🇵🇹 Portuguese, 🇳🇱 Dutch, 🇵🇱 Polish, 🇷🇺 Russian

**Zero-Shot Support (Tier 2 - High Accuracy):**

* 🇨🇿 Czech, 🇸🇰 Slovak, 🇩🇰 Danish, 🇸🇪 Swedish, 🇳🇴 Norwegian, 🇷🇴 Romanian

**Key Features:**

* Automatic detection - no language parameter needed
* Mix multiple languages in the same request
* Works on 15+ languages without configuration

### Custom Entity Detection

Define custom entities for industry-specific identifiers using zero-shot learning.

> [tab] Python
>
> ```python theme={null}
> from blindfold import Blindfold
>
> client = Blindfold(api_key="your-api-key")
>
> # E-commerce example with custom entities
> order_text = "Order #ORD-2024-XYZ for customer CUST-456, SKU: PROD-789-BLU"
> result = client.tokenize(
>     order_text,
>     entities=["order number", "customer id", "product sku"]
> )
> print(result.text)
> # Output: "Order #<CUSTOM_1> for customer <CUSTOM_2>, SKU: <CUSTOM_3>"
>
> # Healthcare example with custom entities
> medical_text = "Patient admitted to Ward 5B, Doctor ID: DOC-123, Procedure Code: PROC-456"
> result = client.tokenize(
>     medical_text,
>     entities=["ward number", "doctor identifier", "procedure code"]
> )
> print(result.text)
>
> # Mix standard and custom entities
> mixed_text = "Customer John Doe (ID: CUST-789) ordered item SKU-456 on 2024-01-15"
> result = client.tokenize(
>     mixed_text,
>     entities=["PERSON", "EMAIL_ADDRESS", "customer id", "product sku", "DATE_TIME"]
> )
> print(result.text)
> # Detects both standard PII (PERSON, DATE_TIME) and custom entities (customer id, product sku)
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({ apiKey: 'your-api-key' });
>
> // E-commerce example with custom entities
> const orderText = "Order #ORD-2024-XYZ for customer CUST-456, SKU: PROD-789-BLU";
> const result = await client.tokenize(
>   orderText,
>   { entities: ["order number", "customer id", "product sku"] }
> );
> console.log(result.text);
>
> // Healthcare example with custom entities
> const medicalText = "Patient admitted to Ward 5B, Doctor ID: DOC-123, Procedure Code: PROC-456";
> const result2 = await client.tokenize(
>   medicalText,
>   { entities: ["ward number", "doctor identifier", "procedure code"] }
> );
> console.log(result2.text);
>
> // Mix standard and custom entities
> const mixedText = "Customer John Doe (ID: CUST-789) ordered item SKU-456 on 2024-01-15";
> const result3 = await client.tokenize(
>   mixedText,
>   { entities: ["PERSON", "EMAIL_ADDRESS", "customer id", "product sku", "DATE_TIME"] }
> );
> console.log(result3.text);
> ```

**Custom Entity Benefits:**

* No training required - describe entities in natural language
* Works across any industry or domain
* Combine with 40+ pre-trained entity types
* Zero-shot detection adapts to your use case

***

## Batch Processing

Process multiple texts efficiently in parallel.

> [tab] Python
>
> ```python theme={null}
> import asyncio
> from blindfold import AsyncBlindfold
>
> async def process_batch(texts: list[str]) -> list:
>     """Process multiple texts concurrently"""
>
>     async with AsyncBlindfold(api_key="your-api-key") as client:
>         # Process all texts in parallel
>         tasks = [client.tokenize(text) for text in texts]
>         results = await asyncio.gather(*tasks)
>
>         return results
>
> # Example: Process 100 customer messages
> messages = [
>     f"Customer {i}: email{i}@example.com"
>     for i in range(100)
> ]
>
> results = asyncio.run(process_batch(messages))
> print(f"Processed {len(results)} messages")
> print(f"Average entities per message: {sum(r.entities_count for r in results) / len(results):.2f}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Blindfold } from '@blindfold/sdk';
>
> const client = new Blindfold({ apiKey: 'your-api-key' });
>
> async function processBatch(texts) {
>   // Process all texts in parallel
>   const results = await Promise.all(
>     texts.map(text => client.tokenize(text))
>   );
>
>   return results;
> }
>
> // Example: Process 100 customer messages
> const messages = Array.from(
>   { length: 100 },
>   (_, i) => `Customer ${i}: email${i}@example.com`
> );
>
> const results = await processBatch(messages);
> console.log(`Processed ${results.length} messages`);
>
> const avgEntities = results.reduce((sum, r) => sum + r.entities_count, 0) / results.length;
> console.log(`Average entities per message: ${avgEntities.toFixed(2)}`);
> ```

**Performance Tips:**

* Use async/parallel processing for batches
* Implement rate limiting
* Use connection pooling
* Handle errors gracefully

***

## Express.js Middleware

Create middleware to automatically protect routes.

```javascript theme={null}
import express from 'express';
import { Blindfold } from '@blindfold/sdk';

const app = express();
const client = new Blindfold({ apiKey: process.env.BLINDFOLD_API_KEY });

// Middleware to protect request bodies
const protectPII = async (req, res, next) => {
  try {
    if (req.body && req.body.text) {
      const protected = await client.tokenize(req.body.text);

      // Store mapping in session for later detokenization
      req.session.tokenMapping = protected.mapping;

      // Replace text with protected version
      req.body.text = protected.text;
      req.body.pii_detected = protected.entities_count;
    }

    next();
  } catch (error) {
    res.status(500).json({ error: 'Failed to protect data' });
  }
};

// Apply middleware to specific routes
app.post('/api/chat', express.json(), protectPII, async (req, res) => {
  // req.body.text is now protected
  // Process with AI...
  res.json({ message: 'Processed securely' });
});

app.listen(3000);
```

***

## Best Practices Summary

### 1. Always Use Environment Variables

```bash theme={null}
export BLINDFOLD_API_KEY="your-key-here"
export ENCRYPTION_KEY="your-encryption-key"
```

### 2. Handle Errors Gracefully

```python theme={null}
try:
    result = client.tokenize(text)
except AuthenticationError:
    # Handle auth error
    pass
except NetworkError:
    # Retry with exponential backoff
    pass
```

### 3. Store Mappings Securely

* Use encrypted session storage
* Implement TTL for mappings
* Clear mappings after use

### 4. Use Appropriate Methods

* **Tokenize**: When you need to restore data later
* **Mask**: For UI display
* **Redact**: For permanent removal
* **Hash**: For analytics identifiers
* **Synthesize**: For test data

### 5. Monitor Usage

* Track API usage in dashboard
* Set up rate limit alerts
* Monitor error rates

## Cookbook

Complete, runnable examples you can clone and use as a starting point. Each example is a self-contained project with setup instructions.

> [card] [OpenAI + Python](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/openai-python)
>
> Tokenize user messages before GPT, detokenize responses

> [card] [OpenAI + Node.js](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/openai-node)
>
> TypeScript/Node.js OpenAI integration

> [card] [LangChain (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/langchain-python)
>
> PII-safe chains with RunnableLambda

> [card] [LangChain (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/langchain-node)
>
> PII-safe LangChain.js chains with RunnableLambda

> [card] [GDPR + OpenAI (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/gdpr-openai-python)
>
> EU region, gdpr\_eu policy, batch processing

> [card] [GDPR + OpenAI (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/gdpr-openai-node)
>
> EU region, gdpr\_eu policy — TypeScript

> [card] [HIPAA Chatbot (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/hipaa-healthcare-chatbot)
>
> Multi-turn chat with hipaa\_us policy, PHI redaction

> [card] [HIPAA Chatbot (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/hipaa-healthcare-chatbot-node)
>
> Multi-turn healthcare chatbot — TypeScript

> [card] [E2B Data Analyst (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/e2b-data-analyst)
>
> AI writes analysis code from tokenized data, E2B runs it on real data

> [card] [E2B Data Analyst (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/e2b-data-analyst-node)
>
> AI data analyst with E2B sandbox — TypeScript

> [card] [FastAPI Middleware](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/fastapi-middleware)
>
> Auto-tokenize request bodies in FastAPI

> [card] [Express Middleware](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/express-middleware)
>
> Auto-tokenize request bodies in Express.js

> [card] [RAG + OpenAI (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-openai-python)
>
> PII-safe RAG with ChromaDB — redact at ingestion, tokenize at query

> [card] [RAG + OpenAI (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-openai-node)
>
> TypeScript RAG pipeline with ChromaDB and PII protection

> [card] [RAG + LangChain (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-langchain-python)
>
> BlindfoldPIITransformer + blindfold\_protect() with FAISS

> [card] [RAG + LangChain (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-langchain-node)
>
> LangChain.js RAG with inline PII protection

> [card] [RAG + LlamaIndex (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-llamaindex-python)
>
> Custom BlindfoldNodePostprocessor for LlamaIndex

> [card] [RAG + LlamaIndex (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-llamaindex-node)
>
> LlamaIndex.TS RAG with PII protection

> [card] [RAG Customer Support (Python)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-customer-support-python)
>
> GDPR multi-turn EU support chatbot with gdpr\_eu policy

> [card] [RAG Customer Support (Node.js)](https://github.com/blindfold-dev/blindfold-cookbook/tree/main/examples/rag-customer-support-node)
>
> TypeScript GDPR multi-turn EU support chatbot

## Need More Examples?

Can't find what you're looking for? Check out:

> [card] [Python SDK](https://docs.blindfold.dev/sdks/python-sdk.md)
>
> Detailed Python SDK documentation

> [card] [JavaScript SDK](https://docs.blindfold.dev/sdks/javascript-sdk.md)
>
> Complete JavaScript SDK guide

> [card] [Java SDK](https://docs.blindfold.dev/sdks/java-sdk.md)
>
> Sync and async Java client

> [card] [REST API](https://docs.blindfold.dev/api-reference/rest-api.md)
>
> HTTP API reference

> [card] [Contact Support](mailto:hello@blindfold.dev)
>
> Email us for custom integration help


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.