Build Your Own AI-Powered Choose Your Own Adventure

A Step-by-Step Python Guide for Beginners

In this project, you will write a Python program that uses real artificial intelligence

(ChatGPT) to create a story that changes based on YOUR choices.

Every time you play, the story will be different!

No coding experience needed — just follow the steps!

In this project, you will write a Python program that uses real artificial intelligence (ChatGPT) to create a story that changes based on your choices. Every time you play, the story will be different!

How to Read This Guide

This guide uses color-coded boxes to help you know what you’re looking at:

🟣 PURPLE — New Vocabulary
Explains new words or concepts.
🟢 GREEN — Terminal Commands
Commands for the terminal, NOT Thonny.
🟠 ORANGE — Tips & Hints
Helpful tips and suggestions.
🔴 RED — Warnings & Mistakes
Common errors and how to fix them.
🟦 TEAL — Expected Output
What you should see on screen.
⬛ DARK — Code to Type
Type this exactly into Thonny.

What You Need Before Starting

  • A Raspberry Pi that is turned on, connected to a monitor, keyboard, mouse, and the internet (Wi-Fi).
  • Thonny — the program where you write your code. It’s already installed on every Raspberry Pi. Look for a blue and white icon on the desktop or in the menu under Programming.
  • An API key — a special password that lets your program talk to ChatGPT. You’ll copy and paste it from www.sekol.ninja.
🟣 New Vocabulary: What is an API Key?

An API key is like a special password that lets one computer program talk to another. In this project, your Python program needs to talk to ChatGPT (which lives on the internet). The API key proves to ChatGPT that you have permission to use it.

Think of it like a library card — the library (ChatGPT) won’t let you borrow books (get AI responses) unless you show your card (API key).

Step 1:Open the Terminal

First, we need to install a small piece of software that lets Python talk to ChatGPT. To do this, we’ll use the terminal — the black window where you type commands directly to the computer.

Click the black rectangle icon in the top taskbar of your Raspberry Pi. A black window with a blinking cursor should open.

🟣 New Vocabulary: What is the Terminal?

The terminal (also called the “command line”) is a way to talk to your computer by typing text commands instead of clicking buttons. It’s what hackers use in movies! But in real life, it’s just a tool that programmers and cybersecurity experts use every day.

Step 2:Install the OpenAI Library

Type the following command into the terminal and press Enter:

pip install openai

Wait for it to finish. You’ll see some text scroll by as it downloads and installs. When you see the blinking cursor again, it’s done.

🟣 New Vocabulary: What is a Library?

A library (in coding) is a bundle of pre-written code that someone else made for you. Instead of writing hundreds of lines of code to connect to ChatGPT yourself, you just install the openai library and it handles all the complicated stuff. Think of it like using a recipe from a cookbook instead of inventing a dish from scratch.

🔴 If You See an Error

If you see a red error message, try this command instead:

pip install openai –break-system-packages

This is a Raspberry Pi-specific thing. It’s safe and normal.

Step 3:Open Thonny and Create a New File

Now close the terminal (type exit or click the X). Open Thonny by clicking its icon (blue and white logo) on the desktop, or find it in the Raspberry Pi menu under Programming → Thonny.

When Thonny opens, you’ll see two sections:

  • Top section — this is where you write your code (the “editor”)
  • Bottom section — this is where your program’s output appears (the “shell”)

Click File → Save As. Name your file adventure.py and save it to the Desktop.

🔴 Important: The File Name Must End in .py

Python files always end in .py — this tells the computer it’s a Python program. Make sure you type adventure.py (not just adventure).

Step 4:Import the Library

Now we start writing code! In the top section of Thonny (the editor), type the following:

# ============================================
# CHOOSE YOUR OWN ADVENTURE
# Powered by AI (ChatGPT)
# ============================================

# Import the library we need
from openai import OpenAI
🟣 What Does This Code Do?

Lines that start with # are called comments. The computer completely ignores them. They’re notes for humans reading the code.

The line from openai import OpenAI tells Python: “Go find the openai library we installed, and bring in the tool called OpenAI so we can use it.”

Step 5:Connect to ChatGPT

Press Enter twice after the last line (to leave a blank line), then type:

# Set up the connection to ChatGPT
# Get your API key from www.sekol.ninja
client = OpenAI(api_key="paste-your-api-key-here")
❗ Getting Your API Key

You need to replace paste-your-api-key-here with a real API key.

Go to www.sekol.ninja in your web browser and copy the API key from the page.

Then come back to Thonny and paste it between the quotation marks. It will look something like:
client = OpenAI(api_key="sk-abc123xyz456...")

Keep the quotation marks! The key must be inside the quotes.

🟣 What Does This Code Do?

This line creates a client — think of it as a phone that can call ChatGPT. The API key is like the phone number. Without it, you can’t make the call.

Step 6:Give the AI Its Personality

This is the fun part! We’re going to tell ChatGPT what kind of storyteller it should be. Add this code below what you already have:

# Tell the AI what kind of stories to create
system_message = {
    "role": "system",
    "content": """You are an adventure story master for kids.
You create exciting choose-your-own-adventure stories.

RULES:
- Keep the story fun, exciting, and kid-friendly.
- Each response should be 2-3 short paragraphs.
- Always end with exactly 3 numbered choices for what to do next.
- Use vivid descriptions to make the story come alive.
- The story should have a sci-fi space adventure theme.
- Never include anything scary, violent, or inappropriate."""
}
🟣 What Does This Code Do?

This creates a system message — it’s like a set of instructions you whisper to ChatGPT before the conversation starts. The player never sees this, but it controls HOW the AI tells the story.

"role": "system" tells ChatGPT “these are your instructions, not something the user said.”

The three quotation marks """ let you write a message that spans multiple lines.

🟠 Customize the Theme!

Want a fantasy adventure instead of sci-fi? A mystery? A pirate story? Change the RULES section to whatever you want! This is YOUR story engine.

Step 7:Create the Conversation History

Add this line below the system message:

# Create a list to keep track of the conversation
conversation = [system_message]
🟣 What Does This Code Do?

ChatGPT doesn’t have a memory on its own. Every time you send it a message, you have to send the entire conversation so far. This list called conversation stores every message — both yours and the AI’s.

Right now it only contains the system message. As the game goes on, we’ll add more messages to this list.

Step 8:Create the Welcome Screen

Add a welcome screen that the player sees when they start:

# Print the welcome screen
print("=" * 50)
print("  CHOOSE YOUR OWN ADVENTURE")
print("  Powered by AI")
print("=" * 50)
print()
🟣 What Does This Code Do?

print() displays text on the screen. "=" * 50 means “repeat the = sign 50 times” — it makes a nice decorative line. print() with nothing inside prints a blank line for spacing.

Step 9:Ask for the Player’s Name
# Ask the player for their name
player_name = input("Enter your character's name: ")
print()
print("Welcome, " + player_name + "! Your adventure begins...")
print()
🟣 What Does This Code Do?

input() pauses the program and waits for the player to type something. Whatever they type gets stored in player_name.

The + sign connects pieces of text together. So if the player types “Luna”, it prints: Welcome, Luna! Your adventure begins…

Step 10:Send the First Message
# Create the first message to start the story
first_message = {
    "role": "user",
    "content": "Start a new adventure story. My character's name is " + player_name + ". Begin the story!"
}
conversation.append(first_message)
🟣 What Does This Code Do?

This creates a message with "role": "user" — meaning it’s FROM the player TO the AI.

.append() means “add to the end of the list.” Now our conversation list has two items: the system message AND this first user message.

Step 11:Build the Game Loop

This is the biggest section — the engine that makes the whole game run. It’s a loop that keeps going: send a message to ChatGPT → show the story → ask the player → repeat.

⚠️ Indentation (the spaces at the beginning of lines) is very important in Python. Everything inside the loop must be indented with 4 spaces. Thonny should add the spaces automatically when you press Enter after a line ending with :

# The game loop
while True:
    # Send the conversation to ChatGPT
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=conversation
    )

    # Get the AI's story text
    story_text = response.choices[0].message.content

    # Save the response to conversation history
    conversation.append({
        "role": "assistant",
        "content": story_text
    })

    # Display the story
    print(story_text)
    print()

    # Ask what the player wants to do
    choice = input("What do you choose? (1, 2, 3, or 'quit'): ")

    # If they type quit, end the game
    if choice.lower() == "quit":
        print()
        print("Thanks for playing, " + player_name + "!")
        print("May the Code be with you!")
        break

    # Send the player's choice to the AI
    conversation.append({
        "role": "user",
        "content": "I choose option " + choice
    })

    print()
    print("Generating next chapter...")
    print()
🟣 What Does This Code Do? (Section by Section)

while True: — Creates a loop that runs forever (until we stop it). Each cycle = one “turn” of the adventure.

client.chat.completions.create(…) — This is the line that actually calls ChatGPT! It sends the entire conversation and gets back a response.

response.choices[0].message.content — The AI’s response comes in a structured package. This pulls out just the story text.

conversation.append(…) — Saves the AI’s response to our conversation list so it remembers what happened.

input(…) — Pauses and waits for the player to type their choice.

if choice.lower() == “quit”: — Checks if the player typed “quit” (or “QUIT” or “Quit” — .lower() converts it to lowercase first).

break — Stops the loop and ends the game.

🔴 Watch the Indentation!

Every line inside the while True: loop must start with 4 spaces. Every line inside the if block must start with 8 spaces (4 for the loop + 4 for the if).

If you see IndentationError, check that every line has the right number of spaces. Thonny usually handles this automatically, but if you’ve been copying and pasting, the spacing might be off.

Step 12:Save and Run Your Program!

You’re done writing code! Time to test it.

  1. Press Ctrl + S to save your file.
  2. Press the green Run ▶ button at the top of Thonny (or press F5).
  3. Look at the bottom section of Thonny (the shell). You should see:
==================================================
  CHOOSE YOUR OWN ADVENTURE
  Powered by AI
==================================================

Enter your character's name: 
  1. Type a character name and press Enter. Wait a few seconds while ChatGPT generates the first chapter.
  2. Read the story! At the end, you’ll see 3 choices. Type 1, 2, or 3 and press Enter.
  3. When you’re done playing, type quit to end.
🟠 It Takes a Few Seconds!

After you make a choice, the program sends your message to ChatGPT over the internet and waits for a response. This usually takes 3–10 seconds. Just be patient — the AI is writing your story!

Troubleshooting

If something goes wrong, check here first:

ErrorWhat to Do
ModuleNotFoundError: No module named 'openai'You skipped Step 2. Open the terminal and run: pip install openai --break-system-packages
AuthenticationError or Invalid API keyYour API key is wrong. Go back to www.sekol.ninja, copy the key again, and make sure it’s pasted between the quotation marks. No extra spaces.
IndentationErrorYour spacing is wrong. Lines inside the while loop need 4 spaces. Lines inside the if block need 8 spaces. Delete the spaces and re-type them.
SyntaxErrorYou have a typo. Check for missing quotation marks, missing colons (:) after while True and if statements, and missing parentheses.
Program runs but nothing happensIt’s waiting for you to type! Look at the bottom of Thonny (the shell) for a blinking cursor.
ConnectionError or TimeoutYour Pi isn’t connected to the internet. Check Wi-Fi (click the icon in the top-right).
RateLimitErrorToo many people using the key at once. Wait 30 seconds and try again.

Make It Your Own!

🎨 Change the Story Theme

Edit the system_message content (Step 6) to change what kind of stories the AI tells. Try:

  • A fantasy quest with dragons and wizards
  • A mystery detective story
  • A pirate adventure on the high seas
  • A zombie survival story (kid-friendly of course!)
  • A time-travel adventure through history
🚀 Add More Player Customization

Ask the player more questions at the start:

companion = input("Name your sidekick: ")
superpower = input("What is your superpower? ")

Then include them in the first_message content so the AI knows about them!

🏆 Challenge: Add a Score System

Create a variable called score = 0 at the beginning. Modify the system message to tell the AI to include score changes in the story like “+10 points for bravery!” Then use Python to track and display the running score.

Complete Code (All Together)

Here is the entire program in one place. If you got lost during the steps, use this as a reference. Remember to replace paste-your-api-key-here with your real API key from www.sekol.ninja.

# ============================================
# CHOOSE YOUR OWN ADVENTURE
# Powered by AI (ChatGPT)
# ============================================

# Import the library we need
from openai import OpenAI

# Set up the connection to ChatGPT
# Get your API key from www.sekol.ninja
client = OpenAI(api_key="paste-your-api-key-here")

# Tell the AI what kind of stories to create
system_message = {
    "role": "system",
    "content": """You are an adventure story master for kids.
You create exciting choose-your-own-adventure stories.

RULES:
- Keep the story fun, exciting, and kid-friendly.
- Each response should be 2-3 short paragraphs.
- Always end with exactly 3 numbered choices for what to do next.
- Use vivid descriptions to make the story come alive.
- The story should have a sci-fi space adventure theme.
- Never include anything scary, violent, or inappropriate."""
}

# Create a list to keep track of the conversation
conversation = [system_message]

# Print the welcome screen
print("=" * 50)
print("  CHOOSE YOUR OWN ADVENTURE")
print("  Powered by AI")
print("=" * 50)
print()

# Ask the player for their name
player_name = input("Enter your character's name: ")
print()
print("Welcome, " + player_name + "! Your adventure begins...")
print()

# Create the first message to start the story
first_message = {
    "role": "user",
    "content": "Start a new adventure story. My character's name is " + player_name + ". Begin the story!"
}
conversation.append(first_message)

# The game loop
while True:
    # Send the conversation to ChatGPT
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=conversation
    )

    # Get the AI's story text
    story_text = response.choices[0].message.content

    # Save the response to conversation history
    conversation.append({
        "role": "assistant",
        "content": story_text
    })

    # Display the story
    print(story_text)
    print()

    # Ask what the player wants to do
    choice = input("What do you choose? (1, 2, 3, or 'quit'): ")

    # If they type quit, end the game
    if choice.lower() == "quit":
        print()
        print("Thanks for playing, " + player_name + "!")
        print("May the Code be with you!")
        break

    # Send the player's choice to the AI
    conversation.append({
        "role": "user",
        "content": "I choose option " + choice
    })

    print()
    print("Generating next chapter...")
    print()

May the Code be with you!