Build a secure LLM wrapper with Python and Pydantic A developer tutorial recommends wrapping large language model calls with Python and Pydantic schema validation plus an Instructor middleware layer to block prompt injection and malformed output, citing a three-day production debugging incident where a model injected Markdown tables into a JSON parser. The guide advises XML-style delimiters such as tags, which it says work better with Claude 3.5 and GPT-4o, and Pydantic field constraints like Field(gt=0, lt=120) to reject hallucinated values before they reach a database. It also warns that prompt-based defenses against system-prompt leakage are weak and recommends a separate guardrail layer instead. Build a secure LLM wrapper with Python and Pydantic If you're building a wrapper around an LLM, the biggest mistake is treating the prompt as a static string and the output as trusted data. I spent three days last month debugging a "ghost" error where a model was injecting random Markdown tables into my JSON parser, crashing my production API. The fix wasn't a better prompt—it was strict schema validation. Stop trusting the LLM to "follow instructions" for formatting. Use Pydantic for structured outputs and a middleware layer to sanitize inputs. Prevent prompt injection using the delimiter strategy The classic "ignore all previous instructions and instead do X" attack still works if you just concatenate user input into a string. To stop this, you need to wrap user input in clear, distinct delimiters that the model is trained to recognize as boundaries. Don't just do f"Translate this: {user input}" . Do this instead: Use clear markers to separate system instructions from untrusted data def format prompt user query : return f""" You are a translation assistant. Translate the text enclosed in