Handling Untrusted Inputs
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
"Untrusted input" sounds like it means attackers. Mostly it means people: someone pasting a 40-page document, a customer whose message contains a card number, a file with strange characters in it, a form field filled with nothing but spaces. This lesson covers the dull, important work of turning arbitrary text into something safe to process, store and send to a model.
What you'll learn
- Validating at the edge: type, size, shape.
- Cleaning text: Unicode normalisation, control and invisible characters.
- Redacting personal data before it reaches logs or the model, with its limits.
- Keeping untrusted content separate from instructions.
Before you start
Validate at the edge
Reject bad requests before any of your real logic runs. In our service the request body is a Pydantic model, so these rules cost nothing and run first:
class AnswerRequest(BaseModel):
user_id: str = Field(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_.-]+$")
question: str = Field(min_length=1, max_length=8000)
order_id: str | None = Field(default=None, pattern=r"^[A-Z]\d{3,6}$")
The tests send a space in the user id, a path-like order id, an empty question and a missing field, and each gets a 422 before anything else happens. Notice that the identifier fields are allow-lists (letters and digits only), not "reject bad characters" lists. An allow-list can't be surprised by a character you didn't think of.
Size limits
Every character becomes tokens you pay for and wait on. Choose limits from the task, not from the API's maximum: a support question rarely needs more than a few thousand characters. We cap the request body at 8,000 characters and the cleaned text at 4,000, and reject (rather than silently truncate) anything longer, so the caller knows. For reference, the documentation lists a 128 MB maximum for the Messages API request body, which is far above anything you should accept from a stranger.
Cleaning text
Text from the outside world can contain characters that are invisible or that change how it displays. They matter because they can hide instructions from a human reviewer who sees a harmless line, or confuse matching rules. clean does four things:
- Unicode normalisation (NFKC) turns look-alike forms such as full-width letters into plain ones, so a pattern for "ignore" also matches a disguised version. We tested that
ABC becomes ABC.
- Removes control characters, zero-width characters and bidirectional overrides (the ones that can make text display in a different order than it's stored). Tests cover a zero-width space, a null byte and a right-to-left override.
- Collapses runs of whitespace and blank lines, which saves tokens and removes padding tricks.
- Rejects empty and over-long input with a reason that's safe to show.
This is hygiene, not a security boundary. A clean string can still say "ignore your instructions". It just does it in a form your other defences can recognise.
Redacting personal data
Customers paste card numbers, emails and phone numbers into messages. Before such text goes into logs, analytics or a prompt that doesn't need it, mask what you can. Our redact function finds email addresses, card numbers (checking the Luhn checksum so ordinary long numbers aren't flagged as cards) and phone-like numbers:
text, found = redact("Mail me at jo.smith@example.com, card 4111 1111 1111 1111")
# text -> "Mail me at [EMAIL], card [CARD]"
# found -> {"email": 1, "card": 1, "phone": 0}
Be realistic about it. Regular expressions find common shapes. They won't find names, street addresses, or a number written out in words. Our test showed the opposite problem too: the phone pattern is greedy, and a 16-digit order number that fails the card checksum still got masked as a phone number. For logs that's the safe direction, since over-masking costs you some detail, but it would be wrong to use redaction to alter the text you actually send for a reply. For stronger guarantees, use a dedicated PII-detection tool, and check what your data-protection obligations are.
Also remember redaction protects copies. If the model genuinely needs the order number to answer, send it, and keep it out of your logs instead.
Keep data and instructions apart
After cleaning, the text still gets framed as data (lesson 8.3's as_data), with its source named. Two small habits help: put the untrusted block in a clearly named place in the prompt, and never build your prompt by pasting user text into the middle of your instructions with string formatting. The second is the prompt version of SQL injection.
Files and other inputs
Text pulled out of a PDF, an image's OCR or a web page is untrusted in exactly the same way, and often worse because nobody read it first. Apply the same steps (limit, clean, label as data, screen if the stakes warrant) at the point where it enters your system. If a user uploads a file, check its type and size before you parse it, parse it in a restricted process where you can, and treat everything extracted as hostile text.
Testing
Each rule has a test. Representative ones: normalisation and control-character removal; blank-line collapsing; rejection of empty text (including text that's only zero-width characters), of over-long text and of non-text; redaction of an email, a valid card number and a phone number; a 16-digit non-card staying out of the card count; and the JSON encoder holding a hostile string intact. A short list of nasty strings you maintain yourself, and run on every change, is one of the best investments in this lesson.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A customer pastes an entire forwarded email thread, nine screens long, including a quoted message containing their card number and a signature block with a phone number. The edge validator accepts it (under the cap), cleaning removes odd whitespace, the screen sees nothing suspicious, and the logs record "email: 1, card: 1, phone: 1" and none of the digits. A different customer pastes 90,000 characters of copied web page and gets a clear "too long" message at once, before any token is spent.
Mistakes to avoid
- Truncating long input silently, so the answer is based on half of what the customer said.
- Deny-lists of "bad characters" instead of allow-lists for identifiers.
- Trusting redaction to be complete.
- Logging the raw message "just for now".
- Building prompts by pasting user text into instructions.
Security notes
Invisible and look-alike characters are a way to hide instructions from the human reviewer in your loop, which is a good reason to clean text before it's shown to a reviewer as well as before it reaches the model. Apply the same checks to anything that comes from tools and files.
Cost and speed
All the work here is local and takes microseconds. Size limits save real money: cutting a ten-thousand-character paste to a clear rejection avoids thousands of input tokens on every call.
Key takeaways
- Validate shape, size and type at the edge, using allow-lists for identifiers.
- Normalise Unicode and strip control and invisible characters; reject rather than truncate.
- Redact personal data from logs and prompts that don't need it, and know that regexes miss things.
- Label untrusted text as data and keep it out of the instruction text.
Lesson recap: validate at the edge, clean, redact, and keep data apart from instructions.
Quick quiz
- Why use an allow-list for an order id?
- What does NFKC normalisation help with?
- Why check the Luhn checksum before calling something a card number?
- Why reject long input instead of truncating it?
- Why is redaction not a guarantee?
Answers and explanations
- It accepts only a known-good shape, so a character you didn't anticipate can't slip through the way it can with a deny-list.
- It turns look-alike characters (such as full-width letters) into plain ones, so patterns and screens see what a person would.
- Many long numbers aren't cards. The checksum cuts false positives.
- Truncation changes what the customer said without telling anyone. A clear rejection keeps the system honest.
- Regular expressions only find common shapes. They miss names and addresses, and they can mask harmless text too.
Official references and further reading
Related tutorials