ChatofAI Blog
Published on

How to build a chatbot with ChatGPT

Authors

Overview

OpenAI has developed several powerful large language models, such as GPT-3 and GPT-4. Future models like GPT-5 may also be released. These models can greatly enhance our work efficiency, allowing us to answer questions, generate articles, analyze data, and more. However, while ChatGPT is designed for personal use, OpenAI does not currently offer a direct service for integrating ChatGPT into websites. Fortunately, OpenAI provides an API to access these models, enabling us to build chatbots and incorporate them into our websites. This article will show you how to create a chatbot using ChatGPT and Python. Finally, we will provide the full code for your reference.

Table of Contents

Prerequisites

  • Basic knowledge of Python
  • Basic knowledge of HTML and CSS
  • A ChatGPT API key (you can get one here)
  • Python libraries: openai, flask
  • A text editor or an IDE like VSCode

Build a Chatbot with ChatGPT

Step 1: Setting up Python environment

First, ensure you have Python installed on your machine. Most operating systems come with Python pre-installed. You can check if Python is installed by running the following command in your terminal or command prompt:

python --version

if you don't have a Python environment, you can download it from the official Python website. and then install it on your machine. the official Python website also provides beginner's guides for installation.

Step 2: Install the required libraries

To build a chatbot service, you need to install the openai and flask libraries. before installing the libraries, We strongly suggest you create a virtual environment. to create a virtual environment, you can use the following command:

python -m venv chatbot-env

then activate the virtual environment:

source chatbot-env/bin/activate

now you can install the required libraries:

pip install openai flask

Step 3: Create a Flask app

Create a new directory for your project and navigate to it. Next, create a new Python file named app.py and add the following code to create a simple Flask app:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

run the app using the following command:

python app.py

open your browser and navigate to http://localhost:5000/ to see the message, Hello, World!. now a simple Flask app is running on your machine.

Step 4: Connect to the ChatGPT API

To connect to the ChatGPT API, you need to get an API key from the OpenAI website. you can get an API key by signing up on the OpenAI website. create a new file named chatbot.py and add the following code to connect to the ChatGPT API:

import json

from openai import OpenAI

OPENAI_API_KEY = "sk-XXXXXXXX"

prompt = """You are an AI assistant that helps users find the best answer to
their questions."""


def ask_question(question):
    client = OpenAI(api_key=OPENAI_API_KEY)
    messages = [
        {
            "role": "system",
            "content": prompt
        },
        {
            "role": "user",
            "content": question
        }
    ]
    stream = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        stream=True
    )
    for chunk in stream:
        if chunk.choices[0].delta.content is not None:
            yield u"data: {}\n\n".format(json.dumps({
                "type": "message",
                "content": chunk.choices[0].delta.content
            }))
    yield u"data: [DONE]\n\n"

Note: Replace sk-XXXXXXXX with your OpenAI API key.

Now, you can use the ask_question function to ask questions to the ChatGPT API, and it will return the response. the response will be a stream of messages, this is a simple SSE (Server-Sent Events) implementation. you can use this stream to send messages to the client in real time. so the client can see the responses as they are generated.

Step 5: Create a chat API endpoint

Change the app.py file to create a chat API endpoint, this endpoint will used by the client to send messages to the ChatGPT API and get the responses.

from flask import Flask, Response, request, stream_with_context

from chatbot import ask_question

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, World!'


@app.route('/chatbot', methods=['POST'])
def chatbot():
    question = request.form.get('question')
    if not question:
        return 'Please provide a question', 400
    data = ask_question(question)
    return Response(
        stream_with_context(data), content_type='text/event-stream'
    )

if __name__ == '__main__':
    app.run(debug=True)

restart the server using the following command:

python app.py

now you can send a POST request to the /chatbot endpoint with a question parameter to get the response from the ChatGPT API.

curl -X POST http://localhost:5000/chatbot -d "question=hello"
data: {"type": "message", "content": ""}

data: {"type": "message", "content": "Hello"}

data: {"type": "message", "content": "!"}

data: {"type": "message", "content": " How"}

data: {"type": "message", "content": " can"}

data: {"type": "message", "content": " I"}

data: {"type": "message", "content": " assist"}

data: {"type": "message", "content": " you"}

data: {"type": "message", "content": " today"}

data: {"type": "message", "content": "?"}

data: [DONE]

Step 6: The last step, create a chat interface

Create a new file named index.html in the templates directory and add the following code to create a simple chat interface:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChatBot</title>
    <style>
        body {
            font-family: "Helvetica Neue", "Segoe UI", "Arial", sans-serif, "pingfang SC";
            background-color: #f4f4f4;
            padding: 20px;
            color: #333;
        }
        #output {
            font-size: 24px;
            font-family: "Helvetica Neue", "Segoe UI", "Arial", sans-serif, "pingfang SC";
            border: 1px solid #ccc;
            padding: 10px;
            margin-top: 20px;
            height: 200px;
            overflow: auto;
            background-color: #fff;
        }
        #startButton {
            background-color: #18ad91; /* Green */
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
        }
        input[type="text"] {
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            box-sizing: border-box;
            border: 3px solid #ccc;
            -webkit-transition: 0.5s;
            transition: 0.5s;
            outline: none;
        }
        input[type="text"]:focus {
            border: 3px solid #555;
        }
    </style>
</head>
<body>
    <input type="text" id="input" placeholder="Input your questions">
    <button id="startButton">Ask</button>
    <div id="output"></div>

    <script type="module">
        import { fetchEventSource } from 'https://esm.run/@microsoft/fetch-event-source';
        const outputDiv = document.getElementById('output');
        const startButton = document.getElementById('startButton');
        startButton.addEventListener('click', function() {
            const url = window.location.protocol + "//" + window.location.host + "/chatbot";
            outputDiv.innerHTML = "";
            const formData = new FormData();
            formData.append('question', document.getElementById('input').value);
            fetchEventSource(url, {
                method: 'POST',
                Headers: {
                    'Content-Type': 'multipart/form-data'
                },
                body: formData,
                onmessage: (event) => {
                    console.log(event);
                    try{
                        if (event.data === "[DONE]") {
                            startButton.disabled = false;
                        } else {
                            const msg = JSON.parse(event.data);
                            if (msg.type == 'system') {
                                console.log(msg.system);
                            } else {
                                outputDiv.innerHTML += msg.content;
                                outputDiv.scrollTop = outputDiv.scrollHeight;
                            }
                        }
                    }
                    catch (e) {
                        console.error("error: ", e);
                    }
                }
            });
            startButton.disabled = true;
        });
    </script>
</body>
</html>

now open the browser and navigate to http://localhost:5000/ to see the chat interface. Input your question and click the Ask button to get the response from the ChatGPT.

Chatbot Interface

full code is available on GitHub

What's next?

This is just a simple example of how to build a chatbot using ChatGPT and Python. You can further enhance the chatbot by adding more features, such as:

  • Optimizing the prompt messages for better responses.
  • Send history of messages to the ChatGPT API to get more context-aware responses.
  • Add private data to the ChatGPT API to get more personalized responses.
  • Implement a more advanced chat interface with more features.
  • Deploy the chatbot to a server and make it available to the public.
  • Integrate the chatbot into your website or application.

Implementing these features is not easy for a beginner, fortunately, ChatofAI offers an advanced chatbot service that can help you create a more sophisticated chatbot that implements all these features and more. you can build your chatbot on our platform and seamlessly integrate it into your website or application easily. We provide a Free plan that allows you to build a chatbot with message limited, you can try it now and see how it works. no credit card is required.