Create Your Own AI Chatbot in Python: Let’s Build a Mini ChatGPT!

Ever wanted to create your own chatbot like ChatGPT?

Well, you’re in luck! In this post, we’ll guide you step-by-step on how to build a simple AI chatbot using Python.

No prior AI experience is required.

We’ll use Hugging Face's transformers library to load a pre-trained model and create a basic conversational agent.

Ready to build your mini ChatGPT?

Let’s get started!

 

What You Will Learn:

1. Install the required libraries – we’ll show you how to set up your Python environment.

2. Load a pre-trained language model – using Hugging Face’s transformers library to power your chatbot.

3. Create a chatbot that responds intelligently to user input.

4. Add personality – customize your chatbot’s responses to make it more interesting.

 

Step 1: Set Up Your Python Environment

 

Before diving into the code, let’s get our environment ready.

 

1. Install the necessary libraries:

We will be using Hugging Face’s transformers library to handle natural language processing. Open your terminal or command prompt and run the following:

 

 pip install transformers torch

 

This installs the transformers library (for working with the DialoGPT model) and torch (PyTorch, which is used under the hood for neural network operations).

 

2. Optional: You can use a virtual environment to keep your project isolated:

 

 python -m venv chatbot_env

   source chatbot_env/bin/activate  # Mac/Linux

   chatbot_env\Scripts\activate  # Windows

 

Now you're all set!

 

Step 2: Load the Pre-Trained Model

 

Hugging Face’s transformers library provides access to powerful pre-trained models, like GPT-2, which we will use for our chatbot.

 

from transformers import AutoModelForCausalLM, AutoTokenizer

 

# Load the model and tokenizer

model_name = "microsoft/DialoGPT-small"

tokenizer = AutoTokenizer.from_pretrained(model_name)

model = AutoModelForCausalLM.from_pretrained(model_name)

 

In this code:

  • We use AutoModelForCausalLM and AutoTokenizer from Hugging Face's transformers library.

  • AutoTokenizer is used to convert text into a format the model can understand.

  • AutoModelForCausalLM loads the model, in this case, DialoGPT, which is great for conversations.

Step 3: Building the Chatbot

Now that we have the model, let’s create a function to make the chatbot respond to user input.

 

def chat_with_bot(user_input):

    # Encode the input and generate a response

    inputs = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors="pt")

    outputs = model.generate(inputs, max_length=1000, pad_token_id=tokenizer.eos_token_id)

 

    # Decode the output and return the response

    response = tokenizer.decode(outputs[:, inputs.shape[-1]:][0], skip_special_tokens=True)

    return response

 

This function takes the user's input, feeds it into the model, and returns a generated response.

We use `generate` to create the reply, limiting the length of the response to prevent the model from generating an endless answer.

 

Step 4: Chat with the Bot

 

Now, it’s time to interact with your chatbot.

Here's how you can loop the conversation and let users chat with the bot:

 

print("Start chatting with the bot! Type 'quit' to stop.")

 

while True:

    user_input = input("You: ")

 

    if user_input.lower() == 'quit':

        break

 

    response = chat_with_bot(user_input)

    print(f"Bot: {response}")

 

The while loop keeps the conversation going until the user types 'quit'.

The bot responds based on the input it receives and uses the chat_with_bot function to generate a reply.

Sample Response

Step 5: Adding Personality to the Bot

 

If you want your chatbot to have a specific personality, you can "prime" the bot with a prompt that sets the tone for its responses.

For instance, if you want the chatbot to be polite, you can start the conversation with something like this:

 

def chat_with_bot(user_input):

    personality = "You are a very polite and friendly assistant. "

    inputs = tokenizer.encode(personality + user_input + tokenizer.eos_token, return_tensors="pt")

    outputs = model.generate(inputs, max_length=1000, pad_token_id=tokenizer.eos_token_id)

    response = tokenizer.decode(outputs[:, inputs.shape[-1]:][0], skip_special_tokens=True)

    return response

 

Here, we add a personality prompt to the chatbot.

You can adjust this prompt to make the chatbot act like a mentor, a humorous friend, or any other personality type you’d like!

Completed Code on PyCharm

What Have You Achieved?

 

🎉 Congratulations! 

You’ve just built your own AI chatbot! Let’s recap what you’ve learned:

  • You set up Python and installed the transformers library.

  • You loaded a pre-trained conversational model, DialoGPT.

  • You built a chatbot that can interact with users in real-time.

  • You even added some personality to your chatbot by giving it a unique prompt!

Coding with a Smile 🤣 😂

Default Argument Debacle:

Realizing default arguments in functions are mutable is like finding out your perfectly organized sock drawer is actually a time bomb.

Handle with care!

Let’s Inspire Future AI Coders Together! ☕

 

I’m excited to continue sharing my passion for Python programming and AI with you all. If you’ve enjoyed the content and found it helpful, do consider supporting my work with a small gift. Just click the link below to make a difference – it’s quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.

Thank you for being amazing!

What’s Next? 📅

This is just the beginning—feel free to experiment by adding new features like memory (where the bot remembers past conversations), or integrating the bot into a web app using Flask or Django.

Stay tuned for more AI adventures in the next post! 🚀

Ready for More Python Fun? 📬

Subscribe to our newsletter now and get a free Python cheat sheet! 📑 Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.

Keep learning, keep coding 👩‍💻👨‍💻, and keep discovering new possibilities! 💻

Enjoy your journey into artificial intelligence, machine learning, data analytics, data science and more with Python!

Stay tuned for our next exciting project in the following edition!

Happy coding!🚀📊✨