Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Beginner ⏱ 25 min

📖 Build an AI Story Generator with Ollama

🎯 What You'll Build

A creative story generator powered by a local Llama model — input a character, setting, and genre, and watch an original story appear word by word, fully offline.

📋 What You'll Need

1

Design a story prompt template

Structured prompts produce better, more focused stories than open-ended ones.

def build_story_prompt(character, setting, genre, length='short'):
    word_counts = {'short': '300-400', 'medium': '500-700', 'long': '800-1000'}
    words = word_counts.get(length, '300-400')

    return f"""You are a creative fiction writer. Write an original {genre} short story.

Requirements:
- Main character: {character}
- Setting: {setting}
- Genre: {genre}
- Length: {words} words
- Include a beginning, conflict, and satisfying resolution
- Write in third person
- Start directly with the story — no title, no preamble

Begin the story now:"""

prompt = build_story_prompt(
    character = "a retired astronaut who can hear the future",
    setting   = "a lighthouse in 1920s Scotland",
    genre     = "mystery",
)
print(prompt[:200])  # Preview the prompt
2

Stream the story from Ollama

Streaming prints each word as the model generates it — much better UX than waiting for the whole story.

import requests, json, sys

def generate_story_streamed(prompt, model='llama3.2'):
    with requests.post(
        'http://localhost:11434/api/generate',
        json={'model': model, 'prompt': prompt, 'stream': True},
        stream=True, timeout=180,
    ) as resp:
        print("\n" + "="*50 + "\n")
        for line in resp.iter_lines():
            if line:
                data = json.loads(line)
                token = data.get('response','')
                print(token, end='', flush=True)
                if data.get('done'):
                    print("\n\n" + "="*50)
                    break

# Generate a story
prompt = build_story_prompt(
    character = "a retired astronaut who can hear the future",
    setting   = "a lighthouse in 1920s Scotland",
    genre     = "mystery",
)
generate_story_streamed(prompt)
3

Interactive CLI with user input

Ask the user for their own character, setting, and genre.

def main():
    print("AI Story Generator (powered by Ollama + llama3.2)")
    print("Press Ctrl+C at any time to exit.\n")

    while True:
        character = input("Main character (e.g. 'a time-travelling chef'): ").strip()
        setting   = input("Setting (e.g. 'a space station in 2150'): ").strip()
        genre     = input("Genre (mystery / romance / thriller / sci-fi / fantasy): ").strip()
        length    = input("Length (short / medium / long) [short]: ").strip() or 'short'

        if not character or not setting or not genre:
            print("Please fill in all fields.\n"); continue

        print("\nGenerating your story...")
        prompt = build_story_prompt(character, setting, genre, length)
        generate_story_streamed(prompt)

        again = input("\nGenerate another? (y/n): ").strip().lower()
        if again != 'y': break

main()
💡 Tip: If the story cuts off, increase the Ollama context window: add "options": {"num_ctx": 4096} to the JSON payload. The default context is 2048 tokens which limits story length.

🎉 You Did It!

A creative writing assistant running entirely on your laptop. No censorship, no rate limits, no cost. The same pattern — structured prompt template + streaming response — works for any generation task: poems, scripts, dialogues, or marketing copy.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.