Introduction to the ChatGPT API: Creating a Python Flask App with ChatGPT API

Skolo Online Learning
Python in Plain English
6 min readMar 8, 2023

--

The new ChatGPT API is finally here and I’m here to tell you all about it. Whether you’re a seasoned developer or just starting out, you’ll find this information both exciting and useful. In this article, we’ll cover everything you need to know about the ChatGPT API, including what it is, how to use it, and how to build an amazing application with it using Python Flask.

Everything that we will cover here detailed step-by-step in a YouTube Video here:

I am sure you too have been waiting to create your own ChatGPT? The newly released ChatGPT API is a makes that possible. I was browsing through my emails on the 1st of March when the long awaited announcement popped in to may mailbox, I was so excited — I nearly feel out of my chair. I have been waiting for this, fo so long.

With its smart language processing and flexible design, the ChatGPT API opens up a world of possibilities for creating awesome and interactive user experiences.

In this article, I will show you how to build a Python Flask app using the ChatGPT API. By the end of it, you’ll know how to use the API to create a chatbot that can understand and respond to user input just like the ChatGPT website.

What is an API?

API stands for Application Programming Interface. It is a set of protocols, routines, and tools for building software and applications. An API specifies how software components should interact and APIs allow for communication between different systems.

In this API project, we will use the OpenAI API to interact with the AI engine and get responses. The process will involve creating a prompt, sending it to the AI engine through the API, and then displaying the received response in our application.

ChatGPT API Documentation

To get started, we need to understand the API documentation — you can find it here: https://platform.openai.com/docs/guides/chat

The structure of the ChatAPI is simmilar to the other OpenAI APIs — If you have not used the other APIs before, you can do some reading here:

Greate a blog writting tool with GPT-3 API — https://python.plainenglish.io/how-to-create-an-ai-blog-writing-tool-with-openai-api-gpt-3-and-python-33665167ff8f

AI Content Generator with GPT-3 and Python Flask — https://python.plainenglish.io/create-ai-content-generator-with-python-flask-and-openai-gpt-3-407a19f096b

Generate Python code with OpenAI Codex API — https://python.plainenglish.io/generate-python-code-with-openai-codex-api-9617f8acd7bd

Create your own DALLE-2 App with OepnAI Image API — https://python.plainenglish.io/create-your-own-dalle-2-ai-image-generating-site-with-flask-and-openai-api-7fecc2ded2f

ChatGPT Engine

ChatGPT operates on “gpt-3.5-turbo” and that is what we will be using in our code. This tutorial will cover the Python application of the API.

This is the code that you will need from the documentation:

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai

openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
]
)

Note: You will need to re-install the openai library (if you have it installed in the past on another project for example) for the code to work, because they have extended it to include ChatCompletion

Get started with the Python Flask Project

You can start by cloning this “starter” Python Flask project — https://github.com/skolo-online/chat-gpt-starter

It is set up to make following along with this tutorial easier.

There are a few modifications we will be doing to get the project ready.

The Index HTML File — The Front-End

The project will use basic Bootsrap CSS and JS libraries, in addition we have installed jquery (Which we will need — to communicate with the server).

Basically what happens in the HTML is as follows:

Step 1: User enters a text — prompt or question in an input box.

 <div class="input-group mb-3">
<input type="text" class="form-control" id="chat-input">
<div class="input-group-append">
<button id="gpt-button" class="btn btn-primary">Ask ChatGPT</button>
</div>
</div>

Step 2: We get this input when the user presses a “Ask GTP Button” and display it back to the user just above the input box — so the user can see what they have typed.

We attach a “click-function” to the button and get the “input” from the “chat-input” field above. We display the same input inside the list-item HTML element that we then append to the “list-group” div.

$("#gpt-button").click(function(){
var question = $("#chat-input").val();
let html_data = '';
html_data += `
<a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">
<img src="{{ url_for('static', filename='images/favicon.png') }}" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">
<div class="d-flex gap-2 w-100 justify-content-between">
<div>
<p class="mb-0 opacity-75">${question}</p>
</div>
</div>
</a>
`;
$("#chat-input").val('');
$("#list-group").append(html_data);
});

Step 3: at the same time we take that input and send it to the server in the background using jquery.

$("#gpt-button").click(function(){
$.ajax({
type: "POST",
url: "/",
data: {'prompt': question },
success: function (data) {
//More code will come here as response from the ajax call
}
});
});

Step 4: We receive the input in the server from a request.POST object submitted by ajax. We submit this prompt to our modified “generateChatResponse(prompt)” functions that will complete the API call to OpenAI for us.

if request.method == 'POST':
prompt = request.form['prompt']
res = {}
res['answer'] = generateChatResponse(prompt)
def generateChatResponse(prompt):
messages = []
messages.append({"role": "system", "content": "Your name is Karabo. You are a helpful assistant."})

question = {}
question['role'] = 'user'
question['content'] = prompt
messages.append(question)

response = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=messages)

try:
answer = response['choices'][0]['message']['content'].replace('\n', '<br>')
except:
answer = 'Oops you beat the AI, try a different question, if the problem persists, come bacl later.'

return answer

Step 5: We wait for a response from the API and send it back to the HTML via the ajax response.

if request.method == 'POST':
prompt = request.form['prompt']

res = {}
res['answer'] = generateChatResponse(prompt)
return jsonify(res), 200

The HTML displays the input back to the user.

$.ajax({
type: "POST",
url: "/",
data: {'prompt': question },
success: function (data) {
let gpt_data = '';
gpt_data += `
<a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">
<img src="https://digital-practice.ams3.cdn.digitaloceanspaces.com/static%2Fapp%2Fimg%2Fopenai-logo.png" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">
<div class="d-flex gap-2 w-100 justify-content-between">
<div>
<p class="mb-0 opacity-75">${data.answer}</p>
</div>
</div>
</a>
`;
$("#list-group").append(gpt_data);
}
});

And that is it . . . . watch the full youtube video to see how the project comes together — step by step.

A snippet of our chatbot:

ChatGPT Chatbot

Get started with your ChatGPT chatbot

There are many applications of ChatGPT — I have demonstrated just the most basic application — I will leave to you, to imagine what else you can do with the API now that it is finally here.

Leave some comments below and tell me what you will be building.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

--

--

Founder of Tati Digital, passionate about digital transformation and ushering businesses in to the digital age and 4th industrial revolution.