- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
Chat histories from more than 21 million US accounts are part of a bankruptcy sale. That figure comes from California's attorney general, one of a coalition of 42 attorneys general asking the court to reject the proposed sale of Character.AI's data. Their objection to the terms: the buyer would not have to follow the company's privacy policies or honour users' requests to opt out or delete their data.
The company's FAQ tells users their information "continues to be protected under our Privacy Policy". In an October 27 filing, it also said that the same policy already permitted the sale and transfer of user data. On November 17, with the company's consent, the judge ordered a privacy ombudsman, whose report is due at least seven days before any sale hearing. Coverage from November 27 still has the auction on December 1, and the states' objections go to a sale hearing after it. This was written on November 29, before either one, so check for a ruling if you read it later.
Character.AI is a consumer app, and your LLM vendor's contract is different. Still, the question carries over: what does the vendor hold about your customers if the company behind the promise disappears? You can send less, starting today. The names, emails and order ids you can detect stay in your process while the model works with stand-in tokens like PERSON1X7F3A9C, and your use cases don't have to change.
The use case asks for a reply and nothing else
Start with the port. Reply carries text and tool calls, and ReplyUnusable is how any adapter says "don't show this to anyone."
# app/ports.py from dataclasses import dataclass from typing import Protocol @dataclass(frozen=True) class ToolCall: name: str arguments: str # JSON text, as vendors return it @dataclass(frozen=True) class Reply: text: str tool_calls: tuple[ToolCall, ...] = () class ReplyUnusable(Exception): """The reply cannot be shown or acted on.""" class LLM(Protocol): async def complete(self, prompt: str) -> Reply: ... # app/draft_reply.py from app.ports import LLM, Reply class DraftReply: def __init__(self, llm: LLM) -> None: self._llm = llm async def __call__(self, ticket: str) -> Reply: return await self._llm.complete( f"Draft a reply to this ticket:\n{ticket}" ) DraftReply writes prompts with real names in them. That is fine, because nothing has left the process yet. Put the masking in an adapter that implements LLM and wraps the real one. The use case keeps working with names, and the vendor adapter underneath gets the masked prompt.
Detectors find the values, a vault swaps them
Finding personal data and replacing it are separate jobs. Detectors only report spans:
# adapters/detectors.py import re from collections.abc import Iterable from dataclasses import dataclass from typing import Protocol @dataclass(frozen=True) class Span: start: int end: int kind: str # letters only: PERSON, EMAIL, ORDER class Detector(Protocol): def find(self, text: str) -> list[Span]: ... Patterns cover anything with a shape, and KnownValues covers what your database already knows, such as the customer on this ticket.
# adapters/detectors.py, continued class Pattern: def __init__(self, kind: str, regex: str, flags=0) -> None: self._kind = kind self._rx = re.compile(regex, flags) def find(self, text: str) -> list[Span]: return [ Span(m.start(), m.end(), self._kind) for m in self._rx.finditer(text) ] class KnownValues: def __init__(self, kind: str, values: Iterable[str]) -> None: self._patterns = [ Pattern( kind, rf"(?<!\w){re.escape(v)}(?!\w)", re.IGNORECASE, ) for v in values if v.strip() ] def find(self, text: str) -> list[Span]: return [s for p in self._patterns for s in p.find(text)] EMAIL = Pattern("EMAIL", r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+") ORDER = Pattern("ORDER", r"\bORD-\d+\b", re.IGNORECASE) Two detectors can report overlapping spans. Those get merged, because picking one would leave the end of the other in clear text.
# adapters/vault.py import re import secrets from dataclasses import replace from adapters.detectors import Span from app.ports import ReplyUnusable def merge(spans: list[Span]) -> list[Span]: out: list[Span] = [] for s in sorted(spans, key=lambda s: (s.start, -s.end)): if out and s.start < out[-1].end: end = max(out[-1].end, s.end) out[-1] = replace(out[-1], end=end) else: out.append(s) return out The vault holds the mapping, in memory, for one conversation. A token like PERSON1X7F3A9C is a kind, a counter, and a random tail shared by the whole conversation.
# adapters/vault.py, continued class Vault: def __init__(self, nonce: str | None = None) -> None: self._tail = "X" + (nonce or secrets.token_hex(3)).upper() self._tokens: dict[tuple[str, str], str] = {} self._values: dict[str, str] = {} self._stems: set[str] = set() self._rx = re.compile( r"(?<![a-z0-9])([a-z]+)[ _-]?(\d+)[ _-]?" + self._tail + r"(?![a-z0-9])", re.IGNORECASE, ) @property def note(self) -> str: return ( f"\n\nCodes ending in {self._tail} stand for " "private values. Copy them character for character." ) def hide(self, text: str, spans: list[Span]) -> str: out, pos = [], 0 for s in merge(spans): value = text[s.start:s.end] out.append(text[pos:s.start]) out.append(self._token(s.kind, value)) pos = s.end out.append(text[pos:]) return "".join(out) def restore(self, text: str) -> str: rest = self._rx.sub(" ", text).upper() if self._tail in rest or any( stem in rest for stem in self._stems ): raise ReplyUnusable("mangled token") return self._rx.sub(self._value, text) def _token(self, kind: str, value: str) -> str: key = (kind, value) if key not in self._tokens: n = 1 + sum(k == kind for k, _ in self._tokens) self._stems.add(f"{kind}{n}") token = f"{kind}{n}{self._tail}" self._tokens[key] = token self._values[token] = value return self._tokens[key] def _value(self, m: re.Match[str]) -> str: token = f"{m[1]}{m[2]}{self._tail}".upper() if token not in self._values: raise ReplyUnusable("unknown token") return self._values[token] Tokens use only letters and digits, so they need no escaping in JSON or Markdown. Restoring uses a function as the replacement in re.sub, so a backslash in a real value is never read as a regex escape.
The exceptions name the problem and never include the text. An error message with the reply in it would put the data in your logs.

The tag is handed out. The box stays locked.
The adapter: mask, call, restore
# adapters/pseudonymizing.py import json from collections.abc import Collection, Sequence from dataclasses import replace from typing import Any from adapters.detectors import Detector from adapters.vault import Vault from app.ports import LLM, Reply, ReplyUnusable, ToolCall class PseudonymizingLLM: def __init__( self, inner: LLM, vault: Vault, detectors: Sequence[Detector], local_tools: Collection[str] = (), ) -> None: self._inner = inner self._vault = vault self._detectors = detectors self._local_tools = local_tools async def complete(self, prompt: str) -> Reply: spans = [ s for d in self._detectors for s in d.find(prompt) ] masked = self._vault.hide(prompt, spans) if spans: masked += self._vault.note reply = await self._inner.complete(masked) return Reply( text=self._vault.restore(reply.text), tool_calls=tuple( self._restore_call(c) for c in reply.tool_calls ), ) def _restore_call(self, call: ToolCall) -> ToolCall: if call.name not in self._local_tools: return call try: args = json.loads(call.arguments) except json.JSONDecodeError: raise ReplyUnusable("bad tool JSON") from None return replace( call, arguments=json.dumps(self._walk(args)) ) def _walk(self, node: Any) -> Any: if isinstance(node, str): return self._vault.restore(node) if isinstance(node, list): return [self._walk(x) for x in node] if isinstance(node, dict): return { self._walk(k): self._walk(v) for k, v in node.items() } return node local_tools is the line I'd defend hardest in review. If you restore tokens in every tool call, a prompt injection can tell the model to put EMAIL1X7F3A9C in a URL, and your adapter will fill in the real address on the way out. The model leaks a value it never saw. Restore only for tools whose effect stays inside your own system, such as saving a draft for a person to check. A send_email tool runs in your process and still delivers wherever the model says, so it gets the token unless your code picks the recipient and a person approves the body.
Test that caught values never reach the vendor
The fake inner adapter records every prompt it receives. Most of these pytest tests go through DraftReply, which shows the use case needs no changes.
# tests/test_pseudonymizing.py import asyncio import json import pytest from adapters.detectors import EMAIL, ORDER, KnownValues from adapters.pseudonymizing import PseudonymizingLLM from adapters.vault import Vault from app.draft_reply import DraftReply from app.ports import Reply, ReplyUnusable, ToolCall TICKET = "Alice Moreno (alice@example.com): where is ORD-10442?" SECRETS = ["Alice", "Moreno", "alice@example.com", "ORD-10442"] class RecordingLLM: def __init__(self, reply: Reply) -> None: self.reply = reply self.prompts: list[str] = [] async def complete(self, prompt: str) -> Reply: self.prompts.append(prompt) return self.reply ask wires the adapter around the fake, with a fixed nonce so the tests can name tokens:
# tests/test_pseudonymizing.py, continued def ask(inner, ticket=TICKET, name="Alice Moreno", extra=()): llm = PseudonymizingLLM( inner, Vault(nonce="7F3A9C"), [EMAIL, ORDER, KnownValues("PERSON", [name]), *extra], local_tools={"save_draft"}, ) return asyncio.run(DraftReply(llm)(ticket)) def test_caught_values_never_reach_the_inner_adapter(): inner = RecordingLLM( Reply("Hi PERSON1X7F3A9C, ORDER1X7F3A9C ships today.") ) reply = ask(inner) sent = inner.prompts[0].lower() assert all(s.lower() not in sent for s in SECRETS) assert reply.text == "Hi Alice Moreno, ORD-10442 ships today." def test_same_value_gets_the_same_token_across_calls(): vault = Vault(nonce="7F3A9C") first = vault.hide("ORD-1", ORDER.find("ORD-1")) again = vault.hide("ORD-1", Source:https://dev.to/gabrielanhaia/characterai-put-user-chats-up-for-sale-swap-names-for-tokens-before-your-llm-call-igmRelated posts
What the Vault Already Knows
Nextcloud Docker install: the 5 checks it leaves red
Design for the Phone in the Customer's Hand, Not the Screen on Your Desk
