0% found this document useful (0 votes)
14 views84 pages

AI-Powered App Development Guide

This document provides a comprehensive guide on using AI templates to build applications, emphasizing the shift in software engineering roles from coding to specifying requirements and validating outputs. It outlines the necessary setup for an AI-assisted coding environment, including installing Python, an IDE, and obtaining an OpenAI account. The document also details a step-by-step approach to application development using AI, highlighting the importance of prompt engineering for effective code generation.

Uploaded by

hkrroy270
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views84 pages

AI-Powered App Development Guide

This document provides a comprehensive guide on using AI templates to build applications, emphasizing the shift in software engineering roles from coding to specifying requirements and validating outputs. It outlines the necessary setup for an AI-assisted coding environment, including installing Python, an IDE, and obtaining an OpenAI account. The document also details a step-by-step approach to application development using AI, highlighting the importance of prompt engineering for effective code generation.

Uploaded by

hkrroy270
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Contents

1 AI templates to build your entire application . . . . . . . 1


1.1 The state of the world in AI assisted coding . . . . . . 3
1.2 How software engineering roles change when using AI 4
1.3 Your code may vary . . . . . . . . . . . . . . . . . . . . 5

2 Setup your environment . . . . . . . . . . . . . . . . . . . 6


2.1 Install Python . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Install an IDE (i.e. PyCharm) . . . . . . . . . . . . . . 8
2.3 Create your OpenAI account . . . . . . . . . . . . . . 10
2.4 Install the CodeGPT plugin . . . . . . . . . . . . . . . 14
2.5 Idea, set, let’s go . . . . . . . . . . . . . . . . . . . . . . 16

3 Prompt One: Start your web project (with Django) . . . 20


3.1 The Model-View-Controller (MVC) Architectural Pat-
tern . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Prompt Two: Create your models . . . . . . . . . . . . . . 26


4.1 Designing Models . . . . . . . . . . . . . . . . . . . . . 26
4.2 Err on the side of too much detail in prompts . . . . . 28
4.3 Running Django test cases . . . . . . . . . . . . . . . . 35

5 Prompt Three: Implement your first use case . . . . . . 36


5.1 Define the user personas . . . . . . . . . . . . . . . . . 36
5.2 Define what actions each user person can take . . . . 37

6 Prompt Four: Implement a business service . . . . . . . 43


CONTENTS

6.1 Implement a generative AI service . . . . . . . . . . . 44


6.2 Parse the data returned from a generative AI function 47

7 Prompt Five: Implement a complex use case . . . . . . . 51


7.1 Modify our existing implementation to create multi-
ple quiz questions . . . . . . . . . . . . . . . . . . . . 55
7.2 Modify the existing page style . . . . . . . . . . . . . . 58

8 Prompt Six: Implement a use case that uses generated


data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
8.1 Persist the results to the database . . . . . . . . . . . . 67

9 Prompt Seven: User authentication . . . . . . . . . . . . . 68

10 Prompt Eight: Reporting use case . . . . . . . . . . . . . 74


10.1 Creating a graph based on your data . . . . . . . . . 74

11 Prompt Checklist . . . . . . . . . . . . . . . . . . . . . . . 80
1 AI templates to build
your entire application
The world of software development has completely changed. Arti-
ficial Intelligence (AI) makes it easy to create entire applications,
chatbots, and websites. OpenAI’s ChatGPT, Google Bard, Mi-
crosoft Bing, and GitHub Copilot can all write and debug code in
almost any programming language.
This book contains step by step prompt templates you can use to
generate your application code using AI services. The approach
detailed here follows a proven system design and development
methodology. The difference with this approach vs. traditional
software development is that the coding portion is accelerated from
months to days using AI.
You design your application largely by defining the requirements.
The design is comprised of natural language descriptions of the data
your application manages and what users can do with it in your
system. Software development methodologies have already been
doing this. The difference with an AI-assissted approach is that
you need to be precise in terms of the details.
Traditional software development leaves room to elaborate on the
requirements through each iteration. While this is still true, when
it comes time to prompt the AI to generate code, you need to give it
all of the relevant information about how your application should
work.
The term prompt engineering is commonly used to reference the
activity of constructing prompts that create the desired output. This
is a fancy term for a simple concept, but an important one. Simply
put, you need to be able to define and capture your thoughts in
clear, English text that can be used in a prompt.
AI templates to build your entire application 2

A problem well-stated is half solved.

—Charles Kettering

Charles Kettering was the head of research at General Motors from


1920 to 1947. This quote has never been more true. Fortunately,
AI enables us to deal with the other half of the problem faster than
ever before.
You fill in your specific application details in the AI prompt
templates provided in this book. These prompts must specify your
requirements, so be as detailed as possible. Any detail that you
do not provide will be decided by the AI. In some cases, you may
be happy with what it generates. In other cases, you may want
something different than what it chose. More often tha not, you
will have specific constraints and ideas about how your application
should work. Be sure to think through these details and include
them in the prompt templates.
A series of prompts is needed because you won’t be able to generate
your entire application in one prompt, unless it is very tiny. AI is
amazing, but does not have the ability to manage that much context
at a time. Coding assistants are incredibly good at writing isolated
or small-scale software functions. However, you need a full-scale
software application, website, or service.
You will use an iterative process to create your application as shown
in the diagram below.
AI templates to build your entire application 3

1.1 The state of the world in AI


assisted coding
As of the time of writing (summer 2023), AI can write about 90%
of your code completely and accurately. This is not clickbait, I will
show you the data. It is quite incredible what it can do.
Even for problems it can’t entirely solve, it can shorten the coding
time from hours to minutes. Incomplete solutions that it generates
provide a great start. They can even be an inspiration for ideas
about how to finish or rewrite the solution.
This is not hands-free driving though. AI generated code can still
contain subtle bugs. For example, it can generate code to insert data
into a database that fails to consider referential integrity checks.
Sometimes it fails to properly create or parse JSON data.
AI templates to build your entire application 4

Fortunately, there are techniques you can use to quickly remediate


these issues. For example, we have found that having AI generate
and parse XML data is far more reliable than plain text or JSON
formats.
Your role as a software engineer changes with AI. You are a
designer. You are a code reviewer. You are an assembler. The good
news is, the whole process goes much faster. You can impress your
manager or build that startup idea you’ve been waiting to bring
to life. The world of software development has changed, for the
better.

1.2 How software engineering roles


change when using AI
The table below shows how traditional software engineering tasks
change in an AI-powered world. The emphases moves from writing
code to specifying requirements, validating output, and assembling
the final result. It is critical to prompt AI to generate tests at each
step of the process and run those tests.

Traditional Engineering AI-assisted Engineering


Tasks Tasks
Obtain specifications Write specifications
Design use cases Design use cases
Write code Prompt to generate code
Perform code reviews Review AI output
Integrate code into project
Write test cases Prompt to generate test
cases
Run tests Run tests
AI templates to build your entire application 5

This book walks you through the entire process, step by step. The
secret to effectively using AI is to break up the process into smaller
steps. This allows the AI to create your software a few components
or functions at a time, an amount of code that fits within its context
limits.
Following a step-by-step process is beneficial for both you and your
AI assistant. It helps you to think through the details of each use
case. You start with a high-level business idea. Then you model the
data for the application. Then you define the use cases that each
actor in the system can perform. Each step along the way requires
detailed information in the prompts so that AI can generate the code
that meets your requirements. Breaking down the development
into a step by step process forces you to think through how you
want each step to work.
A little bit of design goes a long way in terms of code generation.
So once you have the vision in mind for your app, you are ready to
get started.

1.3 Your code may vary


One last thing to note is code you generate may be different than
the examples shown here. That is perfectly okay. In software, there
are many different ways to accomplish the same thing.
The important thing is that whatever the implementation is, it
produces the desired result. The same test cases should pass on
an implementation generated by ChatGPT, Bard, or any other AI
assistant.
With that introduction out of the way, let’s get your environment
setup.
2 Setup your
environment
Python is the primary programming language used in this book.
However, the techniques are applicable to any common program-
ming language.
The primary items you need are:

• An OpenAI ChatGPT account and API key. This is free to


obtain from OpenAI.
• A coding environment with Python, an IDE (we use Py-
Charm), and the CodeGPT plugin installed.
• Optionally, you can create an account on the repl.it1 website.
There is a template created for this book that already has all
of the required libraries installed and ready to go.

For beginners, we recommend using the [Link] site that has


templates for push-button environment setup. You can use this
online programming environment to run examples from the book.
The Gradio template2 has support for Python and the early exam-
ples in the book with web interfaces. The Django3 template allows
you quickly build web apps, including examples from this book.
Eventually, you will want to have your own workstation or envi-
ronment configured with Python and the OpenAI libraries. We
use the PyCharm IDE in the examples in this book. However,
you can also use Visual Studio Code (VSCode) or any other IDE.
We recommend you use an IDE that supports AI plugins, such
1 [Link]
2 [Link]
3 [Link]
Setup your environment 7

as CodeGPT. These plugins make working with AI services much


easier during the development process.
Even if you are not familiar with the libraries or frameworks used
in the examples, that is okay. In fact, that is the whole point. You
can use ChatGPT to give you all the setup instructions or explain
what certain components do.
You can also go back and forth between the online [Link]
environment and your local workstation. [Link] allows you to
download the entire project as a zip file, which you can then easily
unzip and open up in your IDE.
You can create code with ChatGPT chatbot on any operating system
such as Windows, macOS, Linux, or ChromeOS. You do not need a
powerful computer with a high-performance CPU or GPU because
the AI processing is handled by OpenAI’s API on the cloud. Your
computer’s hardware is not a limiting factor.

2.1 Install Python

If you do not already have Python installed, browse to downloads4


to obtain the setup file for your platform.
4 [Link]
Setup your environment 8

Run the setup file and be sure to enable any checkbox for adding
Python to your path. Click “Install Now” and follow the steps to
install Python. You can verify that Python is installed using the
following command. Depending on your system, you may need to
specify python3. We use a virtual environment that is set up by
PyCharm (more info on that in a moment).

1 (venv) broemmerd$ python --version


2 Python 3.9.14
3 (venv) broemmerd$ python3 --version
4 Python 3.9.14

2.2 Install an IDE (i.e. PyCharm)


We use the PyCharm IDE, although you can use Visual Studio
Code or another IDE. If you don’t already have an IDE, browse
to PyCharm5 and download the file for your platform. There is a
paid version, but the Community (free) edition works very well.
5 [Link]
Setup your environment 9

Run the installation file and create a new project in the desired di-
rectory. PyCharm will automatically create a virtual environment
for your project. After creating your project, go to the terminal to
install the required libraries. The icon to open the terminal is in the
lower-left corner of the IDE.
Pip, the Python package manager, was also installed when you
installed Python. However, it is a good practice to update it first.
Run the following command in the terminal window.

1 python -m pip install -U pip

Using the python -m prefix ensures you are running the install
within your virtual environment.
Now install the OpenAI client library using the following com-
mand.

1 python -m pip install openai

Also, install the following libraries.


Setup your environment 10

1 python -m pip install python-dotenv


2 python -m pip install gradio

The python-dotenv library will be used so that you can safely store
your OpenAI API key, without having to insert it directly into your
code. The code will read your API key from an environment file.
The gradio library is an exceptionally useful library that quickly
makes web interfaces based on Python functions. This allows you
to visually interact with your applications quickly. You can easily
create an MVP using this library.

2.3 Create your OpenAI account


To write software assisted by ChatGPT, you’ll need to obtain an
API key from OpenAI. This key allows you to use the ChatGPT
model within your own interface and display the results in real-
time. OpenAI currently offers free API keys, which includes $5 of
free credit for the first three months.
After the free credit has been used up, you’ll need to pay for
continued API access. However, at present, the API access is
available to all free users.
To get started, browse to OpenAI6 to signup and create a free
account. If you already have an account with OpenAI, simply log
in to your existing account.
On the OpenAI webpage, click on your profile in the top-right
corner and select “View API keys” from the drop-down menu.
6 [Link]
Setup your environment 11

Click on “Create new secret key” and copy the API key. It is
important to note that you can’t view the full API key later. Save it
in a safe place immediately. If something happens, you can always
come back and create a new API key or remove old ones.

Your key, the character string, will be used in your code that calls
ChatGPT, as well as in the configuration of the CodeGPT plugin.
As noted earlier, avoid putting your key in the actual code.
To configure your key in an environment settings file, right-click
on your project in PyCharm and select the menu item New | File.
Name the file .env
In this file, define an environment variable that contains your key.
This will be referenced in the code at runtime.
Setup your environment 12

Let’s test the configuration by making a call to ChatGPT. Create a


file named call_chatgpt.py in your project. Add the following code.
call_chatgpt Python function

1 import openai
2 import os
3
4 # Set the OpenAI key
5 from dotenv import load_dotenv
6 load_dotenv()
7 openai.api_key = [Link]("OPENAI_API_KEY")
8
9 # Define the function to call the API
10 # The temperature is the amount of randomness and creativ\
11 ity,
12 # a value between 0 and 2. Higher values make the output \
13 more random,
14 # while lower values are more focused and deterministic.
15 def generate_code(prompt, temperature = 0.5, max_tokens =\
16 256):
17 response = [Link](
18 engine="text-davinci-003",
19 prompt=prompt,
20 max_tokens=max_tokens,
21 temperature=temperature
22 )
23
24 # Extract the response text
Setup your environment 13

25 return [Link][0].[Link]()
26
27 # Lets write some code
28 prompt = (
29 "Write a python function that takes a String "
30 "as input and returns a counts of the number "
31 "of vowels in the string"
32 )
33
34 code = generate_code(prompt)
35 print(code)

This is the basic code to make a call to ChatGPT. Let’s examine


what is happening here.
First, we import the openai library, the ChatGPT client. We
also import the os library, and the load_dotenv function from the
python-dotenv library. This lets us use the environment file we
created with the API key. The load_dotenv function is invoked, and
that makes our OPENAI_API_KEY accessible to the code through
the [Link] function.
The generate_code method uses the OpenAI Completion AI. It
takes the prompt as a parameter, and optionally, you can specify
the temperature and max tokens. As noted in the comments,
the temperature tells ChatGPT how creative or consistent to be
with its answers. A chatbot may require a higher degree of
creativity, whereas a coding assistant is well served using a bit more
consistency.
The max tokens is a limit on how many tokens can be used.
From the API documentation, “The token count of your prompt
plus max_tokens cannot exceed the model’s context length. Most
models have a context length of 2048 tokens (except for the newest
models, which support 4096).”
The context refers to the limit discussed in the first chapter on how
Setup your environment 14

much information ChatGPT can process at a time. Tokens also


relate to your usage of the API, which at first uses the free tokens
given to you when you create an account. Following that, there is
a nominal cost for tokens. See the OpenAI pricing page7 for more
information.
When we run this code asking ChatGPT for a function that counts
vowels, we get the following output.
ChatGPT generated function code

1 def countVowels(string):
2 vowels = 'aeiou'
3 count = 0
4 for char in string:
5 if char in vowels:
6 count += 1
7 return count
8
9 print(countVowels('Hello World')) #3

This function doesn’t look for uppercase vowels, but it does work
for lowercase letters. As you can see already, coding with ChatGPT
can be incredibly productive, but it will also require an iterative
process. We can improve upon this implementation. We will learn
all about iterative development with ChatGPT starting in the next
chapter.

2.4 Install the CodeGPT plugin


We just demonstrated how you can call ChatGPT from Python
code. It will be more convenient during development, however,
if you can invoke ChatGPT directly from your IDE. The CodeGPT
7 [Link]
Setup your environment 15

plugin is available for both PyCharm and Visual Studio Code. Let’s
install this plugin and see how it is used.
Go to the PyCharm File | Settings, or Preferences on Mac OS. Select
Plugins from the list on the left and make sure you are on the
Marketplace tab. Search for CodeGPT and once you find it, click
the Install button. PyCharm will be restarted for the plugin to take
effect.
Now you need to configure the CodeGPT plugin, minimally with
your API key so it can make calls to ChatGPT. In the same
settings interface, search for CodeGPT. Enter your API key in the
appropriate field and click OK. You shouldn’t need to change any
other configuration options at this time.

Now you can right click in the editor, and see the CodeGPT |
Ask ChatGPT option. This allows you to make general queries
to ChatGPT, as if you were on the web interface. However, you
can also select portions of code and right-click for context-sensitive
calls to ChatGPT. We will leverage these features throughout the
Setup your environment 16

book.

2.5 Idea, set, let’s go


Now that you have everything you need, you can get started.
First, create a directory for your application. Name it based on your
application idea. I’ve called mine “template” but you should name
yours according to your application concept.
In PyCharm, select the menu option File | New Project. You will
see a popup window similar to the one below.
Setup your environment 17

Change the location folder at the top to the directory you just
created. Select the option to create a [Link] script at the bottom.
Your project will look something like this.

If you are not familiar with PyCharm, take a minute to get used to
it. By default, the green arrow icon near the upper right corner will
run the main welcome script that was generated. Clicking that will
open a shell window at the bottom of the screen and you will see
the Hi, PyCharm printed to the terminal.
Setup your environment 18

You have two other basic options to run applications.

1. Open a terminal window and run a command.


2. Right-click a Python file in the left hand side directory tree,
and click the Run option.

You will need to use the terminal window to install a few Python
packages before we get into building our application. Pip, the
Python package manager, was installed when you installed Python.
Open a terminal as shown in the image below and run the com-
mand:

1 python -m pip install python-dotenv

Also install the package for your AI coding service.

1 python -m pip install openai


2 python -m pip install bardapi
3 python -m pip install EdgeGPT

We will use the web framework Django to build our application.


It is a common web framework for Python developers found at
[Link] From its website, Django is de-
scribed as “a high-level Python web framework that encourages
rapid development and clean, pragmatic design.”
You may not know anything about Django, and that is okay. Your
AI coding assistant will help you, and so will we.
Setup your environment 19

By default, Django is configured to use SQLite as its database. This


is great for development, but by the time you get to production, you
can swap it out for a database such as Postgres.
Our environment is prepared. We are ready for our first prompt.
Note that in this book, generic prompt templates are provided for
each step in the process. In order to make these prompts more
tangible, we will build an online quiz application and show those
specific prompts based on the templates. These are only examples.
You can customize the templates to build whatever application you
want.
Prompt templates are shown using the following format.

Prompt template
Write Python code for a name type class
Example prompt
Write Python code for a Quiz model class.
Test prompt
Write a Python unittest for the Quiz model class.

Terms in brackets are named according to what the placeholder


should contain. You will substitute in terms specific to your
requirements.
3 Prompt One: Start your
web project (with
Django)
All of the code from this book can be found on GitHub1 .
Use the following prompt to create the basic project structure.

Prompt Template
Create a small example to say hello world using the web_-
framework framework
Example Prompt
Create a small example to say hello world using the Django
framework

You will get the complete instructions to setup the environment and
run a Hello World example. For example, ChatGPT provided the
following instructions.
Install Django: If you haven’t already, you can install Django by
running the following command in your terminal.

1 python -m pip install Django

Create a new Django project: Open your terminal or command


prompt, navigate to the desired directory, and run the following
command. This will create a new Django project named “hel-
loworld” in a directory with the same name.

1 [Link]
Prompt One: Start your web project (with Django) 21

1 django-admin startproject helloworld

Create a Django app: Change into the project directory by running


cd helloworld, and create a new Django app using the following
command.

1 python [Link] startapp helloworldapp

Define a view: Open the file helloworldapp/[Link] and replace


its contents with the following code:

1 from [Link] import HttpResponse


2
3 def hello_world(request):
4 return HttpResponse("Hello, World!")

Create a URL mapping: Open the file helloworld/[Link] and


replace its contents with the following code:

1 from [Link] import path


2 from [Link] import hello_world
3
4 urlpatterns = [
5 path('', hello_world, name='hello_world'),
6 ]

Start the development server: Go back to the project’s root


directory (helloworld) and run the following command in your
terminal.

1 python [Link] runserver

Test the application: Open your web browser and visit


[Link] You should see the “Hello, World!” message
displayed.
Prompt One: Start your web project (with Django) 22

At first, the difference between projects and apps in Django may


seem confusing. The Django documentation says that:

• An app is a web application that does something – e.g., a blog


system, a database of public records or a small poll app.
• A project is a collection of configuration and apps for a
particular website. It can contain multiple apps. Right now,
your HelloWorld project has one app called HelloWorldApp.

The database configuration is defined in the helloworld/[Link]


file. It uses SQLite by default. After you run the first time, you
will see a db.sqlite3 file created in the project root directory.
You can login to this SQLite database using the command sqlite3
db.sqlite3. It is empty to begin, as no tables have been created
yet. Django uses the concept of database migrations to create
tables. There are some built in applications that come with Django,
some which use database tables. You likely saw a warning when
you started the server that these migrations can be run using the
following command. Go ahead and run that command now.

1 (venv) broemmerd$ python [Link] migrate


2 Operations to perform:
3 Apply all migrations: admin, auth, contenttypes, sessio\
4 ns
5 Running migrations:
6 Applying contenttypes.0001_initial... OK
7 Applying auth.0001_initial... OK
8 Applying admin.0001_initial... OK
9 ...
10 Applying sessions.0001_initial... OK

Now if you login, you see the tables that are created.
Prompt One: Start your web project (with Django) 23

1 (venv) broemmerd$ sqlite3 db.sqlite3


2 SQLite version 3.28.0 2019-04-15 14:49:49
3 Enter ".help" for usage hints.
4 sqlite> .tables
5 auth_group auth_user_user_permissions
6 auth_group_permissions django_admin_log
7 auth_permission django_content_type
8 auth_user django_migrations
9 auth_user_groups django_session

3.1 The Model-View-Controller (MVC)


Architectural Pattern
The prompt templates in this book are based on the Model-View-
Controller (MVC) architectural pattern. This pattern defines the
types of components that make up the application and the way in
which they interact. This pattern is used by many web develop-
ment frameworks such as Django.
Unfortunately, Django changes the terminology just a bit. It uses
a Model-View-Template pattern. Each component type is defined
below.

• Model classes represent business entities and they implement


reading and persisting data to a database.
• Views implement the logic used when a user browses to an
application URL or submits a form.
• Templates contain the HTML and associated presentation
logic used to generate the web page and user interface.

The following diagram shows the interaction between these com-


ponent types in the architecture.
Prompt One: Start your web project (with Django) 24

Your directory structure in PyCharm should now look something


like the image shown below.
Prompt One: Start your web project (with Django) 25

The model classes are stored in the [Link] file. The views,
likewise, are stored in the [Link] file. Create a templates
directory in the helloworldapp folder. This directory will store your
html templates.
You will be using prompts to generate code, and then pasting that
code into the appropriate location. Be sure to familiarize yourself
with the project structure so you can be efficient at integrating code
generated by your AI helper.
One recommendation to simplify project organization is having a
having a [Link] file to store reusable functions. This is not
required by Django. However, it is a common construct that has
been helpful for designing applications for many years.
At the end of the day, it is up to you how you want to organize
the code within your project. As long as you know where different
types of components are stored and it makes sense to you, then you
are in good shape.
4 Prompt Two: Create
your models
The best place to start building an application is by modeling your
data. If you have a good understanding of your data model, you
will also have a solid foundation for designing the rest of your
application.
Model classes are a great place to start when building Django
web applications. Once you have model classes, you can create
the corresponding database tables as well. Model classes typically
provide the building blocks for everything else you build in the
application.

4.1 Designing Models


If you have software design experience, you are likely able to design
your application model classes. Models in Django are analogous to
database entity-relationship modeling. These are often captured
using an Entity-Relationship Diagram (ERD). After you have the
design, you can still have AI write the model code for you.
However, If you are not comfortable doing the entity modeling
yourself, you can also have your AI assistant help.
Use a design prompt based on the template below. The require-
ments in this template are essentially your high-level application
requirements. You may have more or less than three requirements.
Non-trivial applications will likely have more than three require-
ments.
Prompt Two: Create your models 27

You can also break this up into multiple prompts. This becomes
more important if you have a large number of requirements and
model entities.

Prompt template
You are a software designer building a project_name appli-
cation. Define the model classes needed to implement the fol-
lowing requirements. 1. Requirement_1 2. Requirement_2
3. Requirement_3
Example prompt
You are a software designer building an online quiz appli-
cation. Define the model classes needed to implement the
following requirements. 1. Each quiz has a given name and
topic. 2. Each quiz can have many questions. 3. Store the
results for each quiz taken by a participant.
Test prompt
None. Review the AI output.

A portion of the response from the quiz prompt is shown below.


Prompt Two: Create your models 28

Review the models defined in the AI response. Does it seem like


it meets your expectation? If it doesn’t, you can use follow up
prompts to change the model based on your needs.

A common problem in this phase is a lack of detail. Be


specific whenever possible.

4.2 Err on the side of too much detail


in prompts
In the absence of details, AI makes assumptions to fill in the gaps. If
you don’t provide specifics, AI will choose for you. And it’s choices
may not be what you had in mind. Providing enough detail and
Prompt Two: Create your models 29

context is critical to the efficiency of this process. The more detail,


the better.
There are context limits to what AI can remember at a given time.
Nonetheless, it is better to err on the side of too much context rather
than too little. If you do hit a context limit, then you can dial back
how much detail you give the AI in a given prompt.
How will you know that you hit a context limit? Typically, the AI
response is cut short in the middle of a sentence or a thought.
If this occurs, break the prompt down into multiple prompts. You
can split out related requirements into smaller groups and run
subsequent prompts to cover all of them.
As AI capabilities grow more advanced, the context (or token)
limit will expand. Building the entire application may one day be
possible with a single prompt. However, we are not there yet. The
process of building the application is, in itself, decomposing the
overall problem into a series of smaller, manageable steps.
It is also important to remember that this is an iterative process. It’s
perfectly okay if the AI doesn’t produce exactly what you want on
the first try. The great thing about AI assistants is that they retain
context and can modify models and code previously generated.
You will be continually reviewing the AI output and modifying the
results through additional prompts. Once you are satisfied with the
output, then you can proceed to the next step in the process.
Use the following prompt to generate the Python Django code for
your models.

Prompt template
Write the Python code for these model classes based on the
framework_name framework
Example prompt
Write the Python code for these model classes based on the
Django framework
Prompt Two: Create your models 30

Test prompt
Write Django test cases for these models

Here is a portion of the sample response from ChatGPT. Copy this


code and place it in your [Link] file.

Anytime you have new or updated model classes, you will want to
create migrations and apply them to your database. To do this, you
first need to let Django know to look in your applications.
Open the helloworld/[Link] file in PyCharm, and add the
HelloworldappConfig line to the INSTALLED_APPS section:
Prompt Two: Create your models 31

1 # Application definition
2
3 INSTALLED_APPS = [
4 '[Link]',
5 '[Link]',
6 '[Link]',
7 '[Link]',
8 '[Link]',
9 '[Link]',
10 '[Link]',
11 ]

Now run the following commands.

1 (venv) broemmerd$ python [Link] makemigrations


2 Migrations for 'helloworldapp':
3 helloworldapp/migrations/0001_initial.py
4 - Create model Participant
5 - Create model Quiz
6 - Create model Result
7 - Create model Question
8 - Create model Answer
9
10 (venv) broemmerd$ python [Link] migrate
11 Operations to perform:
12 Apply all migrations: admin, auth, contenttypes, hellow\
13 orldapp, sessions
14 Running migrations:
15 Applying helloworldapp.0001_initial... OK

The first command created the migration files which define the
database tables using a Django DSL, or Domain-Specific Language.
The second command runs the file against the database to actually
create the tables. You can now login to the sqlite database and see
the tables.
Prompt Two: Create your models 32

1 (venv) broemmerd$ sqlite3 db.sqlite3


2 SQLite version 3.28.0 2019-04-15 14:49:49
3 Enter ".help" for usage hints.
4 sqlite> .tables
5 auth_group django_migrations
6 auth_group_permissions django_session
7 auth_permission helloworldapp_answer
8 auth_user helloworldapp_participant
9 auth_user_groups helloworldapp_question
10 auth_user_user_permissions helloworldapp_quiz
11 django_admin_log helloworldapp_result
12 django_content_type

Model diagrams are often useful to understand and verify your


design. There are a number of tools available to do this. For a
simple approach, you can create an ASCII diagram that illustrates
the model using the following prompt.

Prompt template
Create a diagram that shows the relationships between the
model classes.

To generate a better model diagram, run the following commands


to install Django extensions which has a utility for this purpose.

1 python -m pip install django-extensions


2 python -m pip install pydotplus

Then add it to the list of INSTALLED_APPS in the [Link] file.

1 'django_extensions',

You can now run the following command from the helloworld
directory. This will create a model diagram with the name you
specify. In this example, the diagram will be created with the
filename myapp_models.png.
Prompt Two: Create your models 33

1 python [Link] graph_models -a -g —o myapp_models.png

This creates the following image. We show only the relevant


app here. The default Django framework models created at the
beginning will also be in the diagram unless they are excluded using
other command-line options. This model looks pretty good. Each
quiz is made up of one or more questions, and each question has a
set of possible answers, one of which is correct. Each quiz is taken
by participants and has results with a score for that participant.
Prompt Two: Create your models 34
Prompt Two: Create your models 35

If you want to see more options for the model diagram generation,
use the following command.

1 ./[Link] graph_models --help

4.3 Running Django test cases


Use the test prompt to have AI generate test cases for you. Copy
the code and put it into the [Link] file in your project. You can
run Django tests using the following command.

1 python [Link] test [Link]

Note that the last token uses whatever name you gave your Django
app. Within that app, the tests token that follows refers to the
[Link] file.

Be in the habit of always using the test prompts and running these
tests after each iteration or step in the process. It is significantly
easier to identify a problem right away. If the issue doesn’t pop up
until a few steps later, it will be more challenging to narrow down
where the problem was introduced.
5 Prompt Three:
Implement your first use
case
With the models in place, you are in a position to build user
interfaces and services that leverage those model entities.
What user interfaces and services do we need? The answer to that
question is driven by your application use cases. The first step in
this phase is to identify the user personas.

5.1 Define the user personas


A persona is a type of user that uses your application. You can ask
AI for help with this step, but it should be relatively easy to reason
through yourself.
Consider the example quiz application. There are two user per-
sonas.

• The quiz creator, the user who creates quizzes and can view
aggregate results and metrics.
• The quiz participant, the user who takes the quiz and re-
ceives their score.

If we decide that any user can create quizzes, then all users can play
both roles.
Given that aggregate quiz results are typically not sensitive data,
we can also allow any user to see the overall results for any quiz.
Prompt Three: Implement your first use case 37

The only restriction then, is that participants are the only user who
can see their own individual quiz results. Scores are available to
other users only in an aggregated or anonymized form.

5.2 Define what actions each user


person can take
Your application may have actions only allowed by specific users.
If this is the case in your application, we will revisit the topic of
security and authorization in a later chapter.
If you are struggling to identify use cases, try considering how each
of your models are created. Are they created by the user taking an
action? Does the system generate them based on a certain event?
The answers to these questions become your detailed requirements.
For example, here are the requirements about model creation in the
quiz application. These were part of the model design prompt.

• A quiz instance is created by a user. The user supplies the


quiz name and the topic.
• The quiz questions are generated by the system for the given
topic.
• Each question should have four possible answers.

All of this happens in the Create a Quiz use case. This use case
covers the creation of 3 of the 5 model entities in the system (Quiz,
Question, Answer). The creation of Participant occurs in the Create
Account use case. The creation of Results occurs as a part of the Take
a Quiz use case.

Additional use cases can be identified by considering what users do


with the information. Quiz results are viewed by the participant
and also fed into the generation of aggregate quiz results.
Prompt Three: Implement your first use case 38

After thinking through all of this, list the actions that each user
persona can perform in your application. The following table lists
the actions, or use cases, for the quiz application.

Action (Use Case) User Persona


Create account Creator/Participant
View list of quizzes Creator/Participant
Create a quiz Creator/Participant
View aggregate quiz results Creator/Participant
Take a quiz Creator/Participant
View individual quiz results Participant

We can now map out the flow each user takes through these use
cases.

After a user has created their account, the start point for any
workflow is to view the list of quizzes. Let’s implement that use
case first.
First, ask yourself, does this use case require any underlying
business services? Should we break it down into multiple prompts?
In this case, view the list of quizzes is a fairly simple use case. We
Prompt Three: Implement your first use case 39

can go straight into the basic use case prompt shown below.

Prompt template
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
Example prompt
Write the Python Django code to display a list of Quizzes.
Create a custom view in Django with the list of quizzes from
the database. Create the corresponding HTML template in
Django to display each quiz name and topic.
Test prompt
Write a Django test case for this view

The AI produces this output.


Prompt Three: Implement your first use case 40

Copy the view code and add it to your [Link] file. Create a new
HTML file in the templates directory called quiz_list.html and
copy the template code into that file.
ChatGPT will usually remind you to put an entry in the [Link]
file. You can also prompt it to give you code. For this case, the only
new url entry is as shown below.
Prompt Three: Implement your first use case 41

1 from [Link] import quiz_list


2
3 urlpatterns = [
4 . . .
5 path('quiz-list/', quiz_list, name='quiz_list'),
6 ]

We don’t have any data in the database yet, because we haven’t


implemented the Create a Quiz use case. However, we can still use
the test prompt to exercise this code. Use the test prompt from the
template above. Here is the output from that prompt.

That test should pass. Now let’s create an actual quiz so we can see
Prompt Three: Implement your first use case 42

some quiz data in the browser.


6 Prompt Four:
Implement a business
service
Use cases that create data are typically more complex that read-
only use cases. The Create a Quiz use case is a great example of a
use case that requires additional business logic.
In order to determine what prompts to use, break down the use case
into individual steps. These steps can be derived from the detailed
requirements you put together during the earlier design phase. You
may also need to add requirements in this phase as you go through
the specifics of particular use cases.
To create a quiz in our example application, we need to perform the
following steps.

1. Create a form for the user to enter the name of the quiz and
the topic
2. Create some number of quiz questions. For our application,
we decide to use generative AI to create the questions for us.
Thus, this is a candidate for a business service.
3. Store the quiz, the list of questions, and the answers in the
database.
4. Confirm to the user the quiz was created.

You can see what type of component will be needed for each step,
as shown in the table below.
Prompt Four: Implement a business service 44

Step Component type


Data entry form View, HTML template
Generate quiz questions Business service
Store the quiz objects View
Display user confirmation HTML template

It is best to start at the lowest layer of dependencies and work your


way up. The service to generate quiz questions will be used within
the view, so generate that first. It is also self-contained and be tested
independently.

6.1 Implement a generative AI


service
You will need a helper function to invoke the AI service. The code
to invoke the OpenAI service is shown below. See the Setup your
Environment chapter if you have not already configured and tested
the use of OpenAI. You can put this function in the [Link] file.
call_chatgpt Python function

1 import openai
2 import os
3 from dotenv import load_dotenv
4 load_dotenv()
5
6 def call_chatgpt(prompt, temperature = 0.7, max_tokens = \
7 1024):
8 # Set up OpenAI API key
9 openai.api_key = [Link]("OPENAI_API_KEY")
10
11 response = [Link](
12 engine="text-davinci-003",
13 prompt=prompt,
Prompt Four: Implement a business service 45

14 max_tokens=max_tokens,
15 temperature=temperature,
16 )
17
18 return [Link][0].text

The corresponding code to invoke the Bard API is shown below.


See the Setup Environment chapter for more information on con-
figuring your Bard account. Note that it has to do a bit of post-
processing on the response due to the Bard output format.
call_bard Python function

1 def call_bard(query):
2 bard = Bard()
3 answer = bard.get_answer(query)
4 print(answer)
5
6 # Only return response text within the delimeter,
7 # typically triple backticks
8 response_text = ""
9 lines = answer['content'].split('\n')
10 inside_delimeter = False
11 for line in lines:
12 if [Link]("```"):
13 inside_delimeter = not inside_delimeter
14 elif inside_delimeter:
15 if len(line) > 0:
16 response_text = response_text + line + '\\
17 n'
18
19 return (response_text)

Bard tends to always respond with a first line that says, “Sure, I
can do that”. The information specifically requested in a prompt is
Prompt Four: Implement a business service 46

often later surrounded by lines with triple backticks. Thus, we want


to ignore everything else except the lines between the backticks.
On the trivia question prompt we will see in a minute, Bard also
includes an explanation of the answer at the end. While that may
be useful later, it causes our parsing logic to fail. So we ignore any
lines after the second delimiter line.
Now that you have a function to invoke the generative AI service
from your application, you just need to craft a prompt for your use
case.
Below is the code and associated prompt to generate a trivia
question. Note that the prompt specifies a JSON return format.

It is a good practice to specify the output format for


generative AI prompts used in applications.

This makes it easy for the application software to parse and use
response data. In general, we have found that using XML is the
most effective format. If you were writing code by hand, you likely
would not use XML. Json would be a more logical choice these days.
However, in our testing, XML has been found to be more reliable
for AI code generators, both in terms of creating the data and then
also parsing it. Bard had trouble correctly creating JSON data as it
mixed up quotes and double quotes within the json content. Thus,
we specify XML as the response format in the code example below.
Prompt Four: Implement a business service 47

Code to use generative AI within Python application

1 def generate_question(topic):
2
3 # Define the prompt to generate trivia questions on t\
4 he given topic
5 prompt = f'''Generate one trivia question on the topi\
6 c of {topic}.
7 Provide four possible answers and then indicate the lette\
8 r of the correct answer.
9 Format your response using the following XML template.
10
11 <response>
12 <question>[QUESTION_TEXT]</question>
13 <a>A) [ANSWER_1]</a>
14 <b>B) [ANSWER_2]</b>
15 <c>C) [ANSWER_3]</c>
16 <d>D) [ANSWER_4]</d>
17 <correct_answer>[CORRECT_ANSWER_LETTER]</correct_answer>
18 </response>
19 '''
20
21 return call_chatgpt(prompt)

6.2 Parse the data returned from a


generative AI function
The generate_question function needs to be invoked within the
quiz creation use case. We need to be able to create a Question
model and corresponding Answer models from the response to this
prompt. Let’s ask the AI to write this code using the following
prompt.
Prompt Four: Implement a business service 48

Prompt template
Write a Python function to parse text data and create model_-
objects. The representative format of the text is as follows:
example_data_format
Example prompt
Write a Python function to parse text data and create a corre-
sponding Question model instance as well as corresponding
Answer model instances. The correct answer should set the
boolean flag on the corresponding Answer instance. The
representative format of the text is as follows:<correct_an-
swer>B</correct_answer>
Test prompt
Write a Django test case for the generated_function_name
function.

AI produces the following code.

1 def create_question_with_answers_from_xml(xml_text, quiz):


2 # Parse the XML
3 root = [Link](xml_text)
4
5 # Extract question text
6 question_text = [Link]('question').[Link]()
7
8 # Extract answer options
9 answer_texts = []
10 for child in root:
11 if [Link] in ['a', 'b', 'c', 'd']:
12 answer_texts.append([Link]())
13
14 # Extract correct answer
15 correct_answer = [Link]('correct_answer').[Link]\
16 ip()
17
18 # Create the question instance
Prompt Four: Implement a business service 49

19 question = [Link](quiz=quiz, text=qu\


20 estion_text)
21
22 # Create the answer instances
23 for index, answer_text in enumerate(answer_texts):
24 option = chr(ord('a') + index).upper()
25 is_correct = (option == correct_answer.upper())
26 [Link](question=question, text=ans\
27 wer_text, option=option, is_correct=is_correct)
28
29 return question

The first code that AI generated had a subtle error which caused
our test to fail.

1 [Link]: NOT NULL constraint faile\


2 d:
3 helloworldapp_question.quiz_id

If you get an error of this form, you can simply tell the AI in a
follow up prompt that you got this error. In our case, it was able to
rewrite the code to fix the problem. The Question instance in this
function has to be created with the reference to the related existing
quiz.
This issue highlights the importance of always generating test code
using the test prompt from the template, and then running the tests.
For the code generated above, the test prompt is shown below.

Test Prompt
Write a Django test case for the create_question_with_an-
swers_from_xml function.

You can then run the tests using the following command.
Prompt Four: Implement a business service 50

1 python [Link] test [Link]

It is much easier to identify and resolve issues with the code when
you can isolate the cause and ask the AI to rewrite the code while
all of the information is in context.
You can always rewrite code later on in the development process.
You may need to provide the code in question in the prompt.
However, if you bundle a series of generated code changes at one
time, diagnosing which code caused the problem can become more
challenging and time-consuming.
Now that we have the business service needed for the Create a Quiz
use case, we can generate the rest of the code.
What you read was a sample of the book. If you like what you read
so far, please support the author by purchasing the book.
7 Prompt Five:
Implement a complex
use case
The same use case prompt template can be used to implement the
Create a Quiz capability. The templation is to write the prompt as
shown below.

Use case prompt


Write the Python Django code to create a quiz. Create a
custom view in Django with a form with the Quiz fields and
a submit button. Create the corresponding HTML template
in Django to display the form and confirm the creation was
successful.

This prompt will generate code that implements half of the steps in
this use case. It will create an HTML form and save a Quiz instance
to the database. However, it will not use the business service we
just generated. The quiz will not have any questions or answers.
We need to be specific in the requirements provided in the prompt.
Here is a prompt that incorporates the missing steps.

Prompt template
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
Example prompt
Write the Python Django code to create a quiz. Create a
Prompt Five: Implement a complex use case 52

custom view in Django with a form with the Quiz fields


and a submit button. The view should call the generate_-
question(topic) function and then parse the data using the
create_question_with_answers_from_xml function. Create
the corresponding HTML template in Django to display the
form and confirm the creation was successful.
Test prompt
Write a Django test case for this view

The AI output generates three different pieces of code that you need
in your application.

1. Two views for the form display, submission, and confirma-


tion. This code goes in the [Link] file.
2. A form class used by Django to process the HTML form.
Create a file helloworldapp/[Link] to hold this code.
3. Two templates, one for the quiz creation and another for
confirmation. These files go in the templates directory.

Here is the generated view code which does exactly what we asked
it to do. It does only create one quiz question at this point, but we
can modify that later after the basic capability is working.
Prompt Five: Implement a complex use case 53

The AI did generate templates that extend a base template, adding


the following note.
Note: The [Link] template is not provided here as it depends
on your project’s specific layout and design. You can create a base
template with common elements and extend it in these templates.
Thus, we added a base template with very simple formatting to
start.
Prompt Five: Implement a complex use case 54

1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <link rel="stylesheet" href="[Link]">
5 <title>{% block title %}My amazing site{% endblock %}\
6 </title>
7 </head>
8
9 <body>
10 <div id="content">
11 {% block content %}{% endblock %}
12 </div>
13 </body>
14 </html>

Running the server and testing in the browser shows that the code
is working.
Prompt Five: Implement a complex use case 55

We can see the quiz we created in the quiz list now. We can also
see the question and answer data in the database.

1 sqlite> select * from helloworldapp_quiz;


2 31|First quiz|Science
3 sqlite> select * from helloworldapp_question;
4 12|Which of the following is the largest planet in our so\
5 lar system?|31
6 sqlite> select * from helloworldapp_answer;
7 55|A) Mercury|0|12|A
8 56|B) Venus|0|12|B
9 57|C) Earth|0|12|C
10 58|D) Jupiter|1|12|D
Prompt Five: Implement a complex use case 56

7.1 Modify our existing


implementation to create multiple
quiz questions
As is, our quizzes only have one question. During iterative
development with AI, you will often need to modify existing code.
This is the same as in a normal software development lifecycle.
Requirements change, get added, or bugs are found. All of this is
still true while coding with AI.
For changes like this, if you are a skilled software engineer, you can
simply modify the code yourself. It would not be that hard to do.
The heavy lifting has already been done for you.
But let’s see how we can use AI to modify the code for us using the
following prompt template. Note that you only need to provide the
existing code in the prompt if it is no longer in the AI context. If
you just generated the function(s), you most likely do not need to
supply it. The AI will already have a reference to this code in it’s
context.

Prompt template
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Example prompt
Modify the create_quiz view to create five quiz questions
instead of just one.
Test prompt
Modify the Django test case for the create_quiz view

The AI does a perfect job of providing the modified code. The


only change is the addition of a loop that generates and adds the
questions.
Prompt Five: Implement a complex use case 57

This code change worked great, with one caveat. Using Bard as
the generative AI service, this is the data it created. As you can
see, it used the same question multiple times. Obviously, we want
original questions every time.
Prompt Five: Implement a complex use case 58

1 sqlite> select * from helloworldapp_quiz where id = 32;


2 32|Math quiz|mathematics
3
4 sqlite> select * from helloworldapp_question where quiz_i\
5 d = 32;
6 13|What is the smallest perfect number?|32
7 14|What is the smallest perfect number?|32
8 15|What is the largest prime number less than 100?|32
9 16|What is the smallest perfect number?|32
10 17|Which of the following is the square root of 16?|32

The ChatGPT API has the temperature setting which controls the
creativity. A high temperature setting would likely prevent us from
ever seeing the exact same question twice. As expected, ChatGPT
does a better job with this parameter setting in generating unique
question.

1 sqlite> select * from helloworldapp_quiz where id = 33;


2 33|ChatGPT Math Quiz|mathematics
3
4 sqlite> select * from helloworldapp_question where quiz_i\
5 d = 33;
6 18|What is the area of a circle with a radius of 5?|33
7 19|What is the formula for the area of a circle?|33
8 20|Which of the following numbers is a perfect square?|33
9 21|What is (2x + 3y) / (4x - 5y) equal to?|33
10 22|What is the name of the mathematical expression that r\
11 epresents the relationship between the circumference of a
12 circle and its radius?|33

7.2 Modify the existing page style


Our web pages look very bland right now. We can use AI to
improve the look and feel using this prompt.
Prompt Five: Implement a complex use case 59

Example prompt
Modify the [Link] template to have nicer looking CSS
styles. Also, it should have a header section at the top, and a
sidebar with links to go back to the list of quizzes and also to
create a quiz. Use bootstrap as the CSS framework.

Any templates that do not already extend the base template should
be modified to do so. We can also make the quiz list be the default
page by modifying the [Link] file accordingly, as shown below.

1 urlpatterns = [
2 path('', quiz_list, name='quiz_list'),
3 path('quiz-list/', quiz_list, name='quiz_list'),
4 path('create-quiz/', create_quiz, name='create_quiz'),
5 path('quiz-created/', quiz_created, name='quiz_create\
6 d'),
7 path('admin/', [Link]),
8 ]

When you browse to the root URL, you now see the quiz list with
the improved look and feel.

Now, let’s implement the use case to take the quiz.


8 Prompt Six: Implement
a use case that uses
generated data
First, let’s make a simple change to the quiz list. Each quiz name
should be a link to a view that allows users to take the quiz. The
modify prompt for this is shown below. Note that here you likely
need to provide the existing code in the prompt, since it has been a
while since the AI worked with that code. If you did all of this in
the same session, then it is possible the AI still has a reference to
the code.
If you are ever in doubt, err on the side of supplying the existing
code in the prompt.

Prompt template
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Example prompt
Modify the quiz_list view to make each quiz name a link to a
new view called take_quiz.
Test prompt
Modify the Django test case for the quiz_list view

The view doesn’t need to change. It only retrieves the quiz data
from the database. However, the AI does add a placeholder for the
new take_quiz view. The template is modifed to create a link for
each quiz name.
If the AI did not generate the [Link] entry, you can prompt for it
as follows.
Prompt Six: Implement a use case that uses generated data 61

Example prompt
Write the [Link] entry for take_quiz

That modification successfully creates links in the list of quizzes.

Now, we can implement the actual Take a Quiz use case.


This is a non-trivial use case, so we first need to think through the
steps of what will happen. This will determine how the prompts
are broken up to implement the entire use case. The basic flow of
this use case is as follows.

1. Loop through each question in the selected quiz and display


the question and possible answers.
2. Prompt the user for the answer to this question.
3. Record the result and keep track of how many correct answers
the user got.
4. Keep track of how many correct answers the user got.

In this case, the view and template code to perform steps 1-3 are
all intertwined. It would be difficult to break them up into discrete
prompts. Step 4 can be treated as a follow-up prompt. It will have
its own view and display characteristics.
Prompt Six: Implement a use case that uses generated data 62

There is an important detail in the requirements for this view/tem-


plate combination. We need to tell the AI if we want all the
questions to be displayed on the same page, or do we want the
user to answer each question one-by-one.
If you do not specify this detail in your prompt, the AI will likely
assume you want to show all of the questions in one form. This is
a great example of the need to provide as much detail as possible in
your prompts. If you forget the first time, its okay. You can always
modify the existing code as we have seen with a follow-up prompt
that includes the missing detail.
To implement steps 1-3, use the following prompt.

Prompt template
Write the Python Django view and HTML template for the
use_case_description. description_of_use_case_steps.
Example prompt
Write the Python Django view and HTML template for the
take_quiz view. It should display one question at a time
along with the answers and prompt the user for their chosen
answer. It should keep track of how many correct answers
the users gets. On the the name of the quiz and the current
question number near the top of the form. At the end of the
questions, it should go to a quiz_result view.
Test prompt
Write a Django test case for the take_quiz view

The generated code all seems to work well. Here is a screen capture
from the math quiz generated earlier.
Prompt Six: Implement a use case that uses generated data 63

The actual generated code is shown below. It also notes in


the response: “Note: You need to create the take_quiz.html and
quiz_result.html templates according to your desired layout and
design to display the questions, answers, and quiz result.” We
expected that and can follow-up after with a prompt to generate
the quiz_result template.
The generated take_quiz code uses session variables to manage the
state across question pages. It increments the question count until it
has gone through all the questions, and then redirects to the quiz_-
result view.

1 def take_quiz(request, quiz_id):


2 quiz = get_object_or_404(Quiz, pk=quiz_id)
3 questions = [Link]()
4 total_questions = [Link]()
5 current_question_index = [Link]('current\
6 _question_index', 0)
7 correct_answers = [Link]('correct_answer\
8 s', 0)
9
10 if [Link] == 'POST':
11 user_answer = [Link]('answer')
12
Prompt Six: Implement a use case that uses generated data 64

13 if user_answer:
14 current_question = questions[current_question\
15 _index]
16 answer = get_object_or_404(Answer, pk=user_an\
17 swer)
18
19 if answer.is_correct:
20 correct_answers += 1
21
22 current_question_index += 1
23 [Link]['current_question_index'] = curre\
24 nt_question_index
25 [Link]['correct_answers'] = correct_answ\
26 ers
27
28 if current_question_index >= total_questions:
29 del [Link]['current_question_index']
30 del [Link]['correct_answers']
31 return redirect('quiz_result', quiz_id=quiz_i\
32 d)
33
34 else:
35 if 'current_question_index' in [Link]:
36 del [Link]['current_question_index']
37 if 'correct_answers' in [Link]:
38 del [Link]['correct_answers']
39
40 current_question = questions[current_question_index]
41
42 context = {
43 'quiz': quiz,
44 'question': current_question,
45 'current_question_index': current_question_index \
46 + 1,
47 'total_questions': total_questions,
Prompt Six: Implement a use case that uses generated data 65

48 }
49
50 return render(request, 'take_quiz.html', context)

Thet take_quiz template generated code is shown below.

1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>{{ [Link] }}</h2>
5 <h3>Question {{ current_question_index }} of {{ total\
6 _questions }}</h3>
7
8 <form method="POST" action="{% url 'take_quiz' quiz.i\
9 d %}">
10 {% csrf_token %}
11
12 <h4>{{ [Link] }}</h4>
13
14 {% for answer in [Link] %}
15 <div>
16 <input type="radio" id="answer_{{ answer.\
17 id }}" name="answer" value="{{ [Link] }}">
18 <label for="answer_{{ [Link] }}">{{ an\
19 [Link] }}</label>
20 </div>
21 {% endfor %}
22
23 <button type="submit">Next</button>
24 </form>
25 {% endblock %}

Now we can generate the quiz_result view. This uses a shortened


prompt template because the AI already has most of the context for
what this page needs. You just need to fill in the missing detail.
Prompt Six: Implement a use case that uses generated data 66

Prompt template
Write the Django code for the view_name view and template.
Example prompt
Write the Django code for the quiz_result view and template.
Test prompt
Write a Django test case for the quiz_result view

Here is the generated code for the quiz_result. Note that AI did not
remember it already had the correct answers stored in the session.
In the future, we will store this information in the database, but
for now we can modify the code to simply get the value from the
session.

1 def quiz_result(request, quiz_id):


2 quiz = get_object_or_404(Quiz, pk=quiz_id)
3 total_questions = [Link]()
4
5 # Perform any necessary calculations to determine the\
6 number of correct answers
7 # You should have this logic implemented based on you\
8 r specific requirements
9 #correct_answers = 0 # NOTE: This is what ChatGPT \
10 generated
11 # We replaced it with this line
12 correct_answers = int([Link]['correct_answer\
13 s'])
14
15 # Calculate the score as a percentage
16 score = (correct_answers / total_questions) * 100
17
18 context = {
19 'quiz': quiz,
20 'total_questions': total_questions,
21 'correct_answers': correct_answers,
22 'score': score,
Prompt Six: Implement a use case that uses generated data 67

23 }
24
25 return render(request, 'quiz_result.html', context)

Our application now displays the results after you finish the quiz.
Looks like I didn’t do so well. Need to practice up on my mathe-
matics.

8.1 Persist the results to the


database
We want to report on quiz results and see how participants are
doing in aggregate. The Result entity references a Participant
though. Thus, we need to implement authentication so we can
identify who is taking the quiz.
In the next chapter, we will add authentication to the application
and show how to persist quiz results for each user.
9 Prompt Seven: User
authentication
Here is a prompt to add user authentication to our Django app.
Without additional guidance, it will use Django’s built in user au-
thentication mechanism. We can choose to use our own Participant
class as a custom authentication class, or we can change our models
to reference the Django User class. The latter is the easier option
to get started, so let’s do that for now.
Our Result model is now defined as follow.

1 class Result([Link]):
2 quiz = [Link](Quiz, on_delete=[Link]\
3 DE, related_name='results')
4 user = [Link](User, on_delete=[Link]\
5 DE, related_name='results', null=True)
6 correct_answers = [Link](null=True)
7 score = [Link]()

Unfortunately, our experience with AI coding is that the authen-


tication code was not complete. There were a few additions that
were needed to get everything working properly. Keep this in mind
as you go through the authentication prompt and integration of
resulting code.
Generate the authentication code using the following prompt.
The basic configuration required to use authentication is already
included when we used the Django startproject command at the
very beginning of this book.

Example prompt
Write the code to authenticate the user to a Django Python
Prompt Seven: User authentication 69

application and the corresponding login view

You may get code with the Django built-in LoginView. A follow up
prompt provided this code, which allowed us to easily change the
redirect.

1 def login_view(request):
2 if [Link] == 'POST':
3 username = [Link]['username']
4 password = [Link]['password']
5 user = authenticate(request, username=username, p\
6 assword=password)
7 if user is not None:
8 login(request, user)
9 # Redirect to the desired page after successf\
10 ul login
11 return redirect('quiz_list')
12 else:
13 # Authentication failed
14 return render(request, '[Link]', {'error'\
15 : 'Invalid credentials'})
16 else:
17 return render(request, '[Link]')

The [Link] addition is as follows.

1 from [Link] import path


2 from .views import CustomLoginView
3
4 urlpatterns = [
5 path('login/', login_view, name='login'),
6 # Other URL patterns
7 ]

Finally, here is the login template.


Prompt Seven: User authentication 70

1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>Login</h2>
5 <form method="POST" action="/login/">
6 {% csrf_token %}
7 <input type="text" name="username" placeholder="U\
8 sername"><br/>
9 <input type="password" name="password" placeholde\
10 r="Password"><br/>
11 <input type="submit" value="Login">
12 </form>
13 {% endblock %}

At this point, however, there are no registered users in our database.


You can create one using the Python console if you want to test this
step. Lets go ahead and implement the Create an Account use case
so we can test the whole process.

Example prompt
Write the code to create a Django user, including the view
and the corresponding HTML template.

This generates the following view.

1 from [Link] import UserCreationForm


2 from [Link] import render, redirect
3
4 def register(request):
5 if [Link] == 'POST':
6 form = UserCreationForm([Link])
7 if form.is_valid():
8 [Link]()
9 # Redirect to the desired page after successf\
10 ul registration
Prompt Seven: User authentication 71

11 return redirect('login')
12 else:
13 form = UserCreationForm()
14 return render(request, '[Link]', {'form': form\
15 })

The HTML template is shown below. We modified the language


to welcome the user to the application, but otherwise the code is
exactly what the AI generated.

1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>Welcome to the Quiz App!</h2>
5 Please register below to get started.<br/><br/>
6 <form method="post">
7 {% csrf_token %}
8 {{ form.as_p }}
9 <button type="submit">Register</button>
10 </form>
11 {% endblock %}

Authentication can then be enforced by adding this check at the


beginning of your views. If the user is not authenticated, they will
be sent to the register page.

1 def quiz_list(request):
2 if not [Link].is_authenticated:
3 return register(request)

Now, when you start the server and browse to the app, you will see
the following screen (assuming you have not yet logged in).
Prompt Seven: User authentication 72

After creating an account, the register view forwards you to the


login page.

A successful login attempt redirects you to the quiz list and now
we have the user identify, so we can persist the results after they
complete a quiz.
Prompt Seven: User authentication 73
10 Prompt Eight:
Reporting use case
The quiz_result view already displays the results to the user. Now,
we want to modify that code to also persist the results to a database
for reporting purposes. The code addition is fairly simply, but we
can prompt AI to write it for us.

Prompt template
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Example prompt
Modify the quiz_result view to save the data to the database
using a Result model.
Test prompt
Modify the Django test case for the quiz_result view

The code addition is simply as follows:

1 # Save the result to the database


2 result = Result(user=[Link],
3 quiz=quiz,
4 correct_answers=correct_answers,
5 score=score)
6 [Link]()
Prompt Eight: Reporting use case 75

10.1 Creating a graph based on your


data
We have the data in the Results table. Now, we can implement the
final use case, reporting on aggregate results data.

Prompt template
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
Example prompt
Write the Python Django code to create a graph of quiz results
for a given quiz. Create a custom view in Django with a bar
chart of quiz results by letter grade, where an A is a score of 90
or above, a B is a score of 80-89, etc. Create the corresponding
HTML template in Django to display the graph for a given
quiz.
Test prompt
Write a Django test case for this view

The output of this prompt has a number of code elements for us to


integrate. First, run the following command.

1 python -m pip install django-chartjs

Next, add ChartJS to your [Link] file.


Prompt Eight: Reporting use case 76

1 INSTALLED_APPS = [
2 '[Link]',
3 . . .
4 'chartjs'
5 ]

The AI generated some interesting view code that derives the letter
grades from the scores. However, it didn’t use it at the end. The
view method was simply generated as follows.

1 def quiz_results_chart(request, quiz_id):


2 return render(request, 'quiz_results_chart.html', {'q\
3 uiz_id': quiz_id})

Thus, we needed a simple follow up prompt, which solved the


problem.
Prompt Eight: Reporting use case 77

As usual, we need to prompt the AI to write the [Link] entry for


us.

1 urlpatterns = [
2 path('quiz/<int:quiz_id>/results/chart/', quiz_result\
3 s_chart, name='quiz_results_chart'),
4 ]

Finally, the template has the logic to create the bar chart.
Prompt Eight: Reporting use case 78

1 {% extends '[Link]' %}
2
3 {% block content %}
4 <h2>Quiz Results Chart</h2>
5 <div class="container">
6 <canvas id="quizResultsChart"></canvas>
7 </div>
8
9 <script src="[Link]
10 /script>
11 <script>
12 [Link]('DOMContentLoaded', fun\
13 ction() {
14 var chartData = {
15 labels: {{ labels|safe }},
16 datasets: [{
17 label: 'Quiz Results',
18 data: {{ data|safe }},
19 backgroundColor: 'rgba(54, 162, 235, \
20 0.5)',
21 borderColor: 'rgba(54, 162, 235, 1)',
22 borderWidth: 1
23 }]
24 };
25
26 var chartOptions = {
27 responsive: true,
28 scales: {
29 y: {
30 beginAtZero: true,
31 stepSize: 1
32 }
33 }
34 };
35
Prompt Eight: Reporting use case 79

36 var ctx = [Link]('quizResult\


37 sChart').getContext('2d');
38 new Chart(ctx, {
39 type: 'bar',
40 data: chartData,
41 options: chartOptions
42 });
43 });
44 </script>
45 {% endblock %}

With all of this code integrated into our application, the graph is
now working. We can add links in the quiz list for reports, and
here is the result.
11 Prompt Checklist
We have written an entire quiz application now using eight prompt
templates. The first few prompts were used to design and generate
the model classes upon which the rest of the application was based.
We used the use case prompt template for each use case. When
needed, we used the modify use case template as well. There were
also some follow up prompts that were needed.
Let’s review each of the prompt templates that we used. This will
also serve as a handy checklist for you to use when generating your
applications.

Project setup
Create a small example to say hello world using the frame-
work_name framework
Models
You are a software designer building a project_name appli-
cation. Define the model classes needed to implement the fol-
lowing requirements. 1. Requirement_1 2. Requirement_2
3. Requirement_3
Write the Python code for these model classes based on the
framework_name framework

NOTE: After each model update, you need to run the following
Django commands:

1 python [Link] makemigrations helloworldapp


2 python [Link] migrate

At this point in the process, you should perform the following


design activities before continuing,
Prompt Checklist 81

• Define the user personas who will use the application


• Define the actions (use cases) that each user persona will
perform
• For each use case, break down the process into discrete steps.
• When generating code for each use case, consider how to
break up the steps into a series of prompts.

Business Services
(Generative AI) Generate output_requirements. Format
your response using the following XML template. example_-
xml_structure
Write a Python function to parse text data and create model_-
objects. The representative format of the text is as follows:
example_xml_structure
Use Cases
Write the Python Django code to use_case_description.
Create a custom view in Django with description_of_-
page_contents. Create the corresponding HTML template
in Django to display_details.
(Alternate form) Write the Python Django view and HTML
template for the use_case_description. description_of_-
use_case_steps.
Modify the component_name component_type to
change_description. The existing code is as follows:
existing_code
Authentication
Write the code to authenticate the user to a Django Python
application and the corresponding login view

Note that you can use the use case templates to prompt AI for login
and logout code.
You now have the basic tools to generate almost any application
using AI.
Prompt Checklist 82

The rest of this book will apply this process and the associated
templates to building other types of applications. We will see
how the same methodology can be used to build many types of
applications much faster than was previously possible.

You might also like