Skip to main content
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.
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}")
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.
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}")
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.
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>
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.
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
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.
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",
#   ...
# }
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.
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
# ...
Use Cases:
  • Development environments
  • Automated testing
  • Demo environments
  • Training datasets

Encrypting Sensitive Configuration

Encrypt sensitive configuration values before storing in databases.
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
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

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
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.
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)
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.
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}")
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.
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

export BLINDFOLD_API_KEY="your-key-here"
export ENCRYPTION_KEY="your-encryption-key"

2. Handle Errors Gracefully

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.

OpenAI + Python

Tokenize user messages before GPT, detokenize responses

OpenAI + Node.js

TypeScript/Node.js OpenAI integration

LangChain (Python)

PII-safe chains with RunnableLambda

LangChain (Node.js)

PII-safe LangChain.js chains with RunnableLambda

GDPR + OpenAI (Python)

EU region, gdpr_eu policy, batch processing

GDPR + OpenAI (Node.js)

EU region, gdpr_eu policy — TypeScript

HIPAA Chatbot (Python)

Multi-turn chat with hipaa_us policy, PHI redaction

HIPAA Chatbot (Node.js)

Multi-turn healthcare chatbot — TypeScript

E2B Data Analyst (Python)

AI writes analysis code from tokenized data, E2B runs it on real data

E2B Data Analyst (Node.js)

AI data analyst with E2B sandbox — TypeScript

FastAPI Middleware

Auto-tokenize request bodies in FastAPI

Express Middleware

Auto-tokenize request bodies in Express.js

RAG + OpenAI (Python)

PII-safe RAG with ChromaDB — redact at ingestion, tokenize at query

RAG + OpenAI (Node.js)

TypeScript RAG pipeline with ChromaDB and PII protection

RAG + LangChain (Python)

BlindfoldPIITransformer + blindfold_protect() with FAISS

RAG + LangChain (Node.js)

LangChain.js RAG with inline PII protection

RAG + LlamaIndex (Python)

Custom BlindfoldNodePostprocessor for LlamaIndex

RAG + LlamaIndex (Node.js)

LlamaIndex.TS RAG with PII protection

RAG Customer Support (Python)

GDPR multi-turn EU support chatbot with gdpr_eu policy

RAG Customer Support (Node.js)

TypeScript GDPR multi-turn EU support chatbot

Need More Examples?

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

Python SDK

Detailed Python SDK documentation

JavaScript SDK

Complete JavaScript SDK guide

Java SDK

Sync and async Java client

REST API

HTTP API reference

Contact Support

Email us for custom integration help