Skip to content

Examples

Short recipes to copy. Each client below talks to Privyx instead of the provider: only the base URL changes, and the client keeps its own API key, which Privyx relays. The examples assume a proxy on the default port:

privyx proxy --upstream https://api.openai.com        # for the OpenAI examples
privyx proxy --upstream https://api.anthropic.com     # for the Anthropic examples

For a guided walkthrough instead, see the tutorials.

OpenAI Python SDK

from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1")  # the key still comes from OPENAI_API_KEY

reply = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Write a short greeting to alice@example.com"}],
)
print(reply.choices[0].message.content)

The provider receives <PRIVYX_EMAIL_4FF5EF825E496E1A> in place of the address; the reply has the address back. Streaming (stream=True) is restored as it arrives.

Setting OPENAI_BASE_URL=http://localhost:8000/v1 has the same effect without touching the code.

Anthropic Python SDK

import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000")  # the key still comes from ANTHROPIC_API_KEY

reply = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": "Write a short greeting to alice@example.com"}],
)
print(next(block.text for block in reply.content if block.type == "text"))

Or set ANTHROPIC_BASE_URL=http://localhost:8000.

Node

import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1" }); // the key still comes from OPENAI_API_KEY

const reply = await client.chat.completions.create({
  model: "gpt-4o-mini",
  messages: [{ role: "user", content: "Write a short greeting to alice@example.com" }],
});
console.log(reply.choices[0].message.content);

The Anthropic SDK for Node takes baseURL: "http://localhost:8000" in the same way. Streaming, tool calls, and the Responses API are in An app on the OpenAI or Anthropic SDK; LangChain, LlamaIndex, LiteLLM, and the Vercel AI SDK are under Integrations.

One session per user

By default every request gets its own session. To keep one mapping per user of your application, send an x-privyx-session header:

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    default_headers={"x-privyx-session": "user-42"},
)

anthropic.Anthropic takes the same default_headers argument. Privyx strips the header before forwarding and returns the session id in the response's x-privyx-session header. A persistent vault keeps the mapping across restarts; see Sessions and vault.

curl

curl http://localhost:8000/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini",
       "messages": [{"role": "user", "content": "Write a short greeting to alice@example.com"}]}'
curl http://localhost:8000/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "claude-opus-5-5", "max_tokens": 1024,
       "messages": [{"role": "user", "content": "Write a short greeting to alice@example.com"}]}'

Privyx adds the anthropic-version header when the request has none.

Coding tools

privyx run starts a proxy for the tool and points it there:

privyx run claude      # Claude Code
privyx run codex       # Codex
privyx run aider       # aider
privyx run pi          # pi

For a long-running proxy that several terminals share, start it once and set the variable yourself:

privyx -c privyx.yaml proxy --upstream https://api.anthropic.com
ANTHROPIC_BASE_URL=http://localhost:8000 claude

On the command line

# What would be masked in this text, and what the provider would get
privyx detect --transform "DB_PASSWORD=hunter2, mail dana@acme.example"

# The same for a file
privyx detect --transform --stdin < app.log

# Mask a file and keep the mapping; restore the answer later
privyx mask --map map.json -i app.log -o app.masked.log
privyx unmask --map map.json -i answer.txt

# Only the messages of a JSON request
privyx mask --map map.json -i request.json --path '$.messages'

# A JSONL dataset through a pipe
cat tickets.jsonl | privyx mask --map map.json -f jsonl -i - -o tickets.masked.jsonl

# What happened lately, without any content
privyx audit stats --since 24h

Configuration recipes

These files ship in the repository's configs/ folder and in the Docker image under /app/configs.

Agent profiles

# Example: agent profiles for `privyx run`
#
#   privyx run --list                    # every profile, built-in and yours
#   privyx run --dry-run claude:work     # what a launch would do, no secrets shown
#   privyx run claude:work
#
# Copy what you need into ~/.privyx/config.yaml.  Every value below is a
# placeholder.

# Files merged below this one, such as one file per machine.  A glob may match
# nothing.
include: ["privyx.d/*.yaml"]

agents:
  # claude:work inherits the built-in claude profile and changes where it goes.
  # The token is read from WORK_ANTHROPIC_TOKEN in your shell at launch; this
  # file holds only its name.
  claude:work:
    upstream: https://router.example.com
    env_from:
      ANTHROPIC_AUTH_TOKEN: WORK_ANTHROPIC_TOKEN

  # A second Codex home with its own login and config.toml.
  codex:work:
    env:
      CODEX_HOME: "${HOME}/.codex-work"

  # Privyx settings for one profile only, above config files and environment.
  claude:strict:
    presets: [strict]
    privyx:
      detectors:
        regex:
          terms:
            PERSON: [john smith, alice]
            ORGANIZATION: [acme]
    budget:
      max_turns: 200

  # A wrapper script around Aider keeps following OPENAI_API_BASE, as aider
  # does.  A tool of your own names the variable that holds its endpoint, an
  # option of its type, env.
  aider:work:
    command: my-aider
  acme:
    command: acme
    type: env
    provider: openai
    env_vars: [ACME_BASE_URL]
    endpoint_env: [ACME_BASE_URL]
    base_path: /v1

# Privyx settings written once, for any profile (presets: [strict]) or one
# command (privyx --preset debug run claude:work, privyx --preset strict
# proxy).  A preset does nothing until one of those names it.
presets:
  strict:
    proxy:
      passthrough_unknown: false   # paths outside proxy.routes get 403
  debug:
    log:
      level: debug
      # At debug level this file holds vault rows with original values.
      file: "${HOME}/.privyx/debug.log"

Your own word lists

# Example: pseudonymize your own list of literal terms
#
# `terms` takes plain strings — Privyx escapes them, orders the longest first so
# a compound term wins over a substring of itself, and adds word boundaries.
# Matching is case-insensitive.  The entity name is yours to choose; it is the
# {type} in the emitted token, e.g. <PRIVYX_PERSON_A81B3C9AEE08DE11>.
#
# Every value below is a placeholder — replace it with your own.

detectors:
  regex:                    # keeps the built-in patterns (personal data and secrets)
    terms:
      PERSON:       [ann, bob, annbob]
      ORGANIZATION: [acme, initech]
      URL:          ["https://git.internal.example/team"]
      PROJECT:      [bluebird]          # any entity name works

    # `terms` and `patterns` are merged, so hand-written regexes still work.
    patterns:
      EMPLOYEE_ID: "\\bEMP-\\d{6}\\b"

operator:
  type: pseudonym

vault:
  type: memory

# With `policy.type: strict`, every entity above would also need to appear in
# `policy.allowed` — the default policy passes everything through.
policy:
  type: default

No plain text in the vault

# Example: encrypt operator — no plaintext PII at rest in the vault
#
# The vault stores the AES-256-GCM ciphertext of each detected value (not the
# original) and Privyx decrypts on the way back.  Requires the `crypto` extra:
#   pip install privyx[crypto]
#
# Provide the key via the environment (preferred) rather than committing it:
#   export PRIVYX_ENCRYPT_KEY=$(openssl rand -hex 32)

operator:
  type: encrypt
  key: ""                # 64 hex chars; set via PRIVYX_ENCRYPT_KEY

vault:
  type: memory

Names the model can read

# Example: labeled placeholders, so the model reads a name, not just a number
#
# `john smith` is sent as <PRIVYX_PERSON_A81B3C9AEE08DE11:Alice Johnson>, a fake name of the
# same kind, and the placeholder is restored by its id.  A reply that only says
# "Alice Johnson" is left as written.  Needs `pip install 'privyx[faker]'`.
#
# Every value below is a placeholder — replace it with your own.

token:
  label_format: "<{namespace}_{type}_{id}:{label}>"

operator:
  type: pseudonym           # labels work with this operator only
  locale: en_US             # the language of the labels
  seed: 1234                # optional: other labels for the same tokens

features:
  directive: true           # tells the model to keep each placeholder whole

detectors:
  regex:
    terms:
      PERSON: [ann, bob]

A stricter deployment

# Privyx strict configuration
#
# For higher-sensitivity work.  It changes only how strictly Privyx masks and
# forwards: the upstream, provider, and anchor stay as they would be without
# it, so `privyx -c configs/strict.yaml run claude` still reaches Anthropic.
# Every setting is listed in configs/default.yaml.

# Persist sessions in ~/.privyx/privyx.db across restarts (privyx[sqlite]).
vault:
  type: sqlite

# The default policy masks everything detected: the built-ins, your own
# `terms` and `patterns`, and what `privyx run --harvest` finds.
detectors:
  regex:
    patterns:
      DATE_OF_BIRTH: "\\b\\d{4}-\\d{2}-\\d{2}\\b"
    # Also find values split into strings or Base64/hex/URL encoded, and values
    # written in fullwidth letters or with zero-width characters inside.
    decode: true
    normalize: true

proxy:
  # Only routes with a masking schema may reach the upstream.  Other paths,
  # including models and files, return 403.
  passthrough_unknown: false
  # Refuse (422) a masked request that still holds a value it masked
  # somewhere Privyx does not mask, instead of forwarding it (the default).
  # Only exact signed thinking remembered from the upstream is reinstated
  # after the check.
  dlp_check: true

Sessions that survive a restart

vault:
  type: sqlite               # needs privyx[sqlite]
  dsn: /var/lib/privyx/privyx.db
  ttl: 604800                # forget sessions idle for a week

session:
  strategy: conversation     # one session per conversation

Refuse what cannot be masked

proxy:
  passthrough_unknown: false   # 403 for file uploads and every other unrouted path

Names without a list

detectors:
  regex: {}                   # built-in patterns, your terms and patterns
  presidio:                   # needs privyx[presidio] and a spaCy model
    language: en
    entities: [PERSON, LOCATION]

Using the engine from Python

The engine can run inside your own program, without the proxy. The scripts in examples/ show how, and the test suite runs each of them. Python library walks through them.

"""Build the engine from settings, the way `privyx proxy` does.

Instead of wiring a detector, a policy, an operator, and a vault by hand, load
the same configuration the CLI reads and let Privyx assemble them.
"""

from __future__ import annotations

import asyncio

from privyx import Privyx


async def main() -> None:
    # The same layers as the CLI: built-in defaults, the config files (or one
    # alone: pass its path as the first argument), PRIVYX_* environment
    # variables, then these settings.
    app = Privyx(detectors={"regex": {"terms": {"PROJECT": ["bluebird"]}}})
    async with app.engine() as engine:  # closes the vault on exit
        session = await engine.get_or_create_session()

        masked = await engine.transform("bluebird ships to dana@acme.example", session=session)
        # <PRIVYX_PROJECT_DBBA12EA1BBFFECF> ships to <PRIVYX_EMAIL_19ECE4788CA5AE6F>
        print(masked.text)

        reply = f"Noted: {masked.text}"  # stands in for a model's answer
        restored = await engine.restore(reply, session.session_id)
        print(restored.text)  # Noted: bluebird ships to dana@acme.example


if __name__ == "__main__":
    asyncio.run(main())