Python library¶
The proxy and the CLI are thin layers over one engine, and that engine is an ordinary Python object. Use it directly when you want to mask text inside your own program: before writing to a log, before storing a prompt, in a batch job, or in a service of your own.
Stability
The engine's methods shown here are what the proxy itself calls, and the
scripts on this page are run by the test suite. The Python API is
experimental and may change in a 0.x release; pin the version you build
on.
The engine is asynchronous. Call it from async code, or wrap a call in
asyncio.run.
Build the engine from configuration¶
Privyx reads the same layers as the CLI: the built-in
defaults, the config files
(or one alone, if you pass its path), the PRIVYX_* environment, and overrides
you pass. app.engine() assembles the detector, policy, operator, and vault
those settings describe.
"""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())
app.engine() is an async context manager. Contexts open at once, nested or in
parallel tasks, share one engine, and the last to leave closes its components.
Everything a config file can do works here: word lists, patterns, Presidio,
the encrypt operator, a SQLite or Redis vault, plugins.
The three calls¶
| Call | Does |
|---|---|
await engine.get_or_create_session(session_id=None) |
Returns the session with that id, or creates one. Without an id, a new random one. |
await engine.transform(text, session=session) |
Detects, applies the policy, masks. Returns a result whose .text is the masked text and whose .transformations list each replacement. |
await engine.restore(text, session_id) |
Puts the original values back. Raises SessionNotFoundError when the vault has no such session. |
A session is the mapping between tokens and values. Keep its id for as long as you need to restore text that was masked with it; with a persistent vault, the id is all you have to keep.
Assemble it by hand¶
To skip the configuration layer, pass the four components yourself:
"""Basic usage of the Privyx privacy engine."""
from __future__ import annotations
import asyncio
from privyx import PrivacyEngine
from privyx.detectors import RegexDetector
from privyx.operators import PseudonymOperator
from privyx.policies import DefaultPolicy
from privyx.vaults import MemoryVault
async def main() -> None:
engine = PrivacyEngine(
detector=RegexDetector(),
policy=DefaultPolicy(),
operator=PseudonymOperator(),
vault=MemoryVault(),
)
# A session is created and persisted automatically on first transform.
session = await engine.get_or_create_session()
text = "Contact John at john@example.com or +1 (555) 123-4567."
print(f"Original: {text}")
print(f"Session: {session.session_id}")
result = await engine.transform(text, session=session)
print(f"Pseudonymized: {result.text}")
# Restore (deanonymize) using the session mapping.
restored = await engine.restore(result.text, session.session_id)
print(f"Restored: {restored.text}")
assert restored.text == text
if __name__ == "__main__":
asyncio.run(main())
The configuration is not applied then. Each component takes the defaults of
its own options. The engine has no anchor and no leak check unless you pass
dlp_check=True, and that check treats _ as a word separator only with
underscore_separates_words=True. Set them yourself, or start from Privyx.
Restore a stream¶
A model's reply usually arrives in pieces, and a token can be cut in two.
StreamingDeanonymizer holds back a fragment that could be the start of a
token until it knows:
"""Restore an OpenAI-style stream by hand, without the proxy or a provider.
Pseudonymizes a request, then feeds a simulated SSE reply through the
streaming deanonymizer, with a token split between two chunks. The proxy does
all of this for you; this is the building block it uses.
"""
from __future__ import annotations
import asyncio
import json
from privyx import PrivacyEngine
from privyx.detectors import RegexDetector
from privyx.operators import PseudonymOperator
from privyx.policies import DefaultPolicy
from privyx.streaming import SSEStreamAdapter
from privyx.streaming.deanonymizer import StreamingDeanonymizer
from privyx.streaming.sse import SSEEvent
from privyx.vaults import MemoryVault
async def main() -> None:
engine = PrivacyEngine(
detector=RegexDetector(),
policy=DefaultPolicy(),
operator=PseudonymOperator(),
vault=MemoryVault(),
)
session = await engine.get_or_create_session()
request_text = "Tell me about Alice at alice@example.com"
transformed = await engine.transform(request_text, session=session)
print(f"Request pseudonymized: {transformed.text}")
# Simulate provider SSE chunks that split a pseudonym at the boundary.
# Suppose the provider echoes back the pseudonym as a stream:
pseudo = transformed.text.split("Tell me about ")[1]
chunk1 = pseudo[:10]
chunk2 = pseudo[10:]
adapter = SSEStreamAdapter(data_path=["choices", "0", "delta", "content"])
deanonymizer = StreamingDeanonymizer(session.mapping)
outputs: list[str] = []
for raw in (chunk1, chunk2):
# Wrap each raw delta in an OpenAI-style SSE event envelope.
event = SSEEvent(
data=json.dumps({"choices": [{"delta": {"content": raw}}]}),
event="chat.completion.chunk",
)
delta = adapter.extract_delta(event)
restored = deanonymizer.feed(delta)
if restored:
outputs.append(restored)
outputs.append(deanonymizer.flush())
restored_text = "Tell me about " + "".join(outputs)
print(f"Stream restored: {restored_text}")
assert restored_text == request_text
if __name__ == "__main__":
asyncio.run(main())
feed returns the text that is safe to show so far; flush returns whatever
was still held back when the stream ends.
Serve the gateway from your program¶
"""Run the Privyx gateway on FastAPI programmatically."""
from __future__ import annotations
import asyncio
import uvicorn
from privyx import Privyx
async def main() -> None:
# The settings `privyx proxy --gateway -u http://localhost:20128` would use.
app = Privyx(proxy={"mode": "gateway"}, provider={"base_url": "http://localhost:20128"})
# Its lifespan opens the engine and the provider as uvicorn starts, and
# closes them as it stops.
config = uvicorn.Config(app.asgi(), host="127.0.0.1", port=8000, log_level="info")
server = uvicorn.Server(config)
print("Gateway running at http://127.0.0.1:8000 (Ctrl+C to stop)")
await server.serve()
if __name__ == "__main__":
asyncio.run(main())
Errors¶
Every error Privyx raises derives from privyx.PrivyxError. privyx.core has
ConfigError for a setting that cannot work, DetectorError when a scan
fails, VaultError when the session store does, and SessionNotFoundError
for an unknown session id.
Mask without holding an engine¶
The services of Privyx open the engine for each
call, or use the one already open:
import asyncio
from privyx import Privyx
app = Privyx(vault={"type": "sqlite", "dsn": "sessions.db"})
async def main() -> None:
masked = await app.masking.mask("write to ana@example.com")
print(masked.text)
print(await app.masking.unmask(masked.text, session_id=masked.session.session_id))
print(len(await app.sessions.list()))
asyncio.run(main())
Extending the engine¶
To add a detector, an operator, a policy, a vault, a provider, or another kind of component, write a plugin. The tutorial A detector plugin builds one from start to finish.