Character.AI Put User Chats Up for Sale. Swap Names for Tokens Before Your LLM Call
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 part of bankruptcy sale
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.
What the vendor holds about your customers
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 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 (a****@example.com): where is ORD-10442?"
SECRETS = ["Alice", "Moreno", "a****@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", ORDER.find("ORD-1"))
other = vault.hide("ORD-2", ORDER.find("ORD-2"))
assert first == again != other
That is the happy path. The next tests cover three ways masking breaks.
The reply mangles a token. A model can change the case, add a space, or cut the end off. The vault repairs small changes and raises ReplyUnusable on any damaged or invented token it can recognise.
@pytest.mark.parametrize("token", ["person1x7f3a9c", "PERSON 1 X7F3A9C", "PERSON_1_X7F3A9C",])
def test_small_changes_are_repaired(token):
reply = ask(RecordingLLM(Reply(f"Hi {token}.")))
assert reply.text == "Hi Alice Moreno."
@pytest.mark.parametrize("token", ["PERSON1", # tail lost "PERSON1X7F3A", # cut short "PERSONX7F3A9C", # counter lost "PERSON9X7F3A9C", # never issued])
def test_damaged_tokens_are_refused(token):
with pytest.raises(ReplyUnusable):
ask(RecordingLLM(Reply(f"Hi {token}.")))
The token sits inside a JSON argument. Replacing on the raw string fails twice. A name with quotes in it breaks the JSON, and an escaped newline glues an n to the front of the token (\nPERSON1…), so it reads as a different token. Parsing first avoids both.
def test_tokens_in_json_arguments():
args = {"to": "EMAIL1X7F3A9C", "body": "Dear\nPERSON1X7F3A9C",}
call = ToolCall("save_draft", json.dumps(args))
name = 'Alice "Al" Moreno'
reply = ask(RecordingLLM(Reply("", (call,))), ticket=f"{name} wrote from a****@example.com", name=name,)
assert json.loads(reply.tool_calls[0].arguments) == {"to": "a****@example.com", "body": f"Dear\n{name}",}
def test_external_tools_only_get_the_token():
call = ToolCall("web_search", '{"q": "EMAIL1X7F3A9C"}')
reply = ask(RecordingLLM(Reply("", (call,))))
assert reply.tool_calls == (call,)
The name is in free text. "My neighbour Priya signed for it" matches no pattern and no record in your database. This test records the hole:
def test_free_text_names_need_a_detector():
text = "My neighbour Priya signed for ORD-10442."
bare = RecordingLLM(Reply("ok"))
ask(bare, ticket=text)
assert "Priya" in bare.prompts[0] # leaks
ner = KnownValues("PERSON", ["Priya"]) # stand-in
guarded = RecordingLLM(Reply("ok"))
ask(guarded, ticket=text, extra=[ner])
assert "Priya" not in guarded.prompts[0]
Run it with the project root on pytest's path (pythonpath = . under [pytest] in pytest.ini).
Patterns catch what has a shape. A name in a sentence has none. Plug in a real detector, per conversation
Presidio is an open source toolkit that detects personal data, and its analyzer has a PERSON entity. Run pip install presidio_analyzer, then python -m spacy download en_core_web_lg for the spaCy model (install docs), and a small wrapper fits it to the Detector prot
Comments
No comments yet. Start the discussion.