Privacy with LLMs and synthetic data
You can ask an LLM to write a data analysis script without giving it the records the script will eventually analyze. Give it an invented table with the columns, types, missing values, and relationships the code needs, then run the reviewed code against the real data inside your approved environment.
For example, a script that compares a laboratory measurement between two groups needs a numeric measurement and a group column. It does not need patient names, contact details, or the original measurements to implement that operation. If the failure involves repeated visits, the invented table must contain repeated visits. An example that omits the condition that causes the error will not help reproduce it.
Choose what the example needs to preserve
Section titled “Choose what the example needs to preserve”There are different ways to replace sensitive data, and they expose different information.
| Approach | What the example contains | What you must review |
|---|---|---|
| Invent records from a specification. | You choose the columns, categories, ranges, and edge cases without reading real rows. | Column names and category labels can still disclose a confidential project. |
| Generate values from an existing table. | The generator can retain its types, category frequencies, ranges, or missingness. | These properties can disclose information even when no complete row is copied. |
| Replace identifiers in existing rows. | The measurements and combinations of attributes remain. | Removing names alone does not make the records anonymous. |
For code development, start with an invented specification. Use properties derived from real data only when the task needs them and your organization permits their release. A rare diagnosis, an exact date, and a location can identify a person in combination even if each column looks harmless on its own.
Keep the original data outside the agent’s environment
Section titled “Keep the original data outside the agent’s environment”A local terminal does not imply local model inference. Claude Code, for example, sends prompts and model responses over the network when it uses a hosted model. Its documentation also describes local session transcripts. Files, terminal output, and error messages can become part of a session. See Claude Code data usage.
Prepare the example in your approved local environment before starting a hosted coding session. Give the agent a separate directory containing only the reviewed example and code. Enforce access limits with filesystem permissions or a container that mounts only that directory. Starting in another directory alone does not prevent an agent with shell access from reading elsewhere.
An instruction in AGENTS.md, a deny rule for one tool, or a .gitignore entry
does not replace that access boundary. A shell command can read a file that Git
ignores. Also review notebook outputs, plots, stack traces, paths, database connection
strings, and exported schema descriptions before they enter a prompt.
Use one invented specification in R and Python
Section titled “Use one invented specification in R and Python”Both examples below read the same contract.json, shown in full here.
Every value in this specification is invented. The bounds are test inputs, not
estimates from a study, and marker has arbitrary units.
{ "n_rows": 12, "columns": ["subject_id", "group", "age", "marker"], "groups": ["control", "treated"], "age_min": 25, "age_max": 70, "marker_min": 0.0, "marker_max": 10.0}The examples deliberately include two missing measurements and unique synthetic identifiers. Both generate the same table structure, but they do not generate the same values. Their random number generators differ, and matching invented measurements would add no privacy protection.
The companion container supplies FakeDataR 0.2.2 and Faker 40.43.0. Run the code
from its guide directory so that contract.json is available. The R example runs
in Podman, and the Python example runs through uv inside the same image. Neither
example calls an LLM or needs network access during execution.
R with FakeDataR
Section titled “R with FakeDataR”FakeDataR generates a table from another table’s structure. Here, that starting table is also invented. It contains dummy identifiers, dummy email addresses, and a note column so that the example can demonstrate explicit removal of fields the analysis does not need.
library(FakeDataR)
contract <- jsonlite::fromJSON("contract.json")dir.create("outputs", showWarnings = FALSE)
template <- data.frame( source_id = c("DUMMY_A", "DUMMY_B"), email = c("a@example.invalid", "b@example.invalid"), notes = c("Invented note A", "Invented note B"), group = factor(contract$groups, levels = contract$groups), age = as.integer(c(contract$age_min, contract$age_max)), marker = c(contract$marker_min, contract$marker_max))
synthetic <- generate_fake_with_privacy( data = template, n = contract$n_rows, level = "low", seed = 42, sensitive = c("source_id", "email", "notes"), sensitive_detect = FALSE, sensitive_strategy = "drop", normalize = FALSE)synthetic$subject_id <- sprintf("SYN_%03d", seq_len(nrow(synthetic)))synthetic <- synthetic[contract$columns]synthetic$marker <- round(synthetic$marker, 2)synthetic$marker[c(3, 9)] <- NA_real_print(head(synthetic), row.names = FALSE) subject_id group age marker SYN_001 treated 69 6.76 SYN_002 treated 53 9.83 SYN_003 control 40 NA SYN_004 control 41 5.66 SYN_005 treated 43 8.50 SYN_006 treated 60 1.89The low preset keeps category labels and uses the input numeric ranges. Those
properties are acceptable here because the template is invented. They would need
review if the template came from a real study. Naming sensitive columns explicitly
also makes the intended removal visible; automatic name detection cannot decide
whether a clinical note or a project code is confidential. The package documents
the presets in its privacy vignette.
Check the required columns, identifier uniqueness, types, bounds, and missing measurements before export. These checks test the example’s suitability for code development. They do not test whether a real dataset is anonymous.
stopifnot( identical(names(synthetic), contract$columns), nrow(synthetic) == contract$n_rows, anyDuplicated(synthetic$subject_id) == 0L, all(grepl("^SYN_[0-9]{3}$", synthetic$subject_id)), is.factor(synthetic$group), all(as.character(synthetic$group) %in% contract$groups), is.integer(synthetic$age), all(synthetic$age >= contract$age_min), all(synthetic$age <= contract$age_max), is.numeric(synthetic$marker), all(synthetic$marker >= contract$marker_min, na.rm = TRUE), all(synthetic$marker <= contract$marker_max, na.rm = TRUE), sum(is.na(synthetic$marker)) == 2L)
write.csv(synthetic, "outputs/synthetic_r.csv", row.names = FALSE, na = "")metrics <- list( rows = nrow(synthetic), columns = ncol(synthetic), missing_marker = sum(is.na(synthetic$marker)), unique_ids = length(unique(synthetic$subject_id)))jsonlite::write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE)cat("Rows: ", metrics$rows, "\n", sep = "")cat("Columns: ", metrics$columns, "\n", sep = "")cat("Missing marker values: ", metrics$missing_marker, "\n", sep = "")cat("Unique synthetic IDs: ", metrics$unique_ids, "\n", sep = "")Rows: 12Columns: 4Missing marker values: 2Unique synthetic IDs: 12Export only the reviewed table. FakeDataR objects can contain attributes such as
name_map, which maps original column names to output names. Review these before
you share an R object or a generated bundle. A CSV does not carry these R attributes,
but its column names and cell values still need review.
Why the highest preset is not a privacy guarantee
Section titled “Why the highest preset is not a privacy guarantee”FakeDataR 0.2.2 maps level = "high" to
numeric_mode = "distribution". The package defines this mode as sampling
observed values with replacement. The following example checks whether each
generated numeric value occurs in its invented source. See the
generator reference.
invented_source <- data.frame(marker = c(1001.25, 2003.5, 3007.75))high_example <- generate_fake_with_privacy( invented_source, n = 12, level = "high", seed = 42, sensitive_detect = FALSE, normalize = FALSE)reused_values <- sum(high_example[[1]] %in% invented_source$marker)stopifnot(reused_values == nrow(high_example))cat("Generated values present in the source: ", reused_values, "\n", sep = "")cat("Generated values checked: ", nrow(high_example), "\n", sep = "")Generated values present in the source: 12Generated values checked: 12The preset name does not establish a mathematical disclosure bound. Changing a column label does not hide a rare measurement, and generating each column separately does not preserve the joint relationships needed for scientific inference. Use these examples to develop code, then assess the analysis on real data locally.
Python with Faker
Section titled “Python with Faker”Faker generates invented values through providers. It does not need to learn from a real table. This example reads the same specification as the R example and uses the Python provider for ages and measurements.
Sequential identifiers make uniqueness explicit. The seed makes this example repeatable with the pinned package version; it is not a privacy control. Names, addresses, and phone numbers would add no value to this analysis example, so the table contains none of them.
import csvimport jsonfrom pathlib import Path
from faker import Faker
contract = json.loads(Path("contract.json").read_text(encoding="utf-8"))output_dir = Path("outputs")output_dir.mkdir(exist_ok=True)fake = Faker("en_US")fake.seed_instance(42)
records = []for row_index in range(contract["n_rows"]): records.append({ "subject_id": f"SYN_{row_index + 1:03d}", "group": fake.random_element(elements=contract["groups"]), "age": fake.pyint( min_value=contract["age_min"], max_value=contract["age_max"] ), "marker": fake.pyfloat( min_value=contract["marker_min"], max_value=contract["marker_max"], right_digits=2, ), })for row_index in (2, 8): records[row_index]["marker"] = None
for record in records[:6]: print(json.dumps(record)){"subject_id": "SYN_001", "group": "control", "age": 26, "marker": 4.31}{"subject_id": "SYN_002", "group": "control", "age": 33, "marker": 1.86}{"subject_id": "SYN_003", "group": "control", "age": 62, "marker": null}{"subject_id": "SYN_004", "group": "control", "age": 30, "marker": 3.29}{"subject_id": "SYN_005", "group": "control", "age": 60, "marker": 3.91}{"subject_id": "SYN_006", "group": "treated", "age": 39, "marker": 7.75}The checks below enforce the same requirements as the R checks. Empty CSV fields represent missing measurements. When you load either CSV for analysis, declare the column types explicitly because CSV does not store R factors or Python types.
assert len(records) == contract["n_rows"]assert len({record["subject_id"] for record in records}) == len(records)for row_index, record in enumerate(records, start=1): assert list(record) == contract["columns"] assert record["subject_id"] == f"SYN_{row_index:03d}" assert record["group"] in contract["groups"] assert isinstance(record["age"], int) assert contract["age_min"] <= record["age"] <= contract["age_max"] if record["marker"] is not None: assert isinstance(record["marker"], float) assert contract["marker_min"] <= record["marker"] assert record["marker"] <= contract["marker_max"]missing_marker = sum(record["marker"] is None for record in records)assert missing_marker == 2
with (output_dir / "synthetic_python.csv").open( "w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=contract["columns"]) writer.writeheader() writer.writerows(records)metrics = { "rows": len(records), "columns": len(contract["columns"]), "missing_marker": missing_marker, "unique_ids": len({record["subject_id"] for record in records}),}(output_dir / "metrics_python.json").write_text( json.dumps(metrics, indent=2) + "\n", encoding="utf-8")for key, value in metrics.items(): print(f"{key}: {value}")rows: 12columns: 4missing_marker: 2unique_ids: 12Give the LLM the task and the invented example
Section titled “Give the LLM the task and the invented example”After you review the export, a prompt can describe the code you need without including the original data.
This CSV contains invented records. Write a script that reads subject_id as text, group as a category, age as an integer, and marker as a numeric value with missing entries. Check that subject_id is unique. Report the number of missing marker values per group and calculate each group’s mean from observed marker values. Keep all file paths configurable. Do not infer a treatment effect from this example.
Review the generated script against the specification, including the missing data behavior. Run it against the real data in the approved environment without giving the hosted agent access to that run. If another error needs help, reproduce it with invented values and review the error message before sharing it.
Check the account’s training and retention controls
Section titled “Check the account’s training and retention controls”The provider information below was checked on October 28, 2026. A paid personal subscription does not establish the same data terms as an API or a business workspace. Confirm the account and authentication method your CLI actually uses.
| Access route | Model training | Retention and controls |
|---|---|---|
| Codex with a personal ChatGPT account | Content can be used unless you opt out. | Turn off Improve the model for everyone in ChatGPT’s data controls. Check the separate Codex Include environments setting too. |
| Claude Code with Free, Pro, or Max | General model improvement depends on your privacy choice. | Check the model improvement control in Claude’s privacy settings and disable it if enabled. This also covers Claude Code sessions on that account. |
| OpenAI API | Inputs and outputs are not used for training by default. An organization can opt in. | Standard abuse monitoring logs can retain content for up to 30 days, with exceptions. Some features store application state separately. |
| Anthropic API and commercial Claude Code | Training does not occur by default under commercial terms. Explicit data contribution programs are separate. | Retention depends on the product, model, feature, and agreement. Check ZDR eligibility and covered model exceptions. |
| Amazon Bedrock | AWS states that inputs and outputs are not used to train AWS or third party models. | Zero data retention depends on the model and configured retention mode. Also review logs stored in your AWS account. |
OpenAI’s data controls instructions confirm that the ChatGPT opt out applies to new Codex tasks. It does not change the separate environment sharing setting or delete saved conversations. Anthropic describes the consumer choice in its training policy. Do not assume that every Claude subscriber has training enabled; inspect the setting. Submitted feedback and safety review can have separate terms, so an opt out should not be described as a promise that content can never be retained or reviewed.
Configure ChatGPT and Codex
Section titled “Configure ChatGPT and Codex”For a personal ChatGPT subscription, set the account control before starting a new Codex task. Paying for Plus or Pro does not disable training by itself.
- Open the account menu in ChatGPT.
- Select Settings, then Data controls.
- Turn off
Improve the model for everyoneand select Done. - Open Codex settings and turn off
Include environmentsif that control is available.
The first control covers new ChatGPT conversations and Codex tasks. The environment control covers additional context from Codex environments and must be checked separately. These are the account controls documented in OpenAI’s data controls instructions.
Codex also has local controls for feedback submission and analytics. In
~/.codex/config.toml, add these sections or update their existing values. Keep the
rest of the file, and do not create duplicate sections.
[feedback]enabled = false
[analytics]enabled = falsefeedback.enabled = false disables submission through /feedback across local
Codex clients. analytics.enabled = false disables analytics for the machine or
profile. Neither setting replaces the account’s training opt-out. Restart the
local client after editing its configuration, and check any managed requirements
that apply to your workspace. See the
Codex configuration reference.
Configure Claude and Claude Code
Section titled “Configure Claude and Claude Code”For Claude Free, Pro, or Max, open Settings, then Privacy, and turn off
Help Improve our AI models. This account choice also covers Claude Code sessions
authenticated with that subscription. Anthropic documents the steps in its
model improvement settings guide.
For the local Claude Code client, merge these values into the env object in
~/.claude/settings.json. If the file already has an env object, edit that object
instead of adding another one. Preserve its other settings.
{ "env": { "DISABLE_FEEDBACK_COMMAND": "1", "CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY": "1", "DISABLE_TELEMETRY": "1", "DISABLE_ERROR_REPORTING": "1" }}These controls disable feedback commands, session quality surveys, usage metrics, and error reports, respectively. Restart Claude Code after the edit. The settings documentation explains file locations and precedence; managed settings can take priority over personal settings.
A session quality survey records a rating without the conversation transcript.
A submitted /feedback report can include a transcript, which Anthropic retains
for five years. Disabling surveys alone does not disable feedback reports or change
the account’s model improvement choice. These distinctions and the environment
variables appear in the Claude Code data usage documentation.
Check API sharing separately
Section titled “Check API sharing separately”Codex authenticated with an OpenAI API key and Claude Code authenticated with an Anthropic API key use the respective API data terms. Both providers exclude API inputs and outputs from model training by default. See OpenAI’s API policy and Anthropic’s commercial policy. This statement concerns direct use of those providers; a proxy or another provider has its own terms.
For OpenAI, an organization owner can open the API data sharing settings and leave feedback, evaluation and fine-tuning data, and input/output sharing disabled. Check the selected project as well as the organization. These controls are separate from ChatGPT’s settings, as explained in OpenAI’s API sharing guide.
For Anthropic, confirm that the API organization has not opted into a data contribution program. Explicit feedback can also have different training terms from ordinary API requests. See Anthropic’s commercial training policy.
For an API, distinguish exclusion from model training from deletion of request content. OpenAI’s API data controls describe abuse logs, application state, approval requirements for Zero Data Retention, and feature exceptions. Anthropic’s API retention documentation also lists eligibility by feature and exceptions for covered models. An API key alone does not establish zero retention.
What happens when content is flagged for safety review?
Section titled “What happens when content is flagged for safety review?”A safety flag can permit retention or review without making the content available for general model training. Anthropic also documents a specific training exception for its consumer accounts. The account type changes the answer.
| Access route | Can flagged content be used for training? | What can happen to the content? |
|---|---|---|
| Claude Free, Pro, or Max, including Claude Code on those accounts | Anthropic explicitly permits use of flagged conversations to train models for its Safeguards team, even when ordinary model improvement is disabled. | This exception concerns safety detection and policy enforcement; it is not the same as opting into general Claude training. See the consumer training policy. |
| Claude Code through the Anthropic API | The API documentation states that retained data is not used for model training without express permission. | Flagged inputs and outputs can be retained for up to two years, including under ZDR arrangements. Retention does not itself grant training permission. See the API retention policy. |
| Codex through the OpenAI API | OpenAI states that API data is excluded from training unless the customer opts in. Its documented safety retention provisions do not state that a flag creates a training opt-in. | Abuse logs can contain prompts and responses. Safety Retention can permit retention and human review under the documented conditions. See the API data controls. |
For personal ChatGPT accounts, OpenAI states that new conversations are excluded from training after the opt-out. Its moderation documentation still permits review of flagged content. The reviewed pages do not describe an equivalent to Anthropic’s explicit consumer exception for Safeguards model training. See OpenAI’s training policy and moderation explanation.
Voluntary feedback is a separate action from an automated safety flag. A feedback submission can authorize uses that ordinary API requests do not. Keep the feedback controls above disabled when the conversation contains confidential material.
Amazon Bedrock and zero data retention
Section titled “Amazon Bedrock and zero data retention”Bedrock’s none retention mode prevents durable storage of inference request and
response content under the documented policy. A request to a model that requires
retention is blocked when that mode applies. Check the model, endpoint, account
configuration, and Region; the account setting does not propagate to other Regions.
The default mode follows the model’s policy and is not a universal ZDR promise.
Setting store=false alone is also insufficient. See
Bedrock retention controls.
Bedrock has its own model-specific abuse review rules. Where those rules require retention, AWS stores the content and does not share it with the model provider. Do not apply Anthropic’s consumer training exception to Bedrock requests. See Bedrock abuse detection.
Customer configured invocation logs can also capture requests and responses in CloudWatch Logs or S3. Your application’s own logs, agent transcripts, and exported files need their own access and retention rules. The Bedrock data protection documentation describes the division of responsibilities between AWS and the customer.
Before using real sensitive data with any provider, confirm that your organization approves that exact service and configuration for the data involved. Keep the invented example available for code questions even when an approved production service can process the original data.
Further reading
Section titled “Further reading”-
The vignette explains the generation presets and treatment of sensitive columns. Compare its replacement-sampling behavior with the invented source values in this lesson.
-
The provider reference documents numeric limits and seeded examples. Use it to construct dummy values without deriving their distribution from confidential records.
-
The guide distinguishes account type, feedback reports, and local telemetry. Read those controls separately from any promise about API retention.