How to Safely Redact PII from Segment Events using Destination Insert Functions and Private AI API

Private AI
May 31, 2024
Share this post
Sharing to FacebookSharing to LinkedInSharing to XSharing to Email

Twilio Segment is a great centralized platform for storing customer data. However, it's unlikely Segment will be your only application that needs the data. Most of us will need to download customer information from Segment, store it in the data lake, propagate the data to reporting software, and populate a few backend databases. All of this may end up terribly wrong.

What's the least fun part of data engineering? I bet it's backfilling data when you made a mistake in the pipeline and need to fix months of data and update reports. Do you know what's even worse? When the data you fix contains Personal Identifiable Information (PII) that you were supposed to remove but you didn't. It is better to remove PII as early as possible in your data pipeline and not worry about it ever again.

Why do we need to remove PII from Segment Events?

Data engineering may occasionally feel like the act of pushing problems from one place to another, but when it comes to PII, pushing problems downstream is the worst thing you can do.

One day, you may need to remove a piece of data because of GDPR or other regulations. On that day, you realize PII is propagated to several downstream systems. The systems are scattered across multiple geo locations or belong to third parties with data centers abroad. You aren't entirely sure whether the Data Processing Agreement accepted by your users allows you to send the data to those countries. Ok, enough. You are reading a tech tutorial, not a horror story for data engineers ;)

Let's remove PII immediately instead of pushing data and future problems downstream. If nobody gets access to PII just because PII happened to be included in the dataset they used, you minimize the number of systems you have to touch when someone requests a change or removal of their data.

How Private AI API removes PII

When you send data to the Private AI API (and you can deploy the service in your infrastructure or use cloud SaaS), Private AI will find and mask all of the personal data. The response you receive will contain the processed, redacted data and all of the entities present in the original data. You can use those entities to revert data replacement. Of course, if the downstream systems of your data pipeline shouldn't have access to personal data, you can drop the entities and propagate only the de-identified text.

Right now, Private AI supports over 50 languages and personal data types (in Private AI API, data types are called entity types, such as family name, passport number, location, etc.), so it is most likely the only tool you need to remove PII.

Using Segment Destination Insert Functions to Remove PII while Downloading Data

Of course, we have to call the Private AI API somewhere. While making the API call a separate step in a data pipeline is always a viable option, in the case of downloading data from Segment, we suggest simplifying the pipeline and using Segment Destination Insert Functions.

Insert Functions are a feature allowing you to write custom JavaScript code to transform and enrich data before sending it to the destination. In our case, we will use those functions to redact PII.

Step-by-Step Guide to Redact PII with Destination Insert Functions and Private AI API

Prerequisites

  1. Before starting, head to portal.private-ai.com and get yourself an API key.
  2. Naturally, you will need a Segment account. If you don't have one, create it here.
  3. We will also need some data. This article uses AI and a Python script to generate fake data. We will use Segment API and Cohere AI. Remember to install both as Python dependencies to run our data generation script.

Generating fake data

In the data-generating script, we create a free-form message with the content generated by AI and some hard-coded personal information. First, we have to import the libraries.

```
import datetime
import cohere
import segment.analytics as analytics
```
Next, we ask Cohere AI to generate an example doctor's note:
```
cohere_client = cohere.Client(‘PUT_YOUR_COHERE_API_KEY_HERE’)
response = cohere_client.chat(model='command-r-plus',  message='Write an example of a doctors notes about a patient who suffers from many conditions')
```

Finally, we create a user identification record and track an event for that user.

```
analytics.write_key = ‘PUT_YOUR_SEGMENT_API_KEY_HERE’
analytics.identify('f4ca124298', {
    'name': 'Michael Bolton',
    'email': 'mbolton@example.com',
    'created_at': datetime.datetime.now(),
    'account_id': 1
})
analytics.track('f4ca124298', 'Message Sent', {
    'title': 'Message between Sam and Allan',
    'content': response.text,
})
```


Write JavaScript Code for Destination Insert Function

Before we continue, we must prepare the Insert Function. Note that, in the example, we modify only the event's content property.

In the function, we send a request to the Private AI API to transform the data. When we receive a successful response, we change the event's name to indicate it was modified by the insert function and replace its content with the processed text returned from the API.

The processed text property contains the original data with PII replaced by entity placeholders. Those placeholders and their original values are in the response's "entities" property, but we ignore them. Therefore, the downstream system won't have a way to revert de-identification.

Also, we are using the Private AI default settings to redact all supported data types. However, it's possible to customize the settings and keep some of the information in the text. For example, you could remove people's names but keep city names. For details, visit the Customizing Detection guide.

async function onTrack(event, settings) {
 // Learn more at https://segment.com/docs/connections/spec/track/
 const endpoint = 'https://api.private-ai.com/demo/v3/process/text';
 let response;
 try {
   response = await fetch(endpoint, {
     method: 'POST',
     headers: {
       'x-api-key': `PUT_YOUR_PRIVATE_AI_API_KEY_HERE`,
       'Content-Type': 'application/json'
     },
     body: JSON.stringify({ text: [event.properties.content] })
   });
 } catch (error) {
   // Retry on connection error
   throw new RetryError(error.message);
 }
 if (response.status >= 500 || response.status === 429) {
   // Retry on 5xx (server errors) and 429s (rate limits)
   throw new RetryError(`Failed with ${response.status}`);
 }
 const jsonifiedResponse = await response.json();
 event.name = 'event modified from insert function';
 event.properties.content = jsonifiedResponse[0].processed_text;
 console.log(event);
 return event;
}

Setup the Destination Insert Function

In Segment, navigate to Connections > Catalog > Functions and click Create Function.

Select the Insert function type on the screen and click "Next: Build Function."

Copy-paste the function code we prepared earlier.

When you finish, click "Next: Configure & Create" to add the function metadata and click "Create Function."

Remember to use the "Connect to destination" option and add your function to the destination where you send the data.

Verify Successful PII Redaction

Remember to verify that the PII has been successfully redacted. If something doesn't work, you want to know about it now, not when you gather a few hundred TBs of data. Remember that you can customize the type of entities removed from the data by Private AI.

Conclusion

Private AI API used inside of Segment Destination Insert Functions offers a powerful solution to redact PII from Segment events before sending them to downstream applications. With Private AI, data engineers can ensure data privacy and compliance with data protection regulations and mitigate the risk of exposing sensitive information to applications that don't need it. Check out the Getting Started guide to learn more.

Data Left Behind: AI Scribes’ Promises in Healthcare

Why is linguistics essential when dealing with healthcare data?

Why Health Data Strategies Fail Before They Start

Private AI to Redefine Enterprise Data Privacy and Compliance with NVIDIA

EDPB’s Pseudonymization Guideline and the Challenge of Unstructured Data

HHS’ proposed HIPAA Amendment to Strengthen Cybersecurity in Healthcare and how Private AI can Support Compliance

Japan's Health Data Anonymization Act: Enabling Large-Scale Health Research

What the International AI Safety Report 2025 has to say about Privacy Risks from General Purpose AI

Private AI 4.0: Your Data’s Potential, Protected and Unlocked

How Private AI Facilitates GDPR Compliance for AI Models: Insights from the EDPB's Latest Opinion

Navigating the New Frontier of Data Privacy: Protecting Confidential Company Information in the Age of AI

Belgium’s Data Protection Authority on the Interplay of the EU AI Act and the GDPR

Enhancing Compliance with US Privacy Regulations for the Insurance Industry Using Private AI

Navigating Compliance with Quebec’s Act Respecting Health and Social Services Information Through Private AI’s De-identification Technology

Unlocking New Levels of Accuracy in Privacy-Preserving AI with Co-Reference Resolution

Strengthened Data Protection Enforcement on the Horizon in Japan

How Private AI Can Help to Comply with Thailand's PDPA

How Private AI Can Help Financial Institutions Comply with OSFI Guidelines

The American Privacy Rights Act – The Next Generation of Privacy Laws

How Private AI Can Help with Compliance under China’s Personal Information Protection Law (PIPL)

PII Redaction for Reviews Data: Ensuring Privacy Compliance when Using Review APIs

Independent Review Certifies Private AI’s PII Identification Model as Secure and Reliable

To Use or Not to Use AI: A Delicate Balance Between Productivity and Privacy

To Use or Not to Use AI: A Delicate Balance Between Productivity and Privacy

News from NIST: Dioptra, AI Risk Management Framework (AI RMF) Generative AI Profile, and How PII Identification and Redaction can Support Suggested Best Practices

Handling Personal Information by Financial Institutions in Japan – The Strict Requirements of the FSA Guidelines

日本における金融機関の個人情報の取り扱い - 金融庁ガイドラインの要件

Leveraging Private AI to Meet the EDPB’s AI Audit Checklist for GDPR-Compliant AI Systems

Who is Responsible for Protecting PII?

How Private AI can help the Public Sector to Comply with the Strengthening Cyber Security and Building Trust in the Public Sector Act, 2024

A Comparison of the Approaches to Generative AI in Japan and China

Updated OECD AI Principles to keep up with novel and increased risks from general purpose and generative AI

Is Consent Required for Processing Personal Data via LLMs?

The evolving landscape of data privacy legislation in healthcare in Germany

The CIO’s and CISO’s Guide for Proactive Reporting and DLP with Private AI and Elastic

The Evolving Landscape of Health Data Protection Laws in the United States

Comparing Privacy and Safety Concerns Around Llama 2, GPT4, and Gemini

How to Safely Redact PII from Segment Events using Destination Insert Functions and Private AI API

WHO’s AI Ethics and Governance Guidance for Large Multi-Modal Models operating in the Health Sector – Data Protection Considerations

How to Protect Confidential Corporate Information in the ChatGPT Era

Unlocking the Power of Retrieval Augmented Generation with Added Privacy: A Comprehensive Guide

Leveraging ChatGPT and other AI Tools for Legal Services

Leveraging ChatGPT and other AI tools for HR

Leveraging ChatGPT in the Banking Industry

Law 25 and Data Transfers Outside of Quebec

The Colorado and Connecticut Data Privacy Acts

Unlocking Compliance with the Japanese Data Privacy Act (APPI) using Private AI

Tokenization and Its Benefits for Data Protection

Private AI Launches Cloud API to Streamline Data Privacy

Processing of Special Categories of Data in Germany

End-to-end Privacy Management

Privacy Breach Reporting Requirements under Law25

Migrating Your Privacy Workflows from Amazon Comprehend to Private AI

A Comparison of the Approaches to Generative AI in the US and EU

Benefits of AI in Healthcare and Data Sources (Part 1)

Privacy Attacks against Data and AI Models (Part 3)

Risks of Noncompliance and Challenges around Privacy-Preserving Techniques (Part 2)

Enhancing Data Lake Security: A Guide to PII Scanning in S3 buckets

The Costs of a Data Breach in the Healthcare Sector and its Privacy Compliance Implications

Navigating GDPR Compliance in the Life Cycle of LLM-Based Solutions

What’s New in Version 3.8

How to Protect Your Business from Data Leaks: Lessons from Toyota and the Department of Home Affairs

New York's Acceptable Use of AI Policy: A Focus on Privacy Obligations

Safeguarding Personal Data in Sentiment Analysis: A Guide to PII Anonymization

Changes to South Korea’s Personal Information Protection Act to Take Effect on March 15, 2024

Australia’s Plan to Regulate High-Risk AI

How Private AI can help comply with the EU AI Act

Comment la Loi 25 Impacte l'Utilisation de ChatGPT et de l'IA en Général

Endgültiger Entwurf des Gesetzes über Künstliche Intelligenz – Datenschutzpflichten der KI-Modelle mit Allgemeinem Verwendungszweck

How Law25 Impacts the Use of ChatGPT and AI in General

Is Salesforce Law25 Compliant?

Creating De-Identified Embeddings

Exciting Updates in 3.7

EU AI Act Final Draft – Obligations of General-Purpose AI Systems relating to Data Privacy

FTC Privacy Enforcement Actions Against AI Companies

The CCPA, CPRA, and California's Evolving Data Protection Landscape

HIPAA Compliance – Expert Determination Aided by Private AI

Private AI Software As a Service Agreement

EU's Review of Canada's Data Protection Adequacy: Implications for Ongoing Privacy Reform

Acceptable Use Policy

ISO/IEC 42001: A New Standard for Ethical and Responsible AI Management

Reviewing OpenAI's 31st Jan 2024 Privacy and Business Terms Updates

Comparing OpenAI vs. Azure OpenAI Services

Quebec’s Draft Regulation Respecting the Anonymization of Personal Information

Version 3.6 Release: Enhanced Streaming, Auto Model Selection, and More in Our Data Privacy Platform

Brazil's LGPD: Anonymization, Pseudonymization, and Access Requests

LGPD do Brasil: Anonimização, Pseudonimização e Solicitações de Acesso à Informação

Canada’s Principles for Responsible, Trustworthy and Privacy-Protective Generative AI Technologies and How to Comply Using Private AI

Private AI Named One of The Most Innovative RegTech Companies by RegTech100

Data Integrity, Data Security, and the New NIST Cybersecurity Framework

Safeguarding Privacy with Commercial LLMs

Cybersecurity in the Public Sector: Protecting Vital Services

Privacy Impact Assessment (PIA) Requirements under Law25

Elevate Your Experience with Version 3.5

Fine-Tuning LLMs with a Focus on Privacy

GDPR in Germany: Challenges of German Data Privacy (Part 2)

Comply with US Executive Order on Safe, Secure, and Trustworthy Artificial Intelligence using Private AI

How to Comply with EU AI Act using PrivateGPT

Navigating the Privacy Paradox: A Guide to Ethical Fine-Tuning of Large Language Models

Adding Privacy to LangChain with Private AI