Open In App
Related Articles

Implement ChatGPT in a Flask Application

Like Article
Save Article
Report issue

You can build dynamic and interactive chat interfaces by integrating ChatGPT into a Flask application. This article’s instructions can help you integrate ChatGPT into your Flask project and give users engaging chat experiences. Improve the user interface, try out new prompts, and look into new options to make your chat program more functional.

Implement ChatGPT in a Flask Application


Steps to Implement ChatGPT in a Flask Application Using API

Integrating ChatGPT into a Flask web application allows you to build interactive chat interfaces and provide dynamic conversational experiences to users. Let’s see the overall steps in summary:

  • Setting up the Flask Project.
  • Define a Flask that handles the chat functionality.
  • Configure Django’s URL routing to connect the chat view to a specific URL pattern.
  • Designing the User Interface.
  • Testing and Running the Application.

Implement ChatGPT in a Flask Application

Folder Structure  Creating the Chat View

In this code, you need to have a valid OpenAI API key, which you should replace with ‘YOUR_API_KEY’. The Flask application listens for requests on the root route ‘/’, and when a POST request is received, it generates a response based on the user’s prompt using the OpenAI API. The response is then returned as JSON.


from flask import Flask, render_template, request, jsonify
import openai
app = Flask(__name__)
# OpenAI API Key
openai.api_key = 'YOUR_API_KEY'
def get_completion(prompt):
    query = openai.Completion.create(
    response = query.choices[0].text
    return response
@app.route("/", methods=['POST', 'GET'])
def query_view():
    if request.method == 'POST':
        prompt = request.form['prompt']
        response = get_completion(prompt)
        return jsonify({'response': response})
    return render_template('index.html')
if __name__ == "__main__":


templates/index.html: Creating User Interface

Create an HTML template for the chat interface using HTML, CSS, and Bootstrap, and Set up the necessary JavaScript and AJAX code to handle user interaction.


<!-- query.html -->
    <script src=""></script>
    <script src="" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    <link href="" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="" integrity="sha384-b6lVK+yci+bfDmaY1u0zE8YYJt0TZxLEAFyYSLHId4xoVvsrQu3INevFKo+Xir8e" crossorigin="anonymous">
        $(document).ready(function() {
            // Send the form on enter keypress and avoid if shift is pressed
            $('#prompt').keypress(function(event) {
                if (event.keyCode === 13 && !event.shiftKey) {
            $('form').on('submit', function(event) {
            // get the CSRF token from the cookie
            var csrftoken = Cookies.get('csrftoken');
            // set the CSRF token in the AJAX headers
                headers: { 'X-CSRFToken': csrftoken }
                // Get the prompt
                var prompt = $('#prompt').val();
                var dateTime = new Date();
                var time = dateTime.toLocaleTimeString();
                // Add the prompt to the response div
                $('#response').append('<p id="GFG1">('+ time + ') <i class="bi bi-person"></i>: ' + prompt + '</p>');
                $('#response #GFG1').css({"color": "green", "width": "90%", "float": "left"});
                // Clear the prompt
                    url: '/',
                    type: 'POST',
                    data: {prompt: prompt},
                    dataType: 'json',
                    success: function(data) {
                        $('#response').append('<p id="GFG2">('+ time + ') <i class="bi bi-robot"></i>: ' + data.response + '</p>');
                        $('#response #GFG2').css({"color": "red", "width": "90%", "float": "right"});
    <div class="container p-3">
        <h3>GFG ChatGPT Clone</h3>
        <div class="mb-3">
            <form method="post" action="">
                <label for="prompt" class="form-label"><strong>Prompt: </strong></label>
                <textarea class="form-control" type="textarea" id="prompt" name="prompt" rows="3"></textarea>
                <button class="btn btn-primary " type="submit">Submit</button>
        <div class="mb-3">
            <div class="container border overflow-auto h-50" id="response"></div>




To learn more about Chat GPT, you can refer to:

Last Updated : 24 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads