ai_mask function
Applies to: Databricks SQL
Databricks Runtime
This functionality is in Public Preview and HIPAA compliant.
During the preview:
- The underlying language model can handle several languages, but this AI Function is tuned for English.
- See Features with limited regional availability for AI Functions region availability.
The ai_mask() function uses an AI model to mask specified entities in a given text using SQL. Use it to redact sensitive values inside free text, such as support tickets, call transcripts, agent traces, and text extracted from documents, so the rest of the text stays usable.
To redact sensitive data in agent traces end to end, see Govern and redact traces in Unity Catalog.
Databricks recommends version 2.0 for new queries. It labels each masked value with its classifier, such as [NAME], and reports an error message for each row that fails. To use it, pass options => map('version', '2.0') and read the masked text from the response field:
> SELECT ai_mask(ticket_text, options => map('version', '2.0')):response::string AS masked_text
FROM support_tickets;
Version 1.0 vs. version 2.0
The function has two versions. Version 1.0 is the default. To use version 2.0, pass options => map('version', '2.0'). A call without that option runs version 1.0. If you pass classifier names without it, version 1.0 reads them as labels and returns [MASKED] text.
Version 2.0 differs from version 1.0 as follows:
- It masks sensitive data with a Databricks-built detection model. Version 1.0 uses a Llama chat model served by Databricks Foundation Model APIs.
- It takes an optional list of system-defined classifiers, with an 18-classifier default set and 90 supported classifiers, listed under Supported classifiers. Version 1.0 takes free-text labels.
- It replaces each detected value with its classifier placeholder, such as
[NAME], and numbers several values of one classifier in a row, such as[NAME_1]and[NAME_2]. Version 1.0 replaces every detected value with[MASKED]. - It returns a
VARIANTthat carries the masked text, the version, and a per-row error message. Version 1.0 returns aSTRING. See Returns.
Version 2.0 is in Beta. For the regions and compliance standards it supports, see Requirements. Version 1.0 is in Public Preview and HIPAA compliant.
Requirements
Model licenses
The underlying models that might be used at this time include Databricks-proprietary models (version 2.0), and models licensed under Llama Community License (version 1.0). Customers are responsible for ensuring compliance with applicable model licenses where made available. Databricks recommends reviewing these licenses to ensure compliance with any applicable terms. If models emerge in the future that perform better according to Databricks's internal benchmarks, Databricks might change the model (and the list of applicable licenses provided on this page).
- This function is only available on workspaces in regions that support AI Functions optimized for batch inference.
- This function is not available on Databricks SQL Classic.
- Databricks Runtime 15.4 LTS or above is required. For an upcoming change to this requirement, see AI Functions require Databricks Runtime 17.3 LTS or above. Databricks Runtime 18.2 or above is recommended for the best performance and access to the latest features.
- Check the Databricks SQL pricing page.
- Version 2.0 is available in the regions that the region table lists for
ai_maskv2. In the regions that the table marks with ⥂, version 2.0 works only when cross-Geo processing is enabled. - For workspaces with the Enhanced Security and Compliance add-on, see regional support for
ai_maskv2 for the appropriate compliance standard. - A workspace admin enables the version 2.0 Beta on the Previews page. See Manage Databricks previews.
Syntax
- Version 2.0
- Version 1.0
ai_mask(content [, classifiers], options => map('version', '2.0'))
ai_mask(content, labels [, options])
Arguments
- Version 2.0
- Version 1.0
content: ASTRINGexpression.classifiers: Optional. AnARRAY<STRING>of classifier names such asarray('NAME', 'EMAIL_ADDRESS'). Omit it, or passNULL, to use the default set. Classifier names are case-insensitive. An explicitly empty array fails the query, and an unknown classifier name fails the query.options: AMAP<STRING, STRING>containing configuration options. Required for version 2.0:version: Set to"2.0". If you omit it, the function runs version 1.0, the default.
Supported classifiers
The default classifier set applies when you pass no classifier list or NULL. It contains these 18 classifiers: NAME, EMAIL_ADDRESS, PHONE_NUMBER, STREET_ADDRESS, DATE_OF_BIRTH, AGE, US_SSN, US_ITIN, PASSPORT, DRIVER_LICENSE, CREDIT_CARD, CARD_SECURITY_CODE, CARD_EXPIRATION_DATE, CARD_PIN, BANK_NUMBER, IBAN_CODE, IP_ADDRESS, and SECRET.
Version 2.0 accepts 90 classifiers in total. Expand the table for all of them, with descriptions. All supported classifiers Classifier Description A person's name, such as first, middle, or last names, titles, suffixes, or nicknames. An email address conforming to RFC-822. A phone number pattern, such as an area code, prefix, line number, or country code. A street address: house or building number, street name, and unit. Birth dates of individuals. Age of individuals. A US Social Security number (SSN) containing 9 digits. A US Individual Taxpayer Identification Number (ITIN) starting with “9” and having "7" or "8" as the fourth digit. A passport number from any country. A driver license number from any country. A credit card number containing 12-19 digits. A card security code, such as a CVV or CVC, used for authentication in payment card transactions. A payment card expiration date indicating when a credit or debit card expires. A Personal Identification Number (PIN) used to authenticate payment card or ATM transactions. A bank account number from any country. An International Bank Account Number (IBAN). An IPv4 or IPv6 address. Cryptographic secrets including passwords, API keys, authentication tokens, cloud credentials, private keys, and encryption keys. Geographic coordinates (latitude and longitude) used to specify a location on Earth. A medical provider credential identifier, such as a US National Provider Identifier (NPI, a 10-digit CMS/NPPES number) or a state-issued medical license number. A Uniform Resource Locator (URL) used to specify the address of a resource on the internet. A 17-character Vehicle Identification Number (VIN) used to uniquely identify motor vehicles. Vehicle registration plate numbers. A Media Access Control (MAC) address: a 48-bit hardware identifier for network interfaces. An International Mobile Equipment Identity (IMEI): a 15-digit number uniquely identifying a mobile device. Racial or ethnic origin. Marital or civil partnership status. Sexual orientation. Criminal convictions, offences, or background check results. Health or medical information about an individual, including diagnoses, conditions, treatments, or medications. Biometric identifiers used to uniquely identify an individual, such as fingerprints, facial scans, iris/retina scans, or voiceprints. Genetic data, including DNA/RNA sequences, genotype, or genetic markers of an individual. Religious or philosophical beliefs of an individual, including religion, denomination, faith, or creed. Political opinions or affiliations of an individual, including party membership, political views, or ideology. Trade union or labor union membership of an individual. A US bank account number containing 8-17 digits. A US driver license number following https://ntsi.com/drivers-license-format/ A US passport number containing a letter followed by 8 digits. A UK National Health Service (NHS) number containing 10 digits. A UK National Insurance Number (NINO) following the format: 2 letters, 6 digits, 1 letter. A UK Unique Taxpayer Reference (UTR), 10 digits. A German National ID Card number (Personalausweis) containing 9 alphanumeric characters. A German Social Security Number (Sozialversicherungsnummer) containing 12 alphanumeric characters. A German Tax Identification Number (Steueridentifikationsnummer) containing 11 digits. An Australian Tax File Number (TFN) containing 8 or 9 digits. An Australian Medicare card number containing 10 or 11 digits. A Brazilian CPF (Cadastro de Pessoas Físicas): individual taxpayer identification number. A Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica): business/company tax identification number. A Brazilian RG (Registro Geral): individual state identification number. A Brazilian PIS/PASEP/NIS social-identification number: 11 digits with a Mod-11 check digit. A Brazilian Título de Eleitor (voter registration) number: 12 digits with two check digits; digits 9–10 encode the issuing state. A Brazilian Cartão Nacional de Saúde (CNS / SUS health card) number: 15 digits beginning with 1, 2, 7, 8, or 9, validated by a Mod-11 weighted-sum rule. An Indian Aadhaar number: a 12-digit unique identification number issued by UIDAI. An Indian Permanent Account Number (PAN): a 10-character alphanumeric tax identifier. An Indian Voter ID (EPIC): a 10-character identifier (3 letters + 7 digits) issued by the Election Commission. An India EPFO Universal Account Number (UAN): a 12-digit EPFO identifier linking provident-fund/pension accounts. An India Employee State Insurance (ESI/ESIC) number: a 10-digit Insured Person (IP) number. A Canadian Social Insurance Number (SIN): a 9-digit identifier with Luhn check digit. A Canadian provincial health card number: format varies by province (Ontario OHIP, Quebec RAMQ, and 9-digit formats used by BC, AB, SK, MB, NB, NS, YT, NU). A Canadian Permanent Resident (PR) Card number: two letters followed by 7 or 10 digits. A Japan Individual Number (My Number / マイナンバー): a 12-digit national identification and tax number with a Mod-11 check digit. A Japan Basic Pension Number (基礎年金番号): a 10-digit national-pension identifier, formatted XXXX-XXXXXX. An Italian fiscal code (Codice Fiscale): a 16-character alphanumeric tax/identity code composed of 3 surname letters, 3 first-name letters, a 2-digit birth year, a month letter, a 2-digit birth day (+40 for females), a 4-character birthplace code, and a final check letter. Also the Tessera Sanitaria and INPS identifier. An Italian VAT number (Partita IVA): 11 digits (7-digit taxpayer code + 3-digit office code + 1 Luhn check digit). An Italian identity card number. Identifiers for medical devices, including FDA Unique Device Identifiers (UDI) and their GS1/HIBCC/ICCBBA device-identifier components, such as a GTIN-14, plus device-specific serial or lot numbers such as implant or pacemaker serials. Scoped to medical devices only. A Medical Record Number (MRN): a provider-assigned internal unique identifier for a patient's medical record within a hospital or health system. A health plan beneficiary number: a health insurance member or subscriber identifier, including the US Medicare Beneficiary Identifier (MBI), Medicaid IDs, and commercial insurer member IDs. A clinical date related to an individual: admission date, discharge date, or date of death. A Dutch citizen service number (BSN / burgerservicenummer), 8 or 9 digits. A French social security number (NIR / numéro de sécurité sociale), 15 digits. A French tax identification number (numéro fiscal / SPI), 13 digits. A French national identity card number (CNI / CNIe). A Spanish national identity number (DNI / NIF). A Spanish foreigner identity number (NIE). A Spanish company tax identification number (NIF). A Swiss social security number (AHV / AVS), 13 digits starting 756. A Swedish personal identity number (personnummer / samordningsnummer). A Norwegian national identity number (fødselsnummer), 11 digits. A Norwegian D-number (temporary identity number), 11 digits. A Danish civil registration number (CPR-nummer), 10 digits. Magnetic stripe track data from a payment card, containing encrypted or obfuscated card information. A SWIFT code (ISO 9362 Bank Identifier Code) used for international bank transfers and payment routing. A credit score or creditworthiness rating assigned to an individual or entity by a financial institution. Compensation or salary information for an individual, including wages, salaries, bonuses, and other forms of remuneration. Employment status information indicating whether an individual is employed, unemployed, or in another employment state. A postal or ZIP code. A city, town, or municipality name. A country name. A state or province name or code.NAMEEMAIL_ADDRESSPHONE_NUMBERSTREET_ADDRESSDATE_OF_BIRTHAGEUS_SSNUS_ITINPASSPORTDRIVER_LICENSECREDIT_CARDCARD_SECURITY_CODECARD_EXPIRATION_DATECARD_PINBANK_NUMBERIBAN_CODEIP_ADDRESSSECRETGEO_COORDINATESMEDICAL_LICENSEURLVINLICENSE_PLATEMAC_ADDRESSIMEIETHNICITYMARITAL_STATUSSEXUAL_ORIENTATIONCRIMINAL_BACKGROUNDHEALTH_DATABIOMETRIC_DATAGENETIC_DATARELIGIOUS_BELIEFPOLITICAL_OPINIONTRADE_UNION_MEMBERSHIPUS_BANK_NUMBERUS_DRIVER_LICENSEUS_PASSPORTUK_NHSUK_NINOUK_UTRDE_ID_CARDDE_SVNRDE_TAX_IDAU_TFNAU_MEDICAREBR_CPFBR_CNPJBR_RGBR_PISBR_TITULO_ELEITORBR_CNSIN_AADHAARIN_PANIN_VOTER_IDIN_UANIN_ESICCA_SOCIAL_INSURANCE_NUMBERCA_HEALTH_NUMBERCA_PR_CARDJP_MY_NUMBERJP_PENSION_NUMBERIT_CODICE_FISCALEIT_PARTITA_IVAIT_ID_CARDMEDICAL_DEVICE_IDMEDICAL_RECORD_NUMBERHEALTH_PLAN_BENEFICIARY_NUMBERMEDICAL_DATENL_BSNFR_NIRFR_TAX_IDFR_ID_CARDES_DNIES_NIEES_BUSINESS_TAX_IDCH_AHVSE_PERSONNUMMERNO_FODSELSNUMMERNO_D_NUMBERDK_CPRCARD_TRACK_DATASWIFT_CODECREDIT_SCORECOMPENSATIONEMPLOYMENT_STATUSPOSTAL_CODECITYCOUNTRYPROVINCE
Version 1.0 is the earlier version. Use it only where version 2.0 isn't available.
content: ASTRINGexpression.labels: AnARRAY<STRING>literal. Each element is a short, plain-language description of a type of information to mask, such as'person'or'email'.options: An optionalMAP<STRING, STRING>containing configuration options:version: Version switch to support migration ("1.0", the default, or"2.0").
Returns
- Version 2.0
- Version 1.0
A VARIANT containing:
{
"response": "[NAME] lives in New York. His email is [EMAIL_ADDRESS].",
"metadata": {
"version": "2.0"
},
"error_message": null
}
response: The content with each detected value replaced by its classifier placeholder. A placeholder is the classifier name in uppercase brackets, such as[NAME]or[EMAIL_ADDRESS]. When a row contains several distinct values for one classifier, the placeholders are numbered in order of first appearance, such as[NAME_1]and[NAME_2]. Repeated identical text reuses its placeholder. Overlapping detected spans form one placeholder.metadata.version: The version that produced the result,"2.0".error_message:nullwhen the row succeeded. When the detection call for a row fails, such as a service error or a timeout after retries,responseisnullanderror_messagedescribes the failure. The query continues with the remaining rows.
To work with the masked text as a STRING, read the response field, for example masked:response::string.
NULL or empty content returns a result whose response and error_message are both null.
For how version 2.0 handles failures, see Error conditions.
A STRING where each detected entity that matches one of the labels is replaced with [MASKED]. The replacement text is the same for every label. To get a placeholder that names each classifier, and an error message for each row that fails, use version 2.0, which Databricks recommends for new queries.
If content is NULL, the result is NULL.
Examples
- Version 2.0
- Version 1.0
The following examples use version 2.0 to mask personal information (PII), such as names, email addresses, and phone numbers, in text. Databricks recommends version 2.0 for new queries. Because the model detects the values, results can vary.
To mask a text column and get the masked text as a STRING, read the response field of the result:
> SELECT
ticket_id,
ai_mask(ticket_text, array('NAME', 'EMAIL_ADDRESS', 'PHONE_NUMBER'), options => map('version', '2.0')):response::string AS masked_text
FROM support_tickets;
To mask names and email addresses in a literal, run the following:
> SELECT ai_mask(
'John Doe lives in New York. His email is john.doe@example.com.',
array('NAME', 'EMAIL_ADDRESS'),
options => map('version', '2.0')
);
{
"response": "[NAME] lives in New York. His email is [EMAIL_ADDRESS].",
"metadata": {"version": "2.0"},
"error_message": null
}
When a row contains several values for one classifier, each value gets a numbered placeholder:
> SELECT ai_mask(
'Contact Ana Lopez or Ben Ortiz at ana@example.com or ben@example.com.',
array('NAME', 'EMAIL_ADDRESS'),
options => map('version', '2.0')
);
{
"response": "Contact [NAME_1] or [NAME_2] at [EMAIL_ADDRESS_1] or [EMAIL_ADDRESS_2].",
"metadata": {"version": "2.0"},
"error_message": null
}
To use the default classifiers, pass no classifier list:
> SELECT ai_mask(
'SSN 123-45-6789.',
options => map('version', '2.0')
);
{
"response": "SSN [US_SSN].",
"metadata": {"version": "2.0"},
"error_message": null
}
To get the masked text as a STRING, read the response field of the result:
> SELECT masked:response::string AS masked_text
FROM (
SELECT ai_mask(
'John Doe lives in New York.',
array('NAME'),
options => map('version', '2.0')
) AS masked
);
"[NAME] lives in New York."
Use version 1.0 only where version 2.0 isn't available. Otherwise use version 2.0, which you call the same way: pass classifier names such as NAME, EMAIL_ADDRESS, and PHONE_NUMBER instead of labels, add options => map('version', '2.0'), and read the masked text with :response::string. See the version 2.0 examples.
The following examples use version 1.0, which replaces every detected value with [MASKED]. Because an AI model detects the entities, results can vary.
> SELECT ai_mask(
'John Doe lives in New York. His email is john.doe@example.com.',
array('person', 'email')
);
"[MASKED] lives in New York. His email is [MASKED]."
> SELECT ai_mask(
'Contact me at 555-1234 or visit us at 123 Main St.',
array('phone', 'address')
);
"Contact me at [MASKED] or visit us at [MASKED]"
To mask government IDs, payment details, and dates of birth, pass a label for each type:
> SELECT ai_mask(
'SSN 123-45-6789, card 4111 1111 1111 1111, born on March 3, 1985.',
array('ssn', 'credit card number', 'date of birth')
);
"SSN [MASKED], card [MASKED], born on [MASKED]."
To mask network identifiers, such as IP addresses and URLs, run the following:
> SELECT ai_mask(
'Login from 192.168.1.10 failed. See https://internal.example.com/logs for details.',
array('ip address', 'url')
);
"Login from [MASKED] failed. See [MASKED] for details."
To mask every row of a table column, call ai_mask in a query:
> SELECT
ticket_id,
ai_mask(ticket_text, array('person', 'email', 'phone', 'account number')) AS masked_text
FROM support_tickets;
Limitations
This function is not available on Databricks SQL Classic.
For the errors the function returns, see Error conditions.
Error conditions
- Version 2.0
- Version 1.0
In these cases, the query fails before any row runs with AI_FUNCTION_COMPILATION_ERROR, and the error message includes the text shown:
versioninoptionsisn't in themajor.minorformat, such as'2'. The error isInvalid version: <value>, expected a string in the format of major.minor.versioninoptionsnames a version the function doesn't have. The error isVersion <value> is not supported. Supported versions: <versions>.- Version 2.0 isn't enabled for the workspace. The error is
ai_mask version 2.0 is not enabled for this workspace.A workspace admin enables the version 2.0 Beta on the Previews page. See Manage Databricks previews. - A classifier name isn't one of the supported classifiers. The error is
Invalid ai_mask classifiers: unknown system classifier: <names>.orInvalid ai_mask classifiers: unsupported system classifier: <names>.Classifier names are case-insensitive. classifiersis an empty array. The error isThe classifiers parameter must contain at least 1 classifier.
When version 2.0 isn't available to the workspace, such as in a region the region table doesn't list, the query fails when it starts.
When the detection call for a row fails, that row returns a null response and an error_message, and the query continues with the remaining rows. Filter on error_message to find rows that weren't masked. A null response alone doesn't mean the text contains no sensitive data. Common error_message values include the following:
Rate limit exceeded after several retries. Try again later.The request timed out. Try again later.A connection error occurred after several retries. Try again later.The service was unavailable after several retries. Try again later.Sensitive data detection failed for this row. Try again.An unexpected error occurred. Try again later.
A NULL or empty content isn't an error. See Returns.
The query fails before any row runs when labels has no labels or more than 20 labels, or contains a NULL, an empty string, or a label longer than 50 characters.
When the model call for a row fails, or its answer can't be read, that row returns NULL and the query continues with the remaining rows. A NULL result doesn't mean the text contains no matching entities.