How To Implement ChatGPT In Django?


ChatGPT has become very popular these days. People worldwide are using it to build and perform various tasks like interactive chat interfaces. Development is no exception, there are so many developers using this tool to make life easier for them and to develop better applications like advanced chat applications. One such specific use case is implementing ChatGPT in Django. This will allow developers to introduce conversational experiences to the Django application while reducing time to implement for developers.

In this article, we will learn about implementing ChatGPT in a Django application in a detailed, step-by-step form.

What is Django?

Django is a Python Web Framework that lets developers build really fast development of highly secure and easy-to-maintain websites. It is a fully functional framework and comes with a built-in admin interface of its own. Further, it is really easy to switch databases when working with Django. This makes it easy for developers who are working on a codebase or database shift.

What is ChatGPT?

ChatGPT is a model developed by OpenAI and is based on the GPT (Generative Pre-trained Transformer). It is conversational in nature and answers to prompts given by users using knowledge fed to it in its database. Worldwide, people have been using ChatGPT to perform many tasks like content writing, coding, bug finding, e-book writing, etc.

ChatGPT’s base model data is restricted to 2021 only, currently. But, this does not stop us from implementing ChatGPT in a Django Application.

How to implement ChatGPT in a Django Application?

Before getting into the actual implementation, it's better to understand any prerequisites of implementing this application.

Prerequisites

The following are the prerequisites that you would need before starting the Application.

  • Django is installed on the computer.

  • Access to the internet and browser.

  • Access to Open AI API.

Now, we will look at the complete process of implementing ChatGPT in a Django Application

Setting up the Django Project

To set up a Django Project, follow the given steps −

Step 1 − Open the folder where you want to create the project.

Step 2 − Create a Django Project using the following command.

django-admin startproject ProjectName

Step 3 − After this navigate to the Project Folder and create an application.

cd ProjectName
python manage.py startapp appname

Step 4 − We have to set up the settings.py and TEMPLATES folder (if required).

In the settings.py file, you will see a lot of INSTALLED Applications, make sure to include your application in it as well.

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'appname', # add your application here.
]

Step 5 − We will add the static files in the settings.py file now.

STATIC_URL = 'static/'
STATICFILES_DIRS=[
   os.path.join(BASE_DIR, 'appname/static'),
]

Defining a Django view to handle the chat functionality

To create a chat view, we have two functions to create and keep in mind for views.py - get_completed and prompt_view. Let us understand both of these before getting into the implementation.

prompt_view

We are going to create this function for views. We will use this to handle HTTP requests to get with the endpoint. It will get the user prompt as soon as it receives a POST request from the user. This prompt_view function will then call the get_completed function to get an answer for the user prompt. Now, this will gives an output in the form of a JSON file. It will uses the ‘index.html’ template for GET templates.

get_completed

We will use this function to generate a response based on the user prompt. Then, we will implement this using OpenAI API. This function is used to trigger a request to the OpenAI API’s endpoint by mentioning prompts, tokens, temperature, etc. This then, takes the API completion response and gives an output for the function.

The following is the code implementing the two functions.

from django.shortcuts import render
from django.http import JsonResponse
import openai

openai.api_key = 'ADD_YOUR_API_KEY_HERE'

def get_completed(prompt_input):
	print(prompt_input)
	user_prompt = openai.Completion.create(
		engine="text-davinci-003",
		promp_input=prompt_input,
		max_tokens=1024,
		n=1,
		stop=None,
		temperature=0.5,
	)

	api_response = user_prompt.choices[0].text
	print(api_response)
	return api_response

def prompt_view(api_request):
	if api_request.method == 'POST':
		user_prompt = api_request.POST.get('prompt')
		api_response = get_completed(user_prompt)
		return JsonResponse({'response': api_response})
	return render(api_request, 'index.html')

Configuring Django’s URL routing

There are two URL patterns that we will be setting up while configuring Django’s URL routing in urls.py. One of them for the root URL and the other for the admin UI. The root URL is linked to the query_view functions in the views module.

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


urlpatterns = [
	path('admin/', admin.site.urls),
	path('', views.query_view, name='query'),

]

Designing the User Interface

We can create an HTML template in index.html for the chat interface and add the required HTML, Bootstrap, JavaScript, AJAX, CSS, and Bootstrap.

<html>
<head>
	<title>User Prompt</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.0/dist/js.cookie.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css" integrity="sha384-b6lVK+yci+bfDmaY1u0zE8YYJt0TZxLEAFyYSLHId4xoVvsrQu3INevFKo+Xir8e" crossorigin="anonymous">
	<script>
		$(document).ready(function() {
			// Send the form on enter keypress and avoid if shift is pressed
			$('#prompt_input').keypress(function(event) {
				if (event.keyCode === 13 && !event.shiftKey) {
					event.preventDefault();
					$('form').submit();
				}
			});
			$('form').on('submit', function(event) {
				event.preventDefault();
			// get the CSRF token from the cookie
			var csrftoken = Cookies.get('csrftoken');
			
			// set the CSRF token in the AJAX headers
			$.ajaxSetup({
				headers: { 'X-CSRFToken': csrftoken }
			});
				// Get the prompt
				var prompt = $('#prompt_input').val();
				var dateTime = new Date();
				var time = dateTime.toLocaleTimeString();
				// Add the prompt to the response div
				$('#api_response').append('<p>('+ time + ') <i class="bi bi-person"></i>: ' + prompt + '</p>');
				// Clear the prompt
				$('#prompt_input').val('');
				$.ajax({
					url: '/',
					type: 'POST',
					data: {prompt_input: prompt_input},
					dataType: 'json',
					success: function(data) {
						$('#api_response').append('<p>('+ time + ') <i class="bi bi-robot"></i>: ' + data.api_response + '</p>');
					}
				});
			});
		});
	</script>
</head>
<body>
	<div class="container p-3">
		<h3>ChatGPT in Django</h3>
		<div class="mb-3">
			<form method="post">
				<!--{% csrf_token %}-->
				<label for="prompt_input" class="form-label"><strong> Add a Prompt: </strong></label>
				<textarea class="form-control" type="textarea" id="prompt_input" name="prompt_input" rows="3"></textarea>
				<br>
				<button class="btn btn-primary" type="submit">Submit</button>
			</form>
		</div>
		<br>
		<div class="mb-3">
			<h6>Response:</h6>
			<div class="container border overflow-auto h-50" id="api_response"></div>
			
		</div>
	</div>
</body>
</html>

Conclusion

In this article, we learned how to implement ChatGPT in an Django Application. After that we learned and implemented the two main functions for the views. Then, we set up our settings.py and urls.py files as well.

In this way, we can use ChatGPT to create a lot of applications and for Dev purposes. This helps the developers in implementing applications easily. Also, well be able to deliver high-end applications with great UI and features and functions.

Updated on: 23-Jan-2024

25 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements