ai newsFr., 4. Dez.
EilmeldungAlibaba Releases Qwen4-35B-A3B: Open-Weight MoE Model With 1M Context

Redact before you prompt: a fail-closed pre-processor for call transcripts in Python

This article was created with the help of AI and the code was run and tested before publishing (Python 3.13, standard library only). Sending call transcripts to an LLM for QA scoring, summaries or theme analysis is now routine. The transcript is also where everything the customer said ends up: emai

dev.toDonnerstag 19:20 · 03.12.8 Min. Lesezeit
Bild: dev.to

This article was created with the help of AI and the code was run and tested before publishing (Python 3.13, standard library only).

Sending call transcripts to an LLM for QA scoring, summaries or theme analysis is now routine. The transcript is also where everything the customer said ends up: email addresses, callback numbers, and on payment calls, card numbers and security codes read out loud.

Two pieces of official guidance frame the problem:

Managed redaction exists (for example Amazon Transcribe and the open-source Presidio), but both are explicit that it's not perfect. Amazon's docs: it "may not identify and remove all instances of sensitive data." Presidio: "no guarantee that Presidio will find all sensitive information… additional systems and protections should be employed."

So this tutorial builds a small, deterministic pre-processor that sits between your transcript store and your model, designed around one rule: if it isn't sure, it doesn't send. It complements a real PII detector rather than replacing one.

redact_for_ai.py (standard library only):

"""Minimise and redact a call transcript before it is sent to an AI model. Illustrative tutorial code, not a compliance tool. Pattern-based redaction misses things; treat the residual check and human review as part of the design.

Pipeline: 1. normalise spoken digits ("four one one one" -> "4111") so they can be detected 2. excise payment segments entirely (prefer removing over spot-redacting) 3. redact remaining identifiers with typed placeholders 4. keep only the metadata fields the stated purpose needs 5. residual scan: if anything still looks like a long number, quarantine 6. attach a delete_after date from a per-purpose retention policy """ from __future__ import annotations import json import re import sys from collections import Counter from datetime import date, timedelta DIGIT_WORDS = { "zero": "0", "oh": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9" } _TOKEN = r "(?:\d+|" + "|". join ( DIGIT_WORDS ) + r ")" # three or more digit-ish tokens in a row, separated by spaces/commas/dashes/dots SPOKEN_RUN = re. compile ( rf "\b{_TOKEN}(?:[\s,.\-]+{_TOKEN}){{2,}}\b", re. IGNORECASE ) PAYMENT_OPEN = re. compile ( r "card number|security code|\bcvv\b|\bcvc\b|expir|" r "back of the card|long number on", re. IGNORECASE ) PAYMENT_CLOSE = re. compile ( r "\bapproved\b|went through|\bprocessed\b|payment is complete", re.

IGNORECASE ) MAX_PAYMENT_TURNS = 6 EMAIL = re. compile ( r "\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b" ) PHONE = re. compile ( r "(?<!\d)(?:\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}(?!\d)" ) LONG_NUMBER = re. compile ( r "(?<!\d)(?:\d[\s-]?){12,18}\d(?!\d)" ) ANY_DIGITS_7 = re. compile ( r "(?:\d[\s-]?){6,}\d" ) # Illustrative retention periods only; set real values with your legal/privacy owner. RETENTION_DAYS = { "qa_scoring": 90, "coaching": 90, "trend_reporting": 30 } # Metadata each purpose may keep. Everything else is dropped before the AI sees it.

METADATA_ALLOWLIST = { "qa_scoring": { "call_id", "call_date", "queue", "agent_id", "duration_s" }, "coaching": { "call_id", "call_date", "agent_id" }, "trend_reporting": { "call_id", "call_date", "queue" }, } def luhn_ok ( digits: str ) -> bool: total, parity = 0, len ( digits ) % 2 for i, ch in enumerate ( digits ): d = int ( ch ) if i % 2 == parity: d *= 2 if d > 9: d -= 9 total += d return total % 10 == 0 def normalise_spoken_digits ( text: str ) -> str: def join ( m: re. Match ) -> str: parts = re. split ( r "[\s,.\-]+", m. group ( 0 ) ) return "". join ( DIGIT_WORDS. get ( p. lower ( ), p ) for p in parts ) return SPOKEN_RUN. sub ( join, text ) def redact_text ( text: str, counts: Counter ) -> str: text = normalise_spoken_digits ( text ) def sub ( pattern, label, value_check = None ): nonlocal text def repl ( m ): if value_check and not value_check ( m. group ( 0 ) ): return m. group ( 0 ) counts [ label ] += 1 return f "[{label}]" text = pattern. sub ( repl, text ) sub ( EMAIL, "EMAIL" ) sub ( LONG_NUMBER, "CARD_NUMBER", lambda s: luhn_ok ( re. sub ( r "\D", "", s ) ) ) sub ( PHONE, "PHONE" ) sub ( LONG_NUMBER, "LONG_NUMBER" ) # long numbers that failed the Luhn check return text def excise_payment_segments ( turns: list [ dict ], counts: Counter ) -> list [ dict ]: out, i = [ ], 0 while i < len ( turns ): if PAYMENT_OPEN. search ( normalise_spoken_digits ( turns [ i ] [ "text" ] ) ): j = i while j < len ( turns ) and j - i < MAX_PAYMENT_TURNS: if PAYMENT_CLOSE. search ( turns [ j ] [ "text" ] ): break j += 1 end = min ( j, len ( turns ) - 1 ) n = end - i + 1 counts [ "PAYMENT_TURNS_REMOVED" ] += n out. append ( { "speaker": "system", "text": f "[payment segment removed: {n} turns]" } ) i = end + 1 else: out. append ( turns [ i ] ) i += 1 return out def prepare ( call: dict, purpose: str ) -> dict: if purpose not in METADATA_ALLOWLIST: raise ValueError ( f "unknown purpose {purpose!r}: define it before processing calls" ) counts: Counter = Counter ( ) turns = excise_payment_segments ( call [ "turns" ], counts ) turns = [ { "speaker": t [ "speaker" ], "text": redact_text ( t [ "text" ], counts ) } for t in turns ] meta = { k: v for k, v in call [ "metadata" ]. items ( ) if k in METADATA_ALLOWLIST [ purpose ] } dropped = sorted ( set ( call [ "metadata" ] ) - set ( meta ) ) residual = [ idx for idx, t in enumerate ( turns ) if ANY_DIGITS_7. search ( t [ "text" ] ) ] status = "QUARANTINE_FOR_REVIEW" if residual else "READY_FOR_AI" delete_after = ( date. fromisoformat ( call [ "metadata" ] [ "call_date" ] ) + timedelta ( days = RETENTION_DAYS [ purpose ] ) ). isoformat ( ) return { "status": status, "purpose": purpose, "delete_after": delete_after, "metadata": meta, "turns": turns, # audit record: counts and field names only, never the raw values "audit": { "redactions": dict ( sorted ( counts. items ( ) ) ), "metadata_dropped": dropped, "residual_turns": residual }, } if __name__ == "__main__": path = sys. argv [ 1 ] if len ( sys. argv ) > 1 else "sample_call.json" purpose = sys. argv [ 2 ] if len ( sys. argv ) > 2 else "qa_scoring" with open ( path ) as f: result = prepare ( json. load ( f ), purpose ) print ( json. dumps ( result, indent = 2 ) ) sys. exit ( 0 if result [ "status" ] == "READY_FOR_AI" else 1 ) Enter fullscreen mode Exit fullscreen mode A few details worth calling out:

sample_call.json is an invented billing call: the customer confirms an email, reads out the standard 4111… test card number and a security code, then leaves a callback number. Running python3 redact_for_ai.py sample_call.json qa_scoring prints (exit code 0):

{ "status": "READY_FOR_AI", "purpose": "qa_scoring", "delete_after": "2027-02-11", "metadata": { "call_id": "demo-0001", "call_date": "2026-11-13", "queue": "billing", "agent_id": "a-17", "duration_s": 412 }, "turns": [ { "speaker": "agent", "text": "Thanks for calling billing. Can I confirm the email on the account?" }, { "speaker": "customer", "text": "Sure, it's [EMAIL]. I was charged twice for October." }, { "speaker": "system", "text": "[payment segment removed: 5 turns]" }, { "speaker": "customer", "text": "Great.

If anything else comes up, call me on [PHONE]." }, { "speaker": "agent", "text": "Will do. You'll get a confirmation email within the hour." } ], "audit": { "redactions": { "EMAIL": 1, "PAYMENT_TURNS_REMOVED": 5, "PHONE": 1 }, "metadata_dropped": [ "account_number", "caller_number", "customer_name" ], "residual_turns": [ ] } } Enter fullscreen mode Exit fullscreen mode The five payment turns (from the agent's request for the card number to the payment confirmation) collapse into one line. Notice the cost: the agent's refund explanation sat inside that window and was removed too.

That's the over-redaction trade-off. If your QA scorecard needs that content, fix it upstream (take payment in a separate step, or pause recording only for the digits) rather than loosening the redaction.

If we append a turn like "my member number is 44-17-22-90", nothing matches a specific rule, but the residual scan catches eight digits and the status flips to QUARANTINE_FOR_REVIEW with residual_turns:. That is the behaviour you want: a person looks at it before any model does.

test_redact_for_ai.py pins both the guarantees and the known gaps:

test_card_vs_other_long_number (test_redact_for_ai.TestHelpers.test_card_vs_other_long_number)... ok test_email_and_phone (test_redact_for_ai.TestHelpers.test_email_and_phone)... ok test_luhn (test_redact_for_ai.TestHelpers.test_luhn)... ok test_spoken_digits (test_redact_for_ai.TestHelpers.test_spoken_digits)... ok test_cvv_outside_payment_window_is_a_known_gap (test_redact_for_ai.TestPrepare.test_cvv_outside_payment_window_is_a_known_gap)... ok test_labels_are_best_effort (test_redact_for_ai.TestPrepare.test_labels_are_best_effort)... ok test_metadata_allowlist (test_redact_for_ai.TestPrepare.test_metadata_allowlist)... ok test_payment_segment_removed (test_redact_for_ai.TestPrepare.test_payment_segment_removed)... ok test_purpose_changes_fields (test_redact_for_ai.TestPrepare.test_purpose_changes_fields)... ok test_ready_and_no_raw_values (test_redact_for_ai.TestPrepare.test_ready_and_no_raw_values)... ok test_residual_number_quarantines (test_redact_for_ai.TestPrepare.test_residual_number_quarantines)... ok test_retention_date (test_redact_for_ai.TestPrepare.test_retention_date)... ok test_unknown_purpose_rejected (test_redact_for_ai.TestPrepare.test_unknown_purpose_rejected)... ok ---------------------------------------------------------------------- Ran 13 tests in 0.002s OK Enter fullscreen mode Exit fullscreen mode Two tests are deliberately about limitations:

The pattern generalises beyond calls to tickets, chats and emails: normalise, remove whole sensitive segments, redact, allowlist, and fail closed on anything left over. It's a few dozen lines of code, and it means the question "did the model ever see that card number?" has a testable answer.

Not legal advice. Check payment-security and privacy obligations for your own jurisdiction and contracts.

Quelle: dev.to (dev.to). Original öffnen