The safe story

Your endpoint is streaming, but anyone can send any request. What happens when someone sends character_age: -5? Or a story_theme with a prompt injection? Validation and guardrails are what separate a demo from a real application.

models.py
python
from pydantic import BaseModel, Field

class StoryRequest(BaseModel):
    character_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        description="The name of the story's main character"
    )
    character_age: int = Field(
        ...,
        ge=1,
        le=18,
        description="Age of the character (1-18 years)"
    )
    story_theme: str = Field(
        ...,
        min_length=1,
        max_length=100,
        description="The theme of the story"
    )
    story_length: str = Field(
        ...,
        description="Desired length: 'short', 'medium', or 'long'"
    )

Pydantic validates every request automatically. Invalid data returns a 422 error with a clear message before your code even runs. This is your first line of defense.

Good catch. Pydantic handles structural validation (types, ranges, length limits), but content validation requires additional guardrails. You could add a blocklist for inappropriate themes, use a classification model to flag risky inputs, or constrain the theme to a predefined list. The key principle: validate before you spend money on an API call.

service.py
python
from fastapi import HTTPException

# A simple content guardrail: reject unsafe themes before the LLM call
BLOCKED_THEMES = {"violence", "horror", "weapons"}

def check_theme_safety(theme: str) -> None:
    lowered = theme.lower()
    if any(blocked in lowered for blocked in BLOCKED_THEMES):
        raise HTTPException(
            status_code=400,
            detail="That theme is not suitable for a bedtime story."
        )

This runs after Pydantic validates the structure and before the prompt is built, so bad themes never reach the LLM. A blocklist is the simplest guardrail; production apps often layer a classifier on top.

Quiz: Quiz

Loading practice…