How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial

In a breakthrough announcement, OpenAI recently introduced the ChatGPT API to developers and the public. Particularly, the new “gpt-3.5-turbo” model, which powers ChatGPT Plus has been released at a 10x cheaper price, and it’s extremely responsive as well. Basically, OpenAI has opened the door for endless possibilities and even a non-coder can implement the new ChatGPT API and create their own AI chatbot. So in this article, we bring you a tutorial on how to build your own AI chatbot using the ChatGPT API. We have also implemented a Gradio interface so you can easily demo the AI model and share it with your friends and family. On that note, let’s go ahead and learn how to create a personalized AI with ChatGPT API.

In this tutorial, we have added step-by-step instructions to build your own AI chatbot with ChatGPT API. From setting up tools to installing libraries, and finally, creating the AI chatbot from scratch, we have included all the small details for general users here. We recommend you follow the instructions from top to bottom without skipping any part.

Things to Remember Before You Build an AI Chatbot

1. You can build a ChatGPT chatbot on any platform, whether Windows, macOS, Linux, or ChromeOS. In this article, I am using Windows 11, but the steps are nearly identical for other platforms.

2. The guide is meant for general users, and the instructions are clearly explained with examples. So even if you have a cursory knowledge of computers, you can easily create your own AI chatbot.

3. To create an AI chatbot, you don’t need a powerful computer with a beefy CPU or GPU. The heavy lifting is done by OpenAI’s API on the cloud.

Set Up the Software Environment to Create an AI Chatbot

There are a couple of tools you need to set up the environment before you can create an AI chatbot powered by ChatGPT. To briefly add, you will need Python, Pip, OpenAI, and Gradio libraries, an OpenAI API key, and a code editor like Notepad++. All these tools may seem intimidating at first, but believe me, the steps are easy and can be deployed by anyone. Now, follow the below steps.

Install Python

1. First, you need to install Python on your computer. Open this link and download the setup file for your platform.

Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

2. Next, run the setup file and make sure to enable the checkbox for “Add Python.exe to PATH.” This is an extremely important step. After that, click on “Install Now” and follow the usual steps to install Python.

Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

3. To check if Python is properly installed, open Terminal on your computer. I am using Windows Terminal on Windows, but you can also use Command Prompt. Once here, run the below command below, and it will output the Python version. On Linux or other platforms, you may have to use python3 --version instead of python --version.

python --version
Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

Upgrade Pip

Along with Python, Pip is also installed simultaneously on your system. In this section, we will learn how to upgrade it to the latest version. In case you don’t know, Pip is the package manager for Python. Basically, it enables you to install thousands of Python libraries from the Terminal. With Pip, we can install OpenAI and Gradio libraries. Here is how to go about it.

1. Open the Terminal of your choice on your PC. As for me, I’m using the Windows Terminal. Now, run the below command to update Pip. Again, you may have to use python3 and pip3 on Linux or other platforms.

python -m pip install -U pip
Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

Install OpenAI and Gradio Libraries

1. Now, it’s time to install the OpenAI library, which will allow us to interact with ChatGPT through their API. In the Terminal, run the below command to install the OpenAI library using Pip. If the command does not work, try running it with pip3.

pip install openai
Install the OpenAI and Gradio Libraries

2. After the installation is done, let’s install Gradio. Gradio allows you to quickly develop a friendly web interface so that you can demo your AI chatbot. It also lets you easily share the chatbot on the internet through a shareable link.

pip install gradio
Install the OpenAI and Gradio Libraries

Download a Code Editor

Finally, we need a code editor to edit some of the code. On Windows, I would recommend Notepad++ (Download). Simply download and install the program via the attached link. You can also use VS Code on any platform if you are comfortable with powerful IDEs. Other than VS Code, you can install Sublime Text (Download) on macOS and Linux.

For ChromeOS, you can use the excellent Caret app (Download) to edit the code. We are almost done setting up the software environment, and it’s time to get the OpenAI API key.

Download a Code Editor

Get the OpenAI API Key For Free

Now, to create a ChatGPT-powered AI chatbot, you need an API key from OpenAI. The API key will allow you to call ChatGPT in your own interface and display the results right there. Currently, OpenAI is offering free API keys with $5 worth of free credit for the first three months. If you created your OpenAI account earlier, you may have free credit worth $18. After the free credit is exhausted, you will have to pay for the API access. But for now, it’s available to all free users.

1. Head to platform.openai.com/signup and create a free account. If you already have an OpenAI account, simply log in.

Get the OpenAI API Key For Free

2. Next, click on your profile in the top-right corner and select “View API keys” from the drop-down menu.

Get the OpenAI API Key For Free

3. Here, click on “Create new secret key” and copy the API key. Do note that you can’t copy or view the entire API key later on. So it’s strongly recommended to copy and paste the API key to a Notepad file immediately.

Get the OpenAI API Key For Free

4. Also, do not share or display the API key in public. It’s a private key meant only for access to your account. You can also delete API keys and create multiple private keys (up to five).

Build Your Own AI Chatbot With ChatGPT API and Gradio

Finally, it’s time to deploy the AI chatbot. For this, we are using OpenAI’s latest “gpt-3.5-turbo” model, which powers GPT-3.5. It’s even more powerful than Davinci and has been trained up to September 2021. It’s also very cost-effective, more responsive than earlier models, and remembers the context of the conversation. As for the user interface, we are using Gradio to create a simple web interface that will be available both locally and on the web.

1. First, open Notepad++ (or your choice of code editor) and paste the below code. Thanks to armrrs on GitHub, I have repurposed his code and implemented the Gradio interface as well.

import openai
import gradio as gr

openai.api_key = "Your API key"

messages = [
    {"role": "system", "content": "You are a helpful and kind AI Assistant."},
]

def chatbot(input):
    if input:
        messages.append({"role": "user", "content": input})
        chat = openai.ChatCompletion.create(
            model="gpt-3.5-turbo", messages=messages
        )
        reply = chat.choices[0].message.content
        messages.append({"role": "assistant", "content": reply})
        return reply

inputs = gr.inputs.Textbox(lines=7, label="Chat with AI")
outputs = gr.outputs.Textbox(label="Reply")

gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Chatbot",
             description="Ask anything you want",
             theme="compact").launch(share=True)

2. This is how it looks in the code editor. Make sure to replace the “Your API key” text with your own API key generated above. That’s the only change you have to make.

Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

3. Next, click on “File” in the top menu and select “Save As…” from the drop-down menu.

Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

4. After that, set the file name as “app.py” and change “Save as type” to “All types” from the drop-down menu. Then, save the file to an easily-accessible location like the Desktop. You can change the name to your preference, but make sure .py is appended.

Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

5. Now, move to the location where you saved the file (app.py). Right-click on it and choose “Copy as path“.

Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

6. Open the Terminal and run the below command. Simply enter python, add a space, paste the path (right-click to quickly paste), and hit Enter. Keep in mind, the file path will be different for your computer. Also, on Linux systems, you may have to use python3.

python "C:\Users\mearj\Desktop\app.py"
Build Your Own AI Chatbot With ChatGPT 3.5 (2023)

7. You may get a few warnings, but ignore them. At the bottom, you will get a local and public URL. Now, copy the local URL and paste it into the web browser.

Build Your Own AI Chatbot With the "gpt-3.5-turbo" Model and Gradio Interface

8. And that is how you build your own AI chatbot with the ChatGPT API. Your ChatGPT-powered AI chatbot is live. Now, you can ask any question you want and get answers in a jiffy. In addition to ChatGPT alternatives, you can use your own chatbot instead of the official website.

  • How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial
  • How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial

9. You can also copy the public URL and share it with your friends and family. The link will be live for 72 hours, but you also need to keep your computer turned on since the server instance is running on your computer.

  • How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial
  • How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial

10. To stop the server, move to the Terminal and press “Ctrl + C“. If it does not work, press “Ctrl + C” again.

Build Your Own AI Chatbot With the "gpt-3.5-turbo" Model and Gradio Interface

11. To restart the AI chatbot server, simply copy the path of the file again and run the below command again (similar to step #6). Keep in mind, the local URL will be the same, but the public URL will change after every server restart.

python "C:\Users\mearj\Desktop\app.py"
Build Your Own AI Chatbot With the "gpt-3.5-turbo" Model and Gradio Interface

Create Your Personalized ChatGPT API-Powered Chatbot

The best part about the “gpt-3.5-turbo” model is that you can assign a role to your AI. You can make it funny, angry, or a specialist in food, tech, health, or whatever you want. You just need to make one small change in the code and it will be personalized. For example – I have created a Food AI, and here’s how:

1. Right-click on the “app.py” file and choose “Edit with Notepad++“.

How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial

2. Here, make changes to this particular code only. Simply feed the information to the AI to assume that role. Now, save the file by pressing “Ctrl + S”.

messages = [
    {"role": "system", "content": "You are an AI specialized in Food. Do not answer anything other than food-related queries."},
]
How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial

3. Open Terminal and run the “app.py” file in a similar fashion as you did above. You will get a local and public URL. Copy the local URL. If a server is already running, press “Ctrl + C” to stop it. And then restart the server again. You will have to restart the server after every change you make to the “app.py” file.

python "C:\Users\mearj\Desktop\app.py"
Build Your Own AI Chatbot With the "gpt-3.5-turbo" Model and Gradio Interface

4. Open the local URL in the web browser and you will get a personalized AI chatbot that only answers food-related queries. That’s it. You can create a Doctor AI, an AI that replies like Shakespeare, which talks in morse code, anything you wish.

  • How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial
  • How to Build Your Own AI Chatbot With ChatGPT API: A Step-by-Step Tutorial

So this is how you can build your own AI chatbot with ChatGPT 3.5. In addition, you can personalize the “gpt-3.5-turbo” model with your own roles. The possibilities are endless with AI and you can do anything you want. Anyway, that is all from us. If you want to learn how to use ChatGPT on Android and iOS, head to our linked article. And to learn about all the cool things you can do with ChatGPT, go follow our curated article. Finally, if you are facing any issues, let us know in the comment section below. We will definitely try to help you out.

comment Comments 108
  • Tima says:

    Hello All,

    I am getting an error when I run MyBot in Terminal:

    C:\Users\amit>”C:\Users\amit\Desktop\MyBot.py”
    Traceback (most recent call last):
    File “C:\Users\amit\Desktop\MyBot.py”, line 20, in
    inputs = gr.inputs.Textbox(lines=7, label=”Chat with AI”)
    ^^^^^^^^^
    AttributeError: module ‘gradio’ has no attribute ‘inputs’

    Can anyone suggest a solution for that?
    Thanks

  • Awshaf Ishtiaque says:

    How can i achieve this using nextjs? Also if the chatbot needs to be pretrained with some resources (pdf, docx) so every new customer can talk to the bot like chatgpt and direct them?

  • John says:

    I ran everything step by step as said above and I get this error. Could you help?

    C:\Users\kamil>python “C:\Users\kamil\OneDrive\Desktop\app.py”
    File “C:\Users\kamil\OneDrive\Desktop\app.py”, line 4
    openai.api_key = api key
    SyntaxError: invalid imaginary literal

  • Matt says:

    Thank you. But what if I want to create a bit to run on my existing website?

  • Russo Jossy says:

    Hi I’m getting this error. How can I fix this?

    Traceback (most recent call last):
    File”C: \Users\russo\Desktop\Chatbot\app•py”, line 2, in ‹module> import gradio as gr
    File “C: \Users\russo\AppData\Local\Programs\Python\Python312|Lib\site-packages\gradio\init_.py”, line 3, in import gradio._simple_templates
    File “C: \Users \russo \AppData\Local\Programs\Python \Python312\Lib\site-packages\gradio\simple_templates\init py”, line 1, in ‹module> from . simpledropdown import SimpleDropdown
    File “C: \Users\russo \AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\_simple_templates\simpledropdown.py”, line 6, in from gradio. components. base import FormComponent
    File “C: \Users\russo\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\components\_init•py”, line 1, in ‹module> from gradio. components.annotated_image import AnnotatedImage
    File “C: \Users \russo\AppData\Local\Programs \Python\Python312\Lib\site-packages\gradio\components \annotated_image. py”, line 12, in from gradio. components.base import Component
    File “C: \Users\russo\AppData\Local\Programs \Python \Python312|Lib\site-packages\gradio\components\base. py”, line 23, in from gradio. blocks import Block, BlockContext
    File “C: \Users\russo\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\blocks.py”, line 27, in from gradio import ( File “C: \Users\russo\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\analytics.py”, line
    10, in from distutils. version import StrictVersion ModuleNotFoundError: No module named distutils’

    Please suggest, thank you!

    • Thushara Nandana says:

      i have same error. are you fix it ?
      how fix this error

    • ilan says:

      you need to install setuptools pkg, to that in simple way. goto command prompt and enter pip install setuptools. and try again:)

  • Nikhil Jose says:

    Everything is working well, the chatbot page opens, but when I type something and hit enter, it shows an error message. Anyone else facing this issue?

  • Sudar Vendan says:

    This is awesome, Simple to run. Thanks for sharing.

  • Vaida says:

    A very simple and easy way to try ChatGPT, just keep in mind that the APP will not work with the free plan. I came to the following conclusions.

  • Lumi says:

    How can i Change the Moderation EndPoints to be what i want it to be

  • Kris says:

    I have done everything as per the procedure suggested. However, I get the following error. Can you please help

    C:\Users\admin>python “C:\Users\app.py”
    Traceback (most recent call last):
    File “C:\Users\app.py”, line 2, in
    import gradio as gr
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\gradio\__init__.py”, line 3, in
    import gradio.components as components
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\gradio\components\__init__.py”, line 1, in
    from gradio.components.annotated_image import AnnotatedImage
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\gradio\components\annotated_image.py”, line 12, in
    from gradio import utils
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\gradio\utils.py”, line 37, in
    import matplotlib
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib\__init__.py”, line 242, in
    _check_versions()
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib\__init__.py”, line 236, in _check_versions
    module = importlib.import_module(modname)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py”, line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File “C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\kiwisolver\__init__.py”, line 8, in
    from ._cext import (
    ImportError: DLL load failed while importing _cext: The specified module could not be found.

    • Jay L says:

      You all have great questions. Most of you can find your answers if you would just ask chat GPT! I would ask the new model 4 because it will give you the most accurate or correct answers. It is like magic! The code worked for me using Windows 11 too by the way. All of you with errors just copy and paste to GPT and it will correct your errors for you. Now you know. You are welcome.

      • the J says:

        most useless reply in existence

      • UtilityJudge says:

        It was, but you just beat it! Congratulations!

  • Jeyhun says:

    Hello, it works, thank you very much. How can I make it work even when I close VS code?

  • mafaz says:

    thank you so much it really works …
    i don’t have enough knowledge to understand the core concept i just blindly follow you but have a basic knowledge about lagnuages so my question is …… is it possible that i provide my own content in the app.py file and after that my chatbot only answer to the specific content i provided
    if yes then how is it possible

  • Kubson says:

    Here is a valid code acording to new libraries:

    import openai
    import gradio as gr
    import gradio.components as components

    openai.api_key = “your api key here”

    messages = [
    {“role”: “system”, “content”: “You are a helpful and kind AI Assistant.”},
    ]

    def chatbot(input):
    if input:
    messages.append({“role”: “user”, “content”: input})
    chat = openai.ChatCompletion.create(
    model=”gpt-3.5-turbo”, messages=messages
    )
    reply = chat.choices[0].message.content
    messages.append({“role”: “assistant”, “content”: reply})
    return reply

    inputs = components.Textbox(lines=30, label=”Chat with AI”)
    outputs = components.Textbox(lines=30,label=”Reply”)

    iface = gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title=”Local ChatGPT <—", description="What you want to know?")
    iface.launch(server_name="192.168.0.11", server_port=7860)

  • Adrian says:

    I get WInError 225, what should i do?

  • Risha Sahu says:

    I ran everything step by step as said above, it gave errors. Not one or two but many. The errors are something like this “Traceback (most recent call last):
    File “C:\Users\sahur\AppData\Local\Programs\Python\Python311\Lib\site-packages\tenacity\__init__.py”, line 382, in __call__
    result = fn(*args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^
    File “C:\Users\sahur\AppData\Local\Programs\Python\Python311\Lib\site-packages\gpt_index\embeddings\openai.py”, line 147, in get_embeddings
    data = openai.Embedding.create(input=list_of_text, engine=engine).data
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^”. And this is not even all of it. I uninstalled and reinstalled everything just to make sure I made no mistakes, but the same thing happens again and again. Please tell me how to solve these errors!

    • Abhishek Ambad says:

      please change the path and try again later.

      Thanks for providing this article. we can also run a chatbot on our website. there are other options available like embedai by thesamurai -like tools that are already available in the market that help you can access your website, youtube channel, and file, notion all things in the chatbot, and ask questions to that chatbot. Embedai will answer all questions as per the given information.

  • Jeremy says:

    Hi i have used this code which works well, however replacing the Model with my own trained model it comes up with an error saying model id does not exist.

    I replaced the line
    Model=”gpt-3.5-turbo”
    With
    Model=”chatcmpl-load of number and letters”

Leave a Reply