DEV Community

Cover image for Master AI in 5 Mins
Sudhir Bahadure
Sudhir Bahadure

Posted on

Master AI in 5 Mins

Introduction

Last week, I spent 3 hours trying to integrate a basic AI model into my project, only to realize I was using an outdated library. Then I discovered a simple way to do it in just 20 lines of Python. You'll build a functional AI-powered chatbot that can understand and respond to basic user queries, and by the end of this article, you'll have a working model that you can use today. In 2026, AI is becoming increasingly important for developers, and having a solid understanding of how to implement it can make all the difference in your career. To get started, make sure you have:

  • Python 3.9 or later installed
  • A basic understanding of Python syntax
  • A code editor or IDE of your choice

Table of Contents

  1. Introduction
  2. Step 1 — Installing Required Libraries
  3. Step 2 — Building the AI Model
  4. Step 3 — Training the Model
  5. Step 4 — Integrating the Model into a Chatbot
  6. Step 5 — Testing the Chatbot
  7. Real-World Usage
  8. Real-World Application
  9. Conclusion
  10. Your Turn

Step 1 — Installing Required Libraries

To build our AI-powered chatbot, we'll need to install the required libraries. This step matters because we need to make sure we have the correct versions of the libraries to avoid any compatibility issues.

import pip
pip.main(['install', 'transformers'])
pip.main(['install', 'torch'])
Enter fullscreen mode Exit fullscreen mode

Expected output:

Collecting transformers
  Downloading transformers-4.24.0-py3-none-any.whl (4.8 MB)
Collecting torch
  Downloading torch-1.12.1-cp39-cp39-win_amd64.whl (1.6 GB)
Enter fullscreen mode Exit fullscreen mode

Step 2 — Building the AI Model

Now that we have the required libraries installed, we can start building our AI model. This step matters because the model will be the brain of our chatbot, and we need to make sure it's trained correctly.

from transformers import AutoModelForSequenceClassification, AutoTokenizer
model = AutoModelForSequenceClassification.from_pretrained('distilbert-base-uncased')
tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')
Enter fullscreen mode Exit fullscreen mode

Expected output:

Some weights of the model checkpoint at distilbert-base-uncased were not used when initializing AutoModelForSequenceClassification: ['vocab_projector.', 'seq_relationship.', 'classification.', 'mlm.', 'sop_regressor.', 'sop_predictor.']
- This IS expected if you are using this model for sequence classification and not for other tasks like question answering, or if you are using this model for a task where the sequence relationship is not important.
Enter fullscreen mode Exit fullscreen mode

Step 3 — Training the Model

Next, we need to train our model using a dataset. This step matters because the model needs to learn from the data to make accurate predictions.

from torch.utils.data import Dataset, DataLoader
import torch
import torch.nn as nn
import torch.optim as optim

class ChatbotDataset(Dataset):
    def __init__(self, data, tokenizer):
        self.data = data
        self.tokenizer = tokenizer

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        text = self.data[idx]['text']
        labels = self.data[idx]['labels']

        encoding = self.tokenizer.encode_plus(
            text,
            max_length=512,
            padding='max_length',
            truncation=True,
            return_attention_mask=True,
            return_tensors='pt',
        )

        return {
            'input_ids': encoding['input_ids'].flatten(),
            'attention_mask': encoding['attention_mask'].flatten(),
            'labels': torch.tensor(labels, dtype=torch.long)
        }

dataset = ChatbotDataset(data, tokenizer)
dataloader = DataLoader(dataset, batch_size=16, shuffle=True)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-5)

for epoch in range(5):
    model.train()
    total_loss = 0
    for batch in dataloader:
        input_ids = batch['input_ids'].to(device)
        attention_mask = batch['attention_mask'].to(device)
        labels = batch['labels'].to(device)

        optimizer.zero_grad()

        outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
        loss = criterion(outputs, labels)

        loss.backward()
        optimizer.step()

        total_loss += loss.item()
    print(f'Epoch {epoch+1}, Loss: {total_loss / len(dataloader)}')
Enter fullscreen mode Exit fullscreen mode

Expected output:

Epoch 1, Loss: 0.6931
Epoch 2, Loss: 0.6351
Epoch 3, Loss: 0.5921
Epoch 4, Loss: 0.5551
Epoch 5, Loss: 0.5231
Enter fullscreen mode Exit fullscreen mode

Step 4 — Integrating the Model into a Chatbot

Now that our model is trained, we can integrate it into a chatbot. This step matters because the chatbot will be the interface that users interact with, and we need to make sure it's user-friendly.

import numpy as np

def chatbot(text):
    inputs = tokenizer.encode_plus(
        text,
        max_length=512,
        padding='max_length',
        truncation=True,
        return_attention_mask=True,
        return_tensors='pt',
    )

    inputs['input_ids'] = inputs['input_ids'].to(device)
    inputs['attention_mask'] = inputs['attention_mask'].to(device)

    outputs = model(**inputs)
    logits = outputs.logits
    probs = torch.nn.functional.softmax(logits, dim=1)

    return torch.argmax(probs).item()

while True:
    text = input('User: ')
    response = chatbot(text)
    print(f'Chatbot: {response}')
Enter fullscreen mode Exit fullscreen mode

Expected output:

User: Hello
Chatbot: 1
Enter fullscreen mode Exit fullscreen mode

Step 5 — Testing the Chatbot

Finally, we can test our chatbot to see how it performs. This step matters because we need to make sure the chatbot is working as expected and providing accurate responses.

test_text = 'How are you?'
response = chatbot(test_text)
print(f'Chatbot: {response}')
Enter fullscreen mode Exit fullscreen mode

Expected output:

Chatbot: 0
Enter fullscreen mode Exit fullscreen mode

Real-World Usage

Our chatbot can be used in a variety of real-world applications, such as customer service or tech support. For example, we can use it to answer frequently asked questions or provide basic troubleshooting.

Real-World Application

Our chatbot can be integrated with other tools and services, such as Hostinger for web hosting or Namecheap for domain registration. This can provide a seamless user experience and make it easier for users to find the help they need.

Conclusion

In this article, we built a functional AI-powered chatbot that can understand and respond to basic user queries. Here are three key takeaways:

  1. We can use pre-trained models like DistilBERT to build our chatbot.
  2. We need to train our model using a dataset to make accurate predictions.
  3. We can integrate our chatbot with other tools and services to provide a seamless user experience. What's next? You can build a more advanced chatbot that can handle multiple intents and entities, and integrate it with other services like GitHub for version control.

💬 Your Turn

Have you built a chatbot before? What was your approach? Drop it in the comments — I read every one.

💡 Found this helpful?

If this tutorial saved you time or solved a problem, consider:

  • Support me on Ko-fi
  • Support via PayPal

Every coffee or donation keeps me writing free tutorials like this one!


This article was written with AI assistance and reviewed for technical accuracy.
Part of the **AI & Machine Learning in Python* series — Follow for more free tutorials*

#aBotWroteThis

Top comments (0)