AI

How to Create a Chatbot Using Chat-GPT and Python

Get ready to dive into the world of Chat-GPT! Here's how you can set up a conversation and make the magic happen!

How to Create a Chatbot Using Chat-GPT and Python

🌟 Introduction

Get ready to dive into the world of Chat-GPT! Here’s how you can set up a conversation and make the magic happen!

🎨 The Script

Here’s the code to communicate with Chat-GPT through a chat interface using OpenAI and Gradio:

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.components.Textbox(lines=7, label="Chat with AI")
outputs = gr.components.Textbox(label="Reply")

gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Chatbot",
             description="A friendly AI bot by Marco Mignano").launch(share=False)

🎭 Assigning Roles

Let’s break down the various roles in the script:

1. User 🙋‍♂️

  • The User role means you or whoever is chatting with Chat-GPT.
Example (API Request):
{
  "model": "gpt-3.5-turbo",
  "messages": [
   {
      "role": "user",
      "content": "tell me a joke"
   }
  ]
}

2. Assistant 🤖

  • The Assistant role represents the OpenAI server that replies to your questions.
Example (API Response):
{
"id": "chatcmpl-87n798n6bv4678",
"object": "chat.completion",
"created": 1683212418,
"model": "gpt-3.5-turbo-0301",
"usage": {
    "prompt_tokens": 12,
    "completion_tokens": 18,
    "total_tokens": 30
},
"choices": [
    {
        "message": {
            "role": "assistant",
            "content": "why did the chicken cross the road"
        },
        "finish_reason": "stop",
        "index": 0
    }
 ]
}

To continue a conversation with previous context, text from both roles (user + assistant) needs to be sent to the API.

Example (API Request):
{
  "model": "gpt-3.5-turbo",
  "messages": [
   {
      "role": "user",
      "content": "tell me a joke"
   },
   {
      "role": "assistant",
      "content": "why did the chicken cross the road"
   },
   {
      "role": "user",
      "content": "I don't know, why did the chicken cross the road"
   }
  ]
}

3. System 🧠

  • The System role is used by the developer to provide internal instructions for the conversation.
Example (API Request):
{
  "model": "gpt-3.5-turbo",
  "messages": [
   {
      "role": "user",
      "content": "tell me a joke"
   },
   {
      "role": "system",
      "content": "You are an assistant that speaks like Shakespeare."
   }
  ]
}

🥾 Boot Personalization: Tailoring Your AI Experience

Personalizing the boot sequence of your AI chatbot not only allows you to make the interface uniquely yours but can also enhance user interaction by setting specific parameters and behaviors.

Customizing the Welcome Message

You can customize the initial greeting that appears when users start chatting with your AI. Here’s a snippet of code you can use to create a personalized welcome message:

def welcome_message():
    message = "Hello there! I'm your personalized AI chatbot. How can I assist you today?"
    messages.append({"role": "assistant", "content": message})
    return message

welcome_message()

Setting Behavior and Tone

With the System role, you can set specific instructions for how the AI should behave. For example, if you want your AI to speak like Shakespeare, you can instruct it as follows:

{
  "role": "system",
  "content": "You are an assistant that speaks like Shakespeare."
}

🎉 Assign the Model

The line model=gpt-3.5-turbo selects the model for interacting with the chatbot. The list of all available models can be found here.

🚀 Creating the Chat Using Gradio

The following lines define the chat component to interact with AI:

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

gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Chatbot",
             description="A friendly AI bot by Marco Mignano").launch(share=False)

You can learn more about Gradio’s components here.

🏃‍♂️ Running the App

Launch the program and click on the link to interact with the AI. A snapshot of what you’ll see is found

How to Create a Chatbot Using Chat-GPT and Python

Want to share the app with friends? Just change the share flag to True, and you’ll get a URL to copy and share.

How to Create a Chatbot Using Chat-GPT and Python

Remember, the URL is available only for 72 hours, and your PC must host the app during this time.

🏗️ Going Public: Hosting the Chat on a Server with a Public URL

Host your chat on a public server for free! Follow these steps:

  1. Create an account on Hugging Face.
  2. Create a new free space here. How to Create a Chatbot Using Chat-GPT and Python
  3. Select Gradio as the space SDK. How to Create a Chatbot Using Chat-GPT and Python
  4. Upload your repo with the code, making sure the file containing the code is called app.py.

Detailed documentation is available here.

🎈 Conclusion

There you have it! A complete guide to engaging with Chat-GPT. Happy chatting! 🎉

Written by Marco Mignano

Passionate Unity game developer. Coding aficionado, video game enthusiast and self-proclaimed piazza addict. Constantly conquering new challenges, one line of code at a time.