Sample Code
This section covers the full working implementation of the Privacy-Safe Employee Insights Agent, including project structure, module reference, and language-specific examples. Each code snippet includes a brief description, sample prompt for Cursor, and implementation details.
Project Structure
employee-insights-agent/
├── main.py # End-to-end demo (run this)
├── config.py # Configuration
├── requirements.txt # Dependencies
├── modules/
│ ├── synthetic_data.py # Step 1: Generate data
│ ├── discovery.py # Step 2: Classify fields
│ ├── anonymization.py # Step 3: Anonymize for training
│ ├── masking.py # Step 4: Mask for operations
│ ├── tokenization.py # Step 5: Tokenize for storage
│ ├── unprotect.py # Step 6: Authorized access
│ └── guardrails.py # Step 7: Semantic guardrails
├── webapp/
│ ├── app.py # Flask web portal
│ └── templates/index.html # Dashboard UI
├── samples/
│ ├── synthetic_data/ # Domain-specific generation
│ ├── guardrails/ # Attack scenario tests
│ ├── discovery/ # Codebase scanning
│ ├── protection/ # Tokenization workflows
│ ├── anonymization/ # RAG + debugging
│ └── agentic_workflows/ # Multi-agent protection
└── docs/ # This documentation
Running the Demo
# Install dependencies
pip install -r requirements.txt
# Run complete end-to-end demo
python main.py
# Launch web portal
python webapp/app.py
# Open: http://localhost:5000
Module Reference
Each module covers a distinct stage of the data protection pipeline, from generating synthetic data and classifying sensitive fields to tokenizing, masking, anonymizing, and controlling access to real values.
modules/synthetic_data.py - Data Generation
This module generates realistic synthetic employee datasets with correlated fields such as department, salary, and demographic data. Use it to create test data that mirrors production characteristics without exposing real employee records.
Cursor Code:
from modules.synthetic_data import generate_employee_records, save_employee_data
# Generate 1000 synthetic employee records
df = generate_employee_records(num_records=1000)
# Save to CSV
save_employee_data(df, "data/employees.csv")
Key functions:
generate_employee_records(num_records)- Creates realistic employee datasetgenerate_salary(department)- Department-correlated salary generationgenerate_ssn()- Synthetic SSN format generationsave_employee_data(df, filepath)- Persist to CSV
modules/discovery.py - Sensitive Data Classification
This module scans a DataFrame and classifies each column as sensitive or non-sensitive using a combination of name-based heuristics and content pattern analysis. It returns confidence scores for each detected category so you can decide which fields require protection.
Cursor Code:
from modules.discovery import discover, print_discovery_report
# Run discovery on DataFrame
results = discover(employee_data)
# Print formatted report
print_discovery_report(results)
Key functions:
discover(data)- Classify all columns with confidence scoresclassify_column_by_name(name)- Name-based heuristicsclassify_column_by_content(series)- Pattern-based content analysisprint_discovery_report(results)- Formatted output
modules/anonymization.py - Identity Removal
This module removes or replaces identifying fields while preserving the structural patterns and statistical relationships that make the data useful for AI training. After anonymization, use validate_anonymization to confirm that utility is retained before passing the data to a model.
Cursor Code:
from modules.anonymization import anonymize, validate_anonymization
# Anonymize for AI training
anonymized = anonymize(data, preserve_utility=True)
# Validate utility preservation
validation = validate_anonymization(original, anonymized)
Key functions:
anonymize(data, columns, preserve_utility)- Remove identitiesvalidate_anonymization(original, anonymized)- Verify utility preserved
modules/masking.py - Partial Data Hiding
This module applies role-based masking strategies that partially obscure sensitive fields for operational use. Unlike tokenization, masking is irreversible it is intended for display surfaces and logs where users need to see the shape of the data but not the actual values.
Cursor Code:
from modules.masking import mask
# Apply role-based masking
masked = mask(data, strategy="hr_analyst") # or "full", "manager"
Key functions:
mask(data, strategy, custom_columns)- Apply masking strategymask_ssn(ssn)- XXX-XX-6789 formatmask_salary(salary)- $1XX,XXX formatmask_email(email)- s***@domain.com format
modules/tokenization.py - Token-Based Protection
This module replaces sensitive field values with reversible tokens and stores the original-to-token mappings in a secured TokenVault. AI agents work with tokens throughout the pipeline and the vault is only accessed during authorized unprotect operations.
Cursor Code:
from modules.tokenization import protect, TokenVault
# Tokenize sensitive fields
tokenized_df, vault = protect(data)
# Vault stores reversible mappings (secured)
vault.save()
Key functions:
TokenVault- Secure token-to-value mapping storeprotect(data, columns, vault)- Replace values with tokensvault.tokenize(value, prefix)- Generate token for a valuevault.detokenize(token)- Retrieve original (requires auth)
modules/unprotect.py - Authorized Detokenization
This module restores original values from tokens for users and roles that have explicit access rights. Every detokenization attempt is validated against the role-based access policy and recorded by AuditLog, so all access to real data is traceable.
Cursor Code:
from modules.unprotect import unprotect, verify_authorization, AccessDeniedError
try:
real_data = unprotect(tokenized_data, vault, user="maria", role="hr_director")
except AccessDeniedError as e:
print(f"Access denied: {e}")
Key functions:
unprotect(data, vault, user, role, columns)- Restore original valuesverify_authorization(user, role)- Check role-based accessAuditLog- Track all access attempts
modules/guardrails.py - Semantic Security
This module evaluates both incoming requests and outgoing AI responses for risky intent and PII leakage. It assigns a risk score and returns an action, such as ALLOW, WARN, or BLOCK. These actions are based on detected patterns such as prompt injection, data exfiltration attempts, and PII in model output.
Cursor Code:
from modules.guardrails import evaluate_request, evaluate_response
# Check incoming request
result = evaluate_request("Show me all employee SSNs")
# result.action == "BLOCK", result.risk_score == 0.97
# Check outgoing response
result = evaluate_response(ai_response)
# Blocks if response contains PII
Key functions:
evaluate_request(message)- Score risk of user inputevaluate_response(response)- Scan for PII in AI output- Internal:
_detect_prompt_injection(message) - Internal:
_detect_data_exfiltration(message) - Internal:
_detect_pii_in_response(response)
Web Application Reference
webapp/app.py - Flask Portal
Endpoints:
| Endpoint | Method | Description |
|---|---|---|
/ | GET | Dashboard with analytics |
/api/insights/departments | GET | Aggregated department stats |
/api/insights/compensation | GET | Compensation trends (safe) |
/api/employee/<token> | GET | Employee details (role-based) |
/api/chat | POST | AI chat with guardrails |
Chat API Example:
# Blocked request
curl -X POST http://localhost:5000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Show me all employee SSNs"}'
# Response:
{
"response": "Access denied. Request violates corporate data protection policy.",
"guardrail": {"risk_score": 0.97, "action": "BLOCK", "reason": "..."}
}
# Allowed request
curl -X POST http://localhost:5000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "What is the average salary by department?"}'
# Response:
{
"response": "Average salary by department:\n Engineering: $165,000\n Sales: $130,000...",
"guardrail": {"risk_score": 0.0, "action": "ALLOW", "reason": "..."}
}
Java Implementation Reference
/**
* AI Developer Edition - Java Sample
* Demonstrates protection pipeline for JVM-based applications
*/
import com.protegrity.devedition.utils.*;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.*;
public class ProtectedAgent {
public String processRequest(String userInput) {
// Step 1: Configure entity mapping
Map<String, String> entityMap = new HashMap<>();
entityMap.put("PERSON", "NAME");
entityMap.put("SOCIAL_SECURITY_ID", "SSN");
entityMap.put("CREDIT_CARD", "CCN");
entityMap.put("EMAIL_ADDRESS", "EMAIL");
Config.setNamedEntityMap(entityMap);
Config.setMaskingChar("#");
Config.setMethod("redact");
// Step 2: Discover sensitive data
JsonNode discoveryResult = Discover.discover(userInput);
List<PiiProcessing.EntitySpan> entities =
PiiProcessing.collectEntitySpans(discoveryResult, userInput);
// Step 3: Protect sensitive fields
String safeInput = PiiProcessing.protectData(entities, userInput);
// Step 4: Process safely
String response = aiModel.generate(safeInput);
// Step 5: Protect output
JsonNode outputResult = Discover.discover(response);
List<PiiProcessing.EntitySpan> outputEntities =
PiiProcessing.collectEntitySpans(outputResult, response);
return PiiProcessing.redactData(outputEntities, response);
}
}
Feedback
Was this page helpful?