The reliable story

Sending "tell me a story" to an LLM works, but the output is unpredictable. Sometimes you get a fairy tale, sometimes a horror story, sometimes a poem. Prompt engineering is the practice of writing instructions that consistently produce the output you need.

The prompt builder below reads from a StoryRequest object that carries the user inputs: character_name, character_age, story_theme, and story_length. For now, treat it as a simple container with those four fields. We will define it as a full Pydantic model when we add input validation.

service.py
python
def build_story_prompt(request: StoryRequest) -> str:
    length_map = {
        "short": "3-5 paragraphs, approximately 40-60 words",
        "medium": "5-7 paragraphs, approximately 100-150 words",
        "long": "8-12 paragraphs, approximately 200-300 words"
    }

    prompt = f"""You are a creative and gentle bedtime storyteller.

Write a personalized bedtime story with these details:
- Main character: {request.character_name}, age {request.character_age}
- Theme: {request.story_theme}
- Length: {length_map.get(request.story_length, length_map['medium'])}

Requirements:
1. Start with an engaging title
2. Write in clear paragraphs with natural breaks
3. Make it age-appropriate for a {request.character_age}-year-old
4. End with a gentle moral lesson
5. Keep the tone warm, comforting, and suitable for bedtime

Begin the story now:"""

    return prompt

A structured prompt has four parts: role (who the AI is), context (user inputs), instructions (what to produce), and constraints (boundaries and format).

Flashcards: Flashcards

Loading practice…

Not necessarily. Overly long prompts can confuse the model or cause it to ignore some instructions. The goal is clarity and specificity, not length. A well-structured prompt with clear sections (role, context, instructions, constraints) outperforms a wall of text every time.

Quiz: Quiz

Loading practice…

AI prompt: Try it: prompt engineering

Loading practice…

Checkpoint: Foundations checkpoint

Loading practice…