![]() |
|
[Tut] How I Built an OpenAI-Powered Web Assistant with Django - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How I Built an OpenAI-Powered Web Assistant with Django (/thread-100864.html) |
[Tut] How I Built an OpenAI-Powered Web Assistant with Django - xSicKxBot - 03-13-2023 How I Built an OpenAI-Powered Web Assistant with Django 5/5 – (1 vote) Django is a backend web framework that makes it easy to build web pages quickly using Python. There is no better way to learn Django than by building projects. In this tutorial, I will show you how I built an Artificial Intelligence-powered web assistant using Django. Set Up To get started, we will create a directory where every file will live in. In the directory, we will create and activate a virtual environment. Then we will install the required Python libraries for the project. I am using an Ubuntu terminal, so a basic knowledge of the command line will be an added advantage going forward. Code: mkdir project && cd project
python3 -m venv .venv
source .venv/bin/activateIn the project directory, we create and activate a virtual environment using the Code: sourceCode: sourceCode: .Code: pip install django tzdata openaiOnce the installation is complete, run the following command in your Ubuntu terminal to create a Django project. Code: django-admin startproject webassistant .This creates a folder with the name Code: webassistant
We now check to ensure that the installation went successfully. In your terminal run the following command: Code: python3 manage.py runserver![]() Once you have seen the above image, congrats! You have successfully installed Django. You can use Code: control CCreating Django Apps Back to your terminal, run the following command to create a Django app. Code: python3 manage.py startapp assistantUse the Code: lsCode: ls assistant
__init__.py admin.py apps.py migrations models.py tests.py views.pyThe Code: __init__.pyCode: views.pyNext, we go to the Code: settings.pyCode: INSTALLED_APPCode: nanoCode: nano webassistant/settings.pyCode: ...
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom app 'assistant',
]We also open the project’s Code: urls.pyCode: from django.contrib import admin
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('assistant.urls')),
]The Code: path()Code: include()Code: urls.pyIf you have read Django tutorials including this one, you are gradually becoming familiar with the process. That’s how it is done in every Django application. Getting the API Key We need an API key to enable the OpenAI model to perform web assistant tasks for us. To get the API key, we first have to create an account on the official website of OpenAI. Once you have completed the signup process, go to the OpenAI API reference where you will be directed to a page to generate your API key. Recommended: OpenAI API – or How I Made My Python Code IntelligentMake sure you keep the API key safe. Create a file in your app-level folder and call it Code: key.pyCode: API_KEY = 'YOUR SECRET API KEY'Just replace the text in quotes with your own generated API key. Integrating the OpenAI Model To integrate the API with our Django application, create a file called Code: engine.pyCode: # engine.py from .key import API_KEY
import openai openai.api_key = API_KEY def model(request): prompt = request.POST.get('prompt') response = openai.Completion.create( engine='text-davinci-003', temperature=0.5 prompt=prompt, max_tokens=1000, ) text = response.choices[0].text chats = {'prompt': prompt, 'response': text } return chatsWe import the API key and the Code: openaiCode: openai.api_keyThe temperature affects the randomness of the output, and it’s between 0 and 1. The AI model employed to generate predictions is the Code: text_davinci_003.Code: max_tokensTo learn more about the parameters, perhaps this article can be of help. We will now import the function in our Code: views.pyCode: from django.shortcuts import render, redirect
from .engine import model def home(request): try: if request.method == 'POST': context = model(request) return render(request, 'home.html', context) else: return render(request, 'home.html') except: return redirect('error') def error_handler(request): return render(request, 'error.html')Two functions indicate two separate HTML files. In the first function, we use a try statement to check the block of code for errors. If no errors were found, the code under the Code: tryCode: except Recommended: Python Try/Except Error HandlingThe Code: ifCode: POSTCode: elseThe Code: render()Code: elseCode: render()Code: redirect()Let’s now write a URL in the Code: urls.pyCode: assistant/urls.py from django.urls import path
from .import views urlpatterns = [ path('', views.home, name='home'), path('error', views.error_handler, name='error_handler'),
]The Code: nameTemplates We now want to render our templates. Create a folder named Code: templatesCode: settings.pyIn the Code: settings.pyCode: TEMPLATESCode: DIRSCode: …
TEMPLATES = [ { … 'DIRS': [os.path.join(BASE_DIR, 'templates')], … }
]Be sure to import the Code: osCode: base.htmlCode: <!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Web Assistant | {% block title %} {% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body> {% block content %} {% endblock %}
</body>
</html>That’s our HTML boilerplate with bootstrap added to it for styling our web pages. Next is the Code: home.htmlCode: base.htmlCode: {% extends 'base.html' %}
{% block title %} Home {% endblock %}
{% block content %}
<div class="row justify-content-center my-4"> <div class="col-md-7 mt-4"> <div class="card"> <h1 class="card-header text-center">A.I WEB ASSISTANT</h1> <div class="card-body"> <pre>Hello, how can I help you?</pre> <form action="." method="POST"> <!-- this secures the form from malicious attacks during submission --> {% csrf_token %} <input class="form-control mb-2" required type="text" autofocus="autofocus" name="prompt" value="{{ prompt }}" id=""> <button class="btn btn-success fw-bold" type="submit"> GENERATE </button> </form> <hr> <pre> {{ response }} </pre> </div> </div> </div> </div>
</div>
{% endblock %}![]() Finally, the Code: error.htmlCode: base.htmlCode: {% extends 'base.html' %}
{% block title %} 404 {% endblock %}
{% block content %}
<div class="row justify-content-center my-4"> <div class="col-md-7 mt-4"> <h1>Page Not Found</h1> <p>Make sure you are connected to the internet or your query is correct</p> <a href="{% url 'home' %}" class="btn btn-secondary">Home</a> </div>
</div>
{% endblock %}![]() Certain things in these HTML files demand an explanation. Those strange syntaxes that begin with curly braces are Django templating language. When used with a Code: blockCode: endblockCode: base.htmlThis makes it possible to override the home and error HTML files with a different word. But you can see the ‘Web Assistant’ remains the same in all files inheriting Code: base.htmlThe Code: csrf_tokenCode: view.pyCode: engine.pyCode: render()The Code: {% url 'home' %}Code: urls.py![]() Conclusion Congrats on creating an AI-powered web assistant using Django. If you enjoy the tutorial, feel free to share it with others. Have a nice day. Recommended: How I Created an URL Shortener App Using Django
|