Make Prompt Injection a Type Error: Untrusted Text Your Prompt Builder Refuses A developer built a Python type-safety pattern that wraps all externally sourced text (web fetches, emails, tool results, user input) in a non-string `Untrusted` class, so prompt builders accept it only in delimited data slots while instruction slots take only string literals. The approach, which relies on pyright to catch injection-shaped mistakes before runtime and on a `__str__` that raises TypeError, aims to prevent outside text from reaching the instruction portion of a prompt. The developer notes mypy catches fewer cases than pyright, with one gap handled separately. Open OWASP's LLM Prompt Injection Prevention Cheat Sheet https://cheatsheetseries.owasp.org/cheatsheets/LLM Prompt Injection Prevention Cheat Sheet.html and the first vulnerable example is one line of string glue: full prompt = system prompt + "\n\nUser: " + user input Every value on that line is a str . The cheat sheet's structured version, create structured prompt system instructions: str, user data: str , labels the two parts inside the template, but the signature is still two str parameters. Pass them in the wrong order and nothing in your build complains. The cheat sheet is upfront that its templates are for formatting and "do not establish prompt-injection resistance." OWASP ranks prompt injection first in its 2025 Top 10 for LLM Applications https://genai.owasp.org/llmrisk/llm01-prompt-injection/ and splits it in two. Direct injection is the user typing the attack. Indirect injection "occurs when an LLM accepts input from external sources, such as websites or files." In both cases the bug in your code has the same shape: a value from outside the process reaches the part of the prompt that tells the model what to do. Nobody has solved the model believing what it reads. You can, however, stop your own code from putting outside text in the instruction slot, and a type checker is the tool for that. Text from web fetches, emails, tool results and the end user gets wrapped in an Untrusted object the moment an adapter receives it. Untrusted is not a str subclass. The prompt builder accepts it only in delimited data slots, and its instruction slot accepts only string literals from your source. pyright https://github.com/microsoft/pyright catches every mix shown below before the code runs. mypy https://mypy-lang.org/ catches fewer: an Untrusted that slips into an f-string still fails loudly at runtime, and the one case mypy misses entirely gets its own section. Untrusted where the text comes in NewType is the first thing you'd reach for, and it doesn't fit. The typing docs https://docs.python.org/3/library/typing.html newtype say the checker treats a NewType "as if it were a subclass of the original type", so NewType "UntrustedText", str is still accepted anywhere a plain str is. You need a class that isn't a string at all: python app/core/trust.py from future import annotations import secrets from dataclasses import dataclass from typing import Literal, LiteralString, final Source = Literal "user", "web", "email", "tool", "model" @final class Untrusted: """Text that came from outside the codebase.""" slots = " text", "source" def init self, text: str, source: Source - None: self. text = text self.source = source def str self - str: raise TypeError "pass Untrusted to PromptBuilder.data " def repr self - str: n = len self. text return f"Untrusted source={self.source r}, {n} chars " @final makes the checker reject any subclass, so nobody turns it into something that also inherits from str . Source is a closed Literal , so the label that ends up in the prompt can never be attacker text. str raises: f-strings, % formatting and str all go through it, so a stray f"Summarize {page}" fails on the first test run instead of shipping. repr still works, so %r or r in log calls and pytest's failure output stay readable. A plain %s in a log call goes through str and fails, as intended. The adapter is the only place a raw string becomes one. The port's return type is the contract: python app/core/ports.py from typing import Protocol from app.core.trust import Prompt, Untrusted class PageFetcher Protocol : def fetch self, url: str - Untrusted: ... class LLM Protocol : def complete self, prompt: Prompt - Untrusted: ... python app/adapters/web.py import httpx from app.core.trust import Untrusted class HttpxPageFetcher: def init self, client: httpx.Client - None: self. client = client def fetch self, url: str - Untrusted: resp = self. client.get url, timeout=10.0 resp.raise for status return Untrusted resp.text, source="web" The core never receives a raw str from the outside world, because no port hands one over. The httpx https://www.python-httpx.org/ adapter above, an email reader, a tool runner and your chat endpoint all follow the same pattern with their own source label. The LLM port returns Untrusted too, because a model's reply can repeat what it read. Adapters at the edge seal outside text; the core only ever handles the sealed version. The builder lives in the same module, so it is the one place that reads text : app/core/trust.py continued @dataclass frozen=True class Prompt: system: str user: str class PromptBuilder: def init self, instructions: LiteralString - None: self. instructions = instructions self. slots: list tuple LiteralString, Untrusted = def data self, name: LiteralString, value: Untrusted - PromptBuilder: self. slots.append name, value return self build mints a fresh tag on every call and wraps each slot in it: php PromptBuilder, continued def build self - Prompt: tag = f"data-{secrets.token hex 8 }" blocks: list str = for name, value in self. slots: text = value. text.replace tag, "" blocks.append f'<{tag} name="{name}" source="{value.source}" \n' f"{text}\n