AI Chatbot with Django

TheHormat
5 min readNov 5, 2024

--

Let’s create a mini gpt using Django and Google Gemini AI :D. We will see and learn how we can use AI and what is the working logic of AI.

First, I’ll ask you to do a little research on Google Gemini API and API Studio. It will be useful to do some analysis on the site itself. Then create an API Key for yourself.

Link to this website: https://ai.google.dev/pricing#1_5flash
Link to a video to analyze: https://www.youtube.com/watch?v=LXBod7UDRqE

Now let’s create our Django project, again I will skip this part without wasting time, because I hope you are already familiar with it.

The only additional package I will download is this “google-generativeai”. I use poetry for package manegment, I recommend it to you. So let’s download this package to our project by typing “poetry add google-generativeai”.

views.py:

from django.shortcuts import render
import google.generativeai as genai
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST


def chatbot_view(request):
return render(request, 'index.html')

genai.configure(api_key="Your API key")

generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}

model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config=generation_config,
system_instruction="precise and concise outputs",
)

@csrf_exempt
@require_POST
def ask_question(request):
question = request.POST.get("question")
if not question:
return JsonResponse({"error": "Question is required"}, status=400)

chat_session = model.start_chat(history=[{"role": "user", "parts": [question]}])
response = chat_session.send_message(question)

return JsonResponse({"answer": response.text})

urls.py:

from django.contrib import admin
from django.urls import path

from home import views

urlpatterns = [
path("admin/", admin.site.urls),
path('', views.chatbot_view, name='chatbot'),
path("ask/", views.ask_question, name="ask_question"),
]

chatbot_view function to show our site to the user. The ask_question function is our code to run the Mini GPT. If you examine the code a bit, we actually wrote the code that Gemini provided us in the documentation. So normally, if you want to run this AI Api in a main.py file, the code is as follows:

main.py:

import os
import google.generativeai as genai

genai.configure(api_key="YOUR_API_KEY")

# Create the model
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}

model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config=generation_config,
system_instruction="precise and concise outputs",
)

chat_session = model.start_chat(
history=[
{
"role": "user",
"parts": [
"How many pizza shopw in New York",
],
},
{
"role": "model",
"parts": [
"I need to be more specific to give you an exact number. The number of pizza shops in New York will vary greatly depending on if you mean:\n\n* **New York City:** This will have the highest concentration of pizza places. \n* **New York State:** This will include a wide range of areas, from cities to small towns.\n\nTo get an accurate number, please tell me:\n\n* **Do you want the number for New York City or New York State?** \n \nOnce I know this, I can do a better job finding the information you need! 🍕 \n",
],
},
]
)

response = chat_session.send_message("essay on ai")

print(response.text)

If you analyze this file code you will already understand. If you pay attention, I didn’t write anything very different in the django view code.

Now let’s finally add our codes for the frontend side and make a nice presentation to the user.

index.html:

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
<div id="chat-container">
<h1>AI Chatbot</h1>
<div id="chat-box">
<!-- User and bot messages will be added here -->
</div>
<div id="loading-indicator">
<span class="dots"></span><span class="dots"></span><span class="dots"></span>
</div>
<form id="chat-form">
<input type="text" id="question" name="question" required placeholder="Ask a question...">
<button type="submit">Send</button>
</form>
</div>

<script>
$(document).ready(function () {
$("#chat-form").on("submit", function (event) {
event.preventDefault();
const question = $("#question").val();

// Show user messages
$("#chat-box").append(`<div class="message user-message">${question}</div>`);
$("#question").val("");

// Bekleme animasyonunu göster
$("#loading-indicator").show();

$.ajax({
url: "/ask/",
method: "POST",
data: {
question: question,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (response) {
// Hide waiting animation
$("#loading-indicator").hide();

// Show bot reply
$("#chat-box").append(`<div class="message bot-message">${response.answer}</div>`);
},
error: function (error) {
$("#loading-indicator").hide();
$("#chat-box").append(`<div class="message bot-message">An error occurred. Please try again.</div>`);
}
});
});
});
</script>
</body>

</html>

style.css:

body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f2f5;
margin: 0;
}

#chat-container {
width: 400px;
max-width: 90%;
background: #ffffff;
border-radius: 8px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
display: flex;
flex-direction: column;
}

h1 {
font-size: 24px;
color: #333;
text-align: center;
}

#chat-box {
display: flex;
flex-direction: column;
gap: 10px;
max-height: 400px;
overflow-y: auto;
padding-bottom: 20px;
border-bottom: 1px solid #ddd;
margin-bottom: 15px;
}

.message {
padding: 10px;
border-radius: 8px;
max-width: 80%;
}

.user-message {
background-color: #dcf8c6;
align-self: flex-end;
}

.bot-message {
background-color: #e8e8e8;
align-self: flex-start;
}

#response-text {
font-size: 14px;
color: #555;
margin-top: 5px;
}

#loading-indicator {
display: none;
color: #777;
font-size: 16px;
align-self: center;
}

.dots {
display: inline-block;
width: 8px;
height: 8px;
margin: 0 2px;
background-color: #777;
border-radius: 50%;
opacity: 0;
animation: blink 1.4s infinite both;
}

.dots:nth-child(1) { animation-delay: 0.2s; }
.dots:nth-child(2) { animation-delay: 0.4s; }
.dots:nth-child(3) { animation-delay: 0.6s; }

@keyframes blink {
0%, 80%, 100% { opacity: 0; }
40% { opacity: 1; }
}

form {
display: flex;
gap: 10px;
}

input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
padding: 10px 15px;
border: none;
border-radius: 4px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}

And with this, our Mini AI Chatbot is ready. Of course, there are many more improvements to be made on this project, and more beautiful and different things can be done using GPT API in the future. With this project, we can take a step forward. I hope it was useful. You can download the project here. I will place the stock you need to install it in the README.md file of the project. If you like the project and it works for you, don’t forget to ⭐️ it. So that it can be in front of more people and most people can benefit from it.

Thanks for reading✨ If you like the article, make sure to:

That’s it from me. We will talk soon!

— Hormat Hamidov♟️

--

--

TheHormat
TheHormat

Written by TheHormat

Full Stack Developer | Instructor | PCEP

Responses (1)