AI Dungeon: Building an Interactive Text-Based Game with GPT-3

Objective: The objective of this project is to create a text-based game called AI Dungeon using the power of GPT-3. AI Dungeon allows players to embark on a limitless adventure where their actions and choices are interpreted by the AI, generating unique and dynamic responses. By building AI Dungeon, you will gain a deep understanding of how to integrate GPT-3 into an interactive application, harnessing its generative capabilities to create a captivating and immersive gaming experience.

Learning Outcomes: Upon completion of this project, you will:

  • Understand how to leverage GPT-3’s generative AI capabilities to create interactive experiences.
  • Gain proficiency in handling user inputs and processing them for optimal interaction with the AI.
  • Learn techniques for managing and controlling the AI’s responses to ensure a coherent and engaging gameplay.
  • Acquire skills in designing and developing a text-based game, emphasizing player choice and narrative branching.
  • Enhance your problem-solving abilities by addressing challenges in user experience, AI integration, and game design.

Steps and Tasks: Step 1: Set Up the Project

  • Create a new directory for your project and navigate into it.
  • Set up a virtual environment to isolate the project’s dependencies.
  • Install the required packages, including OpenAI’s gpt-3.5-turbo and Flask for web hosting.
  • Import the necessary modules and set up the OpenAI API with your GPT-3 API key.

Step 2: Define the Game’s Structure

  • Determine the theme and setting of your text-based game. It could be a fantasy quest, a sci-fi adventure, or any other genre of your choice.
  • Identify key decision points in the game where player choices will significantly impact the narrative.
  • Sketch out a basic flowchart or outline to visualize the branching paths and possible outcomes.

Step 3: Build the Gameplay Loop

  • Define a function that encapsulates the gameplay loop. This function will handle user inputs, process them, and generate AI responses.
  • Prompt the player for their actions or choices within the function.
  • Use the openai.ChatCompletion.create() method to send the player’s input to the GPT-3 API for generating a response.
  • Extract the AI’s reply from the API response and return it.

Step 4: Process User Inputs

  • Create a function to process the user’s inputs before sending them to the GPT-3 API. This processing step is crucial for providing clear instructions to the AI and ensuring coherent responses.
  • Remove any leading or trailing white spaces from the input.
  • Add a system message to provide context and instructions for the AI. This message should be formatted as a user message with a role of “system”.

Step 5: Generate AI Responses

  • Implement a function that utilizes the GPT-3 API to generate the AI’s responses based on the processed user inputs.
  • Call the openai.ChatCompletion.create() method, passing in the processed user inputs as the chat history.
  • Set the model parameter to “gpt-3.5-turbo” and the messages parameter to an array of user messages, including both the player’s input and the system message.
  • Extract and return the AI’s reply from the API response.

Step 6: Control and Enhance the AI’s Responses

  • Experiment with different parameters and techniques to control the AI’s responses and ensure a more game-like experience.
  • Adjust the temperature parameter to influence the randomness of the AI’s output. Higher values (e.g., 0.8) result in more diverse and unpredictable responses, while lower values (e.g., 0.2) make the output more focused and deterministic.
  • You can also modify the max_tokens parameter to limit the length of the AI’s response, forcing it to be more concise.
  • Implement a safety mechanism to prevent the AI from generating inappropriate or nonsensical content. You can use a simple text filter to check for banned words or phrases in the AI’s output, and if any are detected, regenerate the response.

Step 7: Implement Game Choices and Branching Narratives

  • Integrate meaningful choices and branching narratives into your game to create a compelling player experience.
  • Identify points in the game where the player’s actions should lead to different outcomes or paths.
  • When processing the user’s inputs, look for keywords or patterns that indicate a choice is being made.
  • Randomly select a few different options for each choice, and pass them as user messages with a role of “player” to the GPT-3 API.
  • Based on the player’s chosen option, determine the next steps in the game and present new choices or challenges.

Step 8: Host the Game

  • Create a Flask web application to host your AI Dungeon game.
  • Define a route for the game’s interface where players can interact with the text-based game.
  • In this route, call your gameplay loop function to process the player’s inputs and generate the AI’s responses.
  • Display the game’s interface, including the player’s input, the AI’s response, and a text field for the player to enter their next action.

Evaluation: To evaluate your project, you can consider the following points:

  • Creativity and User Engagement: The success of AI Dungeon lies in its ability to captivate players with imaginative and compelling narratives. Evaluate your project based on the creativity and engagement of the game’s storyline and interactions.
  • Seamless AI Integration: Assess how well you’ve integrated GPT-3 into the game. The AI’s responses should feel natural and coherent, seamlessly blending with the rest of the game.
  • Player Choice and Narrative Branching: A key aspect of text-based games is the impact of player choices on the narrative. Review your project based on the meaningful choices offered to players and the branching paths that result from these decisions.
  • Technical Implementation: Consider the technical aspects of your project, such as the robustness of user input processing, the effectiveness of response filtering, and the overall performance of the game.
  • Hosting and User Experience: Evaluate your project’s hosting capabilities and the user experience of the game interface. The hosting should be smooth and accessible, while the interface should be intuitive and immersive.

Resources and Learning Materials:

  1. OpenAI GPT-3 Documentation: OpenAI GPT-3 API Documentation
  2. Building Chatbots with GPT-3: OpenAI ChatGPT Guide How to build a chatbot with GPT-3
  3. Text-Based Game Design: Emily Short’s Interactive Storytelling Interactive Storytelling
  4. Flask Web Framework: Flask Documentation
  5. Git and Version Control: Git Documentation

Need a little extra help? Sure! Here’s some code to help you with the initial steps of the project:

Step 1: Set Up the Project

import openai
from flask import Flask, render_template, request

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

openai.api_key = 'your-gpt3-api-key'

Step 2: Define the Game’s Structure For this step, you can use pen and paper or any text editor to outline the structure of your game. Here’s a simple example:

You are in a dark forest. There are two paths ahead of you.
1. Take the left path.
2. Take the right path.

Step 3: Build the Gameplay Loop

def play_game():
    user_input = request.form['user_input']
    # Process user input
    # Generate AI response
    return render_template('game.html', user_input=user_input, ai_response=ai_response)

def home():
    return render_template('game.html')

@app.route('/game', methods=['POST'])
def game():
    return play_game()

if __name__ == '__main__':

Step 4: Process User Inputs

def process_user_input(user_input):
    processed_input = user_input.strip()
    system_message = {
        'role': 'system',
        'content': 'You are a brave adventurer in search of treasure. What do you do?'
    return processed_input, system_message

Step 5: Generate AI Responses

def generate_ai_response(processed_input):
    chat_history = [processed_input]
    response = openai.Completion.create(
    ai_response = response.choices[0].text.strip()
    return ai_response

Step 6: Control and Enhance the AI’s Responses

def filter_ai_response(ai_response):
    if 'attack' in ai_response:
        ai_response = ai_response.replace('attack', 'defend')
    return ai_response

Step 7: Implement Game Choices and Branching Narratives

def process_user_input(user_input):
    processed_input = user_input.strip()
    system_message = {
        'role': 'system',
        'content': 'You are a brave adventurer in search of treasure. What do you do?'
    return processed_input, system_message

def handle_user_choice(user_input):
    choice = int(user_input)
    if choice == 1:
        return 'You take the left path.'
    elif choice == 2:
        return 'You take the right path.'
        return 'Invalid choice. Please select 1 or 2.'

def process_user_input(user_input):
    if user_input.isdigit():
        return handle_user_choice(user_input)
    return user_input

def play_game():
    user_input = request.form['user_input']
    processed_input, system_message = process_user_input(user_input)
    ai_response = generate_ai_response(processed_input, system_message)
    return render_template('game.html', user_input=user_input, ai_response=ai_response)

Step 8: Host the Game You can use the following HTML template for your game interface. Create a new file called game.html in a templates folder in your project directory, and paste the code below into it.

<!DOCTYPE html>
    <title>AI Dungeon</title>
    <h1>AI Dungeon</h1>
    <form action="/game" method="POST">
        <p>{{ user_input }}</p>
        <p>{{ ai_response }}</p>
        <input type="text" name="user_input" autocomplete="off">
        <input type="submit" value="Submit">

Remember to install the required packages, set up your GPT-3 API key, and create a Flask application. These initial code snippets should help you get started with the project. As you progress, you can refer to the OpenAI documentation and explore more advanced techniques to enhance your game’s AI interactions and develop complex branching narratives. Happy coding, and have fun building your own version of AI Dungeon!

@joy.b has been assigned as the mentor. View code along.