How to redact sensitive data before sending a free LLM API request

If a prompt contains customer text, logs, or internal notes, minimize it first and redact known values locally before building the API request. Then test the serialized body at a loopback HTTP mock. A cleaned application log or an instruction telling the model to ignore secrets does not prove that the provider received a cleaned request.

A free LLM API payload is minimized and redacted locally, then checked by a loopback receiver before any provider request.

This guide handles sensitive message content. The API key still belongs in a server-side secret store or another protected runtime boundary; redacting prompt text does not protect an exposed key. See the browser key proxy guide for that separate problem.

Check the provider and tier before sending data

“Free” and “OpenAI-compatible” describe access or request shape, not a universal data-handling promise. Read the current terms for the exact provider, model, and tier you intend to use. For example, on 2026-11-10 Google’s Gemini Developer API pricing page labeled free-tier content as used to improve Google products and paid-tier content as not used for that purpose. That is a dated Google example, not a rule for every free API; check the current pricing and data terms again when you choose a provider.

If your organization has not approved a provider for the data class in question, do not send that data. A local redactor can reduce what leaves your app, but it does not change the provider’s retention rules or turn a request into a compliance approval.

Minimize first, then redact known patterns locally

Start by removing fields the model does not need. A support summary may need the error message and a short stack frame, but not the customer’s full name, email, session cookie, or entire production log. Removing unnecessary context is more reliable than trying to identify every sensitive string afterward.

Redact the values you can recognize before constructing the outbound Chat Completions payload. This small JavaScript example recursively scans JSON strings and replaces a few known formats. It is a starting point, not a complete detector:

const rules = [
  [/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[API_KEY]"],
  [/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[EMAIL]"],
];

export function redactJson(value) {
  if (typeof value === "string") {
    return rules.reduce((text, [pattern, replacement]) =>
      text.replace(pattern, replacement), value);
  }
  if (Array.isArray(value)) return value.map(redactJson);
  if (value && Object.getPrototypeOf(value) === Object.prototype) {
    return Object.fromEntries(
      Object.entries(value).map(([key, child]) => [key, redactJson(child)])
    );
  }
  return value;
}

const requestBody = redactJson({
  model: "your-selected-model-id",
  messages: [
    { role: "user", content: "Summarize this sanitized support excerpt: ..." },
  ],
});

Apply the function to the payload you will actually send, including prior conversation messages and tool results that are included as text. Keep the provider credential separate in the authorization header. If your application needs to restore placeholders later, keep the mapping local to one request and do not include that mapping in the prompt, logs, or analytics.

These patterns only illustrate recognizable key and email shapes. Providers use different credential formats; identifiers and confidential facts may have no recognizable pattern at all. Add patterns for your own data only after testing both matches and false positives. Never treat this sample as a promise that a prompt is safe to transmit.

Prove what crosses the HTTP boundary with a local mock

A redacted debug log can differ from the actual provider request. In a historical LiteLLM report, the author saw masked content in proxy logs while provider-side logs still contained the original value; the issue was closed in March 2025. That report does not establish a current LiteLLM defect. It illustrates why the test should inspect the request body received by an HTTP server, not only a log line.

Use synthetic canaries and a loopback server. This test makes no provider request and uses no real user data or API key:

import assert from "node:assert/strict";
import { once } from "node:events";
import { createServer } from "node:http";
import { test } from "node:test";
import { redactJson } from "./redact-json.mjs";

test("the loopback receiver sees placeholders, not raw canaries", async (t) => {
  let received = "";
  const server = createServer((req, res) => {
    req.setEncoding("utf8");
    req.on("data", (chunk) => { received += chunk; });
    req.on("end", () => { res.writeHead(204); res.end(); });
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  t.after(() => new Promise((resolve, reject) => {
  server.close((error) => error ? reject(error) : resolve());
}));

  const rawKey = "sk-test-fake-canary-1234567890";
  const rawEmail = "redaction.fixture@example.test";
  const body = redactJson({
    model: "fixture-model",
    messages: [{ role: "user", content: `Contact ${rawEmail}; token ${rawKey}` }],
  });
  const { port } = server.address();
  const response = await fetch(`http://127.0.0.1:${port}/capture`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });

  assert.equal(response.status, 204);
  assert.match(received, /\[API_KEY\]/);
  assert.match(received, /\[EMAIL\]/);
  assert.equal(received.includes(rawKey), false);
  assert.equal(received.includes(rawEmail), false);
});

Run it with Node’s built-in test runner: node --test redact-json.test.mjs. The test’s evidence is deliberately narrow: a synthetic JSON request reached 127.0.0.1, the receiver saw the placeholders, and it did not see these two raw canaries. It does not prove that every sensitive value is detectable, inspect an external provider, or certify privacy compliance.

Add a negative test with a fake internal project name or a natural-language secret that has no known pattern. If it reaches the mock unchanged, record that limitation and remove, generalize, or manually review that field before the real request. Also inspect the final JSON.stringify(requestBody) path in your application: sanitizing one object and later rebuilding the request from the original object defeats the check.

Interpret each loopback result

The receiver is the boundary under test. It reads the exact JSON bytes sent by the test client, so it can catch a request builder that accidentally reuses the original prompt after a separate preview was sanitized. Keep the request builder and redactor in the same function used by production code, then inject the destination URL or transport in the test. For this fixture, the only destination is an ephemeral port bound to 127.0.0.1; do not configure a provider URL or real authorization header.

Read a failure as a stop signal, not as a reason to weaken the assertion. If a raw canary appears, the redactor did not run on the final payload or another code path restored the original value. If the placeholder is missing but the canary is absent, inspect whether the field was removed, encoded, or transformed; document that behavior explicitly. A passing 204 response proves only that the local fixture received the sanitized sample.

Add separate fixtures for each format your app expects: nested message text, conversation history, tool output, structured content arrays, and log excerpts. File attachments, image pixels, audio, and encoded blobs need their own handling; recursively replacing ordinary JSON strings does not inspect their contents. For those inputs, either avoid sending them, use an approved local extraction step, or test the exact transformation before the upload boundary.

Finally, make the negative case visible. A pattern test should include an invented internal reference such as Project LARCH-43, which the two sample rules do not recognize. The expected result is that the test flags the phrase as unclassified, not that the regex silently claims success. Remove that field, replace it with a safe category label, or route it through an approved detector. This makes the detector’s coverage and its blind spot part of the test record.

Keep logs and responses inside the same boundary

Avoid logging raw prompts before redaction. For debugging, log the route, model identifier, status, elapsed time, and redaction counts rather than full message text. If you need a payload sample, use a synthetic fixture.

Treat model output as untrusted too. A response may repeat a placeholder or contain sensitive material from the prompt. Do not automatically restore real values into generated commands, SQL, or messages. If restoration is required for a user-facing workflow, do it only in an explicitly approved local step, after output checks, and only for placeholders created by that same request.

OWASP’s LLM02 guidance identifies personal, financial, health, business, and credential data as sensitive-information categories. It also notes that instructions in a system prompt are not a dependable substitute for application controls. Keep the sanitizer at the application boundary where you can inspect the exact bytes before they leave your process.

A pre-request checklist

FAQ

Does telling the model not to reveal a secret protect the request? No. The text has already crossed the provider boundary by the time the model receives that instruction. Remove or redact it locally before the request is sent.

Can a regular expression find every private detail? No. It can match known formats, but names, internal project references, and contextual facts may not have a stable pattern. Minimize input and review fields that the detector cannot classify.

Does an OpenAI-compatible endpoint follow OpenAI’s data terms? No. Compatibility describes parts of the API shape. Check the current data terms for the provider and account tier that will process the request.

Sources checked on 2026-11-10