Create Your Own Python AI Chatbot

Faraz

By Faraz - June 14, 2024

Learn how to create a Python AI chatbot with our detailed guide. Follow step-by-step instructions to set up, integrate with RapidAPI, and enhance your chatbot.


create-your-own-python-ai-chatbot.webp

Creating a Python AI chatbot is a rewarding project that blends coding skills with the latest in AI technology. In this guide, we’ll walk you through setting up, coding, and enhancing your very own AI chat bot using Python and RapidAPI’s Simple ChatGPT API.

Table of Contents

  1. Introduction to Python AI Chatbot
  2. Setting Up Your Development Environment
  3. Full AI Chatbot Source Code
  4. Explanation of AI Chatbot Source Code
  5. Conclusion
  6. FAQs

1. Introduction to Python AI Chatbot

AI chatbots are transforming how we interact with technology. From customer service to personal assistants, these bots can handle a variety of tasks. Python, known for its simplicity and robust libraries, is an excellent choice for developing an AI chatbot. In this guide, you'll learn the basics of creating a Python chatbot, integrating AI capabilities, and refining it to improve user interaction.

2. Setting Up Your Development Environment

Installing Python

First, ensure you have Python installed on your machine. You can download it from the official Python website.

Installing Required Libraries

Once your virtual environment is active, install the necessary libraries using pip:

pip install requests pyfiglet

Setting Up RapidAPI for Chatbot Integration

RapidAPI is a marketplace for APIs, offering access to a variety of API services. For this project, we’ll use the Simple ChatGPT API. First, create an account on RapidAPI and subscribe to the Simple ChatGPT API. You will receive an API key, which you’ll need to authenticate your requests.

3. Full AI Chatbot Source Code

import requests
import pyfiglet
import itertools
import threading
import time
import sys

url = "https://simple-chatgpt-api.p.rapidapi.com/ask"


headers = {
    "content-type": "application/json",
    "X-RapidAPI-Key": "OUR API KEY",
    "X-RapidAPI-Host": "simple-chatgpt-api.p.rapidapi.com"
}


def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\r' + c)
        sys.stdout.flush()
        time.sleep(0.1)

    # Clear the console output
    sys.stdout.write('\r')
    sys.stdout.flush()


def ask(question):
    payload = {"question": question}
    response = requests.post(url, json=payload, headers=headers)
    return response.json().get("answer")


if __name__ == "__main__":
    print(pyfiglet.figlet_format("AI Chat BOT"))
    print("Enter the question to ask:")
    print()
    while True:
        # print("/>>  ", end="")
        question = str(input(">>  "))
        if (question == 'q'):
            print(">>  Bye! Thanks for Using...")
            break
        # loading
        done = False
        # here is the animation
        t = threading.Thread(target=animate)
        t.start()
        answer = ask(question)
        time.sleep(5)
        done = True
        t.join()
        print(">> ", answer)
        print()

4. Explanation of AI Chatbot Source Code

Here’s a breakdown of what each part of the code does:

1. Import Statements

import requests
import pyfiglet
import itertools
import threading
import time
import sys
  • requests: For making HTTP requests to the API.
  • pyfiglet: For creating ASCII art from the text, used to display the title.
  • itertools: For creating an iterator used in the loading animation.
  • threading: For running the loading animation in a separate thread.
  • time: For adding delays in the animation.
  • sys: For interacting with the system’s standard output (console).

2. API Configuration

url = "https://simple-chatgpt-api.p.rapidapi.com/ask"

headers = {
    "content-type": "application/json",
    "X-RapidAPI-Key": "OUR API KEY",
    "X-RapidAPI-Host": "simple-chatgpt-api.p.rapidapi.com"
}
  • url: The endpoint for the API that will be used to get answers to questions.
  • headers: The HTTP headers required for the API request, including the API key and host.

3. Loading Animation Function

def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\r' + c)
        sys.stdout.flush()
        time.sleep(0.1)

    # Clear the console output
    sys.stdout.write('\r')
    sys.stdout.flush()
  • animate(): This function creates a simple loading animation that cycles through the characters |, /, -, and \ to give the illusion of a spinning progress indicator.
  • itertools.cycle: Repeats the sequence of characters indefinitely.
  • sys.stdout.write and sys.stdout.flush: Updates the console output with the current character without creating a new line.
  • time.sleep(0.1): Adds a short delay between each character update.

4. Function to Ask Questions

def ask(question):
    payload = {"question": question}
    response = requests.post(url, json=payload, headers=headers)
    return response.json().get("answer")
  • ask(question): Sends the question to the API and returns the answer.
  • payload: The data sent to the API, containing the question.
  • requests.post: Makes a POST request to the API with the payload and headers.
  • response.json().get("answer"): Extracts the answer from the JSON response.

5. Main Program Execution

if __name__ == "__main__":
    print(pyfiglet.figlet_format("AI Chat BOT"))
    print("Enter the question to ask:")
    print()
    while True:
        question = str(input(">>  "))
        if (question == 'q'):
            print(">>  Bye! Thanks for Using...")
            break
        done = False
        t = threading.Thread(target=animate)
        t.start()
        answer = ask(question)
        time.sleep(5)
        done = True
        t.join()
        print(">> ", answer)
        print()
  • pyfiglet.figlet_format("AI Chat BOT"): Displays "AI Chat BOT" in ASCII art.
  • Prompts the user to enter a question or type 'q' to quit.
  • while True: Loop to continually ask for user input until 'q' is entered.
  • question = str(input(">> ")): Gets the user's question.
  • if (question == 'q'): Checks if the user wants to quit.
  • done = False: Indicates the animation should run.
  • threading.Thread(target=animate): Starts the animation in a separate thread.
  • answer = ask(question): Gets the answer from the API.
  • time.sleep(5): Adds a delay to simulate waiting for the response.
  • done = True: Stops the animation.
  • t.join(): Waits for the animation thread to finish.
  • print(">> ", answer): Prints the answer from the API.

5. Conclusion

Creating your own Python AI chatbot with RapidAPI is a rewarding and educational experience. By following this guide, you've learned how to set up your environment, integrate various Python libraries, and build a functional AI chatbot. With further customization and enhancements, the possibilities are endless.

6. FAQs

Q1. What are the prerequisites for building a Python AI chatbot?

You need basic knowledge of Python programming, an internet connection, and a RapidAPI account.

Q2. How can I customize the chatbot's responses?

You can customize responses by modifying the logic in the get_ai_response function and by adding more diverse responses in your chatbot workflow.

Q3. What are some advanced features I can add to my chatbot?

You can add features like sentiment analysis, voice recognition, or integration with other APIs to enhance functionality.

Q4. How can I troubleshoot common issues with my chatbot?

Check for common issues such as incorrect API keys, network connectivity problems, and syntax errors in your code.

Q5. What are some alternatives to RapidAPI for API integration?

Alternatives include using direct API integrations from providers like Google Cloud AI, Microsoft Azure Cognitive Services, and IBM Watson.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺